Pattern matching with LIKE
= only finds exact matches. LIKE finds text that fits a pattern.
The two wildcards
| Wildcard | Means | Pattern | Would match |
|---|---|---|---|
% | any number of characters, even none | 'L%' | Liam, Lucas, L |
_ | exactly one character | '_a%' | Maya, Ravi, Hana |
Starts with, ends with, contains
SQL
SELECT name FROM customers WHERE name LIKE 'L%'; -- starts with LSQL
SELECT name FROM customers WHERE name LIKE '%n'; -- ends with nSQL
SELECT name FROM products WHERE name LIKE '%or%'; -- contains "or"Exactly one character: _
Cities with exactly five letters:
SQL
SELECT name, city
FROM customers
WHERE city LIKE '_____';First names whose second letter is "a":
SQL
SELECT first_name, last_name
FROM employees
WHERE first_name LIKE '_a%';Upper and lower case
In SQLite, LIKE ignores case for English letters, so '%monitor%' finds the 27" Monitor:
SQL
SELECT name FROM products WHERE name LIKE '%monitor%';Databases differ here. MySQL usually ignores case too (it depends on the column's collation), while PostgreSQL's LIKE is case-sensitive and offers ILIKE for case-insensitive matching. A portable way to ignore case is to lower-case the column: WHERE LOWER(name) LIKE '%monitor%'.
NOT LIKE
SQL
SELECT first_name, title
FROM employees
WHERE title NOT LIKE '%Engineer%';Searching for a literal % or _
To match the % character itself, pick an escape character with ESCAPE and put it in front of the wildcard:
SQL
SELECT
'50% off' LIKE '%\%%' ESCAPE '\' AS has_percent,
'Half off' LIKE '%\%%' ESCAPE '\' AS also_has_percent;The answers are 1 (true) and 0 (false): SQLite shows true and false as numbers.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.