✏️ Explanatory Question
Level: Basic to Intermediate — Essential for pattern-based searching in text columns.
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column, rather than an exact match. It works together with two wildcard characters.
BINARY keyword: WHERE name LIKE BINARY 'R%'.
| Pattern | Meaning | Matches |
|---|---|---|
'R%' |
Starts with R | Rumman, Rita, Rohan |
'%an' |
Ends with "an" | Rohan, Milan |
'%mm%' |
Contains "mm" | Rumman, Sammy |
'_a%' |
2nd letter is "a" | Ram, Kate |
'R____' |
R + exactly 4 chars | Rohan, Rumia |
To search for a literal % or _, use the ESCAPE clause:
-- Find values that literally contain a '%' sign
SELECT * FROM products
WHERE discount LIKE '%50\%%' ESCAPE '\\';
'%an') cannot use an index, forcing a full table scan. Prefer patterns like 'R%' that allow index usage.
-- Names starting with 'R'
SELECT * FROM employees WHERE name LIKE 'R%';
-- Emails ending in '@gmail.com'
SELECT * FROM users WHERE email LIKE '%@gmail.com';
-- Names where the second character is 'a'
SELECT * FROM employees WHERE name LIKE '_a%';
-- NOT LIKE: exclude a pattern
SELECT * FROM employees WHERE name NOT LIKE 'A%';