SQL LIKE
Operator
The LIKE operator is used to search for a specified pattern in a column within the WHERE clause.
SQL LIKE Operator
The LIKE operator is used to search for a specified pattern in a column within the WHERE clause.
SQL LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column LIKE pattern;
Parameter explanations:
column1, column2, ...: The names of the fields to select. Multiple fields can be specified. If no field names are specified, all fields will be selected.
table_name: The name of the table to query.
column: The name of the field to search.
pattern: The search pattern.
Demonstration Database
In this tutorial, we will use the tutorialpro sample database.
Below is data selected from the "Websites" table:
mysql> SELECT * FROM Websites;
+----+---------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+---------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | tutorialpro.org | http://www.tutorialpro.org/ | 5000 | USA |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
SQL LIKE Operator Examples
The following SQL statement selects all customers where the name starts with the letter "G":
Example
SELECT * FROM Websites
WHERE name LIKE 'G%';
Execution output:
Note: The "%" symbol is used to define wildcards (default letters) before and after the pattern. You will learn more about wildcards in the next chapter.
The following SQL statement selects all customers where the name ends with the letter "k":
Example
SELECT * FROM Websites
WHERE name LIKE '%k';
Execution output:
The following SQL statement selects all customers where the name contains the pattern "oo":
Example
SELECT * FROM Websites
WHERE name LIKE '%oo%';
Execution output:
By using the NOT keyword, you can select records that do not match the pattern.
The following SQL statement selects all customers where the name does not contain the pattern "oo":
Example
SELECT * FROM Websites
WHERE name NOT LIKE '%oo%';
Execution output: