SQL LIKE Keyword
The LIKE
operator in SQL is used to search for a pattern within a column. It's incredibly useful for finding rows where a string column matches a specific pattern, allowing for flexible and efficient searches.
LIKE: Definition and Usage
LIKE
is used within the WHERE
clause of a SELECT
statement (or other data retrieval statements). It uses wildcard characters to match patterns, making it much more powerful than a simple equality check.
Wildcard Characters
%
: Matches any sequence of zero or more characters._
: Matches any single character. (MS Access uses?
instead of_
)
Syntax
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE 'pattern';
Examples
Selecting Customers Whose Names Start with "a"
This query finds all customers whose names begin with the letter "a".
Syntax
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Output
(All rows where CustomerName starts with 'a' will be returned)
Selecting Customers Whose Names End with "a"
This query selects customers whose names end with "a".
Syntax
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Output
(All rows where CustomerName ends with 'a' will be returned)
Selecting Customers Whose Names Contain "or"
This query finds customers with "or" anywhere in their name.
Syntax
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Output
(All rows where CustomerName contains 'or' will be returned)
Selecting Customers Whose Names Start with "a" and are at least 3 characters long
This query demonstrates using multiple wildcards. It finds names starting with 'a', followed by at least two more characters.
Syntax
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
Output
(All rows where CustomerName starts with 'a' and is at least 3 characters long will be returned)