SQL Tutorial
In SQL, the LIKE
operator is used in a WHERE
clause to search for a specified pattern in a column.
There are two wildcards that are used in conjunction with the LIKE
operator:
%
: The percent sign represents zero, one, or multiple characters_
: The underscore represents a single characterThe syntax for the LIKE
operator is as follows:
SELECT column1, column2, ... FROM table_name WHERE columnN LIKE pattern;
Examples:
Consider the following Employees
table:
EmployeeID | FirstName | LastName |
---|---|---|
1 | John | Doe |
2 | Jane | Smith |
3 | Alice | Johnson |
4 | Charlie | Brown |
5 | David | Thompson |
SELECT * FROM Employees WHERE FirstName LIKE 'J%';
This will return all employees where the first name begins with "J".
SELECT * FROM Employees WHERE LastName LIKE '%son';
This will return all employees where the last name ends with "son".
SELECT * FROM Employees WHERE FirstName LIKE '%hn%';
This will return all employees where the first name contains "hn" in any position.
SELECT * FROM Employees WHERE FirstName LIKE 'A__%';
This will return all employees where the first name starts with "A" and is at least 3 characters long.
Remember that the LIKE
operator is case insensitive in some databases. If you need a case sensitive search, look at the specific SQL dialect documentation for information. For example, in MySQL, the LIKE
operator is case insensitive, but the case sensitivity of string comparisons can be changed using the BINARY
keyword or by changing the collation of your database, table, or column.
Using Wildcard Characters in SQL LIKE:
SELECT * FROM table WHERE column_name LIKE 'pattern%';
SQL LIKE vs Equals for Pattern Matching:
-- Exact match SELECT * FROM table WHERE column_name = 'exact_value'; -- Fuzzy match with LIKE SELECT * FROM table WHERE column_name LIKE 'partial_value%';
Case-Insensitive Matching with SQL LIKE:
LOWER
or UPPER
functions.SELECT * FROM table WHERE LOWER(column_name) LIKE 'pattern%';
Combining Wildcard Characters in SQL LIKE:
SELECT * FROM table WHERE column_name LIKE 'start%middle_ending';
Escaping Special Characters in SQL LIKE:
SELECT * FROM table WHERE column_name LIKE 'special\_pattern%' ESCAPE '\';
SQL LIKE with Multiple Conditions:
SELECT * FROM table WHERE column1 LIKE 'pattern%' AND column2 LIKE '%another_pattern%';
Examples of Fuzzy Matching with SQL LIKE:
-- Matching names starting with 'John' SELECT * FROM employees WHERE employee_name LIKE 'John%'; -- Finding products with 'apple' anywhere in the name SELECT * FROM products WHERE product_name LIKE '%apple%'; -- Searching for email addresses ending with 'company.com' SELECT * FROM contacts WHERE email LIKE '%@company.com';