Pattern Matching in SQL
o LIKE clause is used to perform the pattern matching task in SQL.
o A WHERE clause is generally preceded by a LIKE clause in an SQL query.
o LIKE clause searches for a match between the patterns in a query with the pattern in
the values present in an SQL table. If the match is successful, then that particular
value will be retrieved from the SQL table.
o LIKE clause can work with strings and numbers.
The LIKE clause uses the following symbols known as wildcard operators in SQL to
perform this pattern-matching task in SQL.
1. To represent zero, one or more than one character, % (percentage) is used.
2. To represent a single character _ (underscore) is used.
Let us start with the syntax of a LIKE clause:
1. SELECT ColumnName1, ColumnName2 FROM TableName WHERE ColumnName
LIKE [Expression];
Here, Expression refers to the pattern which we want to search for in the values of a
table. This expression will include the wildcard operators such as '%' and '_'.
Example
Select all customers that starts with the letter "a":
SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
Example
Return all customers from a city that contains the letter 'L':
SELECT * FROM Customers WHERE city LIKE '%L%';
Example
Return all customers that starts with 'La':
SELECT * FROM Customers WHERE CustomerName LIKE 'La%';
Example
Return all customers that starts with 'a' or starts with 'b':
SELECT * FROM Customers WHERE CustomerName LIKE 'a
%' OR CustomerName LIKE 'b%';
Example
Return all customers that ends with 'a':
SELECT * FROM Customers WHERE CustomerName LIKE '%a';
Example
Return all customers that starts with "b" and ends with "s":
SELECT * FROM Customers WHERE CustomerName LIKE 'b%s';