SQL LIKE
LIKE matches text against a simple pattern. It is used in WHERE to find values that start with, end with or contain something.
SELECT columns
FROM table_name
WHERE column LIKE pattern;Two wildcards build the patterns:
| Wildcard | Matches |
|---|---|
% |
any sequence of characters, including none |
_ |
exactly one character |
Starts with
SELECT name FROM products WHERE name LIKE 'C%' ORDER BY name;name
---------------
Cast Iron Pan
Chai Latte Mix
Chef Knife
Cherry Tomatoes
Chocolate Cake
Coffee Grinder
(6 rows)
Ends with
SELECT name, city FROM customers WHERE name LIKE '%Books' OR name LIKE '%Bytes' ORDER BY name;name | city
----------------+---------
Bright Bytes | Paris
Night Owl Books | New York
(2 rows)
Contains
% on both sides finds the text anywhere:
SELECT name FROM products WHERE name LIKE '%chocolate%' ORDER BY name;name
------------------
Chocolate Cake
Dark Chocolate Bar
(2 rows)
Notice that '%chocolate%' matched "Chocolate Cake" and "Dark Chocolate Bar" even though they are capitalised.
Case sensitivity
| Database | Is LIKE case-sensitive? |
|---|---|
| SQLite | No for ASCII letters (A–Z) |
| MySQL | Depends on the collation; usually no |
| PostgreSQL | Yes — use ILIKE for case-insensitive |
| SQL Server | Depends on the collation; usually no |
Exactly N characters with _
Each _ stands for exactly one character. Cities with exactly four letters:
SELECT DISTINCT city FROM customers WHERE city LIKE '____' ORDER BY city;city
----
Oslo
Rome
(2 rows)
Combine both wildcards: names whose second letter is a:
SELECT first_name FROM employees WHERE first_name LIKE '_a%' ORDER BY first_name;first_name
----------
Hana
Marco
(2 rows)
NOT LIKE
NOT LIKE keeps the rows that do not match. Products whose name is a single word (contains no space):
SELECT name
FROM products
WHERE name NOT LIKE '% %'
ORDER BY name;name
--------
Apples
Avocados
Bagels
Bananas
(4 rows)
Remember that NULL values match neither LIKE nor NOT LIKE; add OR col IS NULL if you want them.
Tip: A pattern starting with
%(like'%Books') cannot use an index, so the database must check every row. On large tables, prefer "starts with" searches or a full-text index.
Test yourself
Which pattern finds names that end with 'Cafe'?
- 'Cafe%'
- '%Cafe'
- '_Cafe'
- '%Cafe%'
How many characters does _ match?
- Zero or more
- Exactly one
- One or more
- Zero or one
In PostgreSQL, how do you match text case-insensitively?
- LIKE
- ILIKE
- NOCASE
- MATCH