In MySQL, the LIKE operator is used in the WHERE clause of a SELECT, UPDATE, DELETE or INSERT statement to perform pattern matching on a string column.
The basic syntax of the LIKE operator is:
SELECT column1, column2, ... FROM table_name WHERE column_name LIKE pattern;
Here, column_name
is the name of the string column on which you want to perform pattern matching, table_name
is the name of the table where the column exists, and pattern
is the pattern that you want to match.
The pattern
can include the following special characters:
%
: matches any string of zero or more characters._
: matches any single character.[character_list]
: matches any single character from the list of characters.[^character_list]
: matches any single character not in the list of characters.
For example, to find all rows in a table called employees
where the last_name
column starts with the letter “S”, you would use the following query:
SELECT * FROM employees WHERE last_name LIKE 'S%';
This would return all rows where the last_name
column starts with the letter “S”.
Similarly, to find all rows where the first_name
column ends with the letter “a”, you would use the following query:
SELECT * FROM employees WHERE first_name LIKE '%a';
This would return all rows where the first_name
column ends with the letter “a”.
You can also use the LIKE
operator with the NOT
keyword to perform a negative match. For example, to find all rows where the first_name
column does not contain the letter “a”, you would use the following query:
SELECT * FROM employees WHERE first_name NOT LIKE '%a%';
This would return all rows where the first_name
column does not contain the letter “a”.