The LIKE command in SQL is used to search for a pattern within a text/string column. It’s very useful when you don’t want an exact match but want to find strings that follow a certain pattern. Here’s a clear breakdown:
Basic Syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern';
column_name→ the column you want to search.'pattern'→ the text pattern you are looking for.- Patterns are case-insensitive in some DBs (like MySQL with default collation) or case-sensitive in others (like PostgreSQL).
Wildcards
LIKE uses wildcards to define flexible patterns:
| Wildcard | Meaning | Example |
|---|---|---|
% | Any number of characters (including zero) | 'a%' → anything starting with a |
_ | Exactly one character | 'a_' → ab, ac but not abc |
Examples
- Find names starting with ‘J’
SELECT name
FROM users
WHERE name LIKE 'J%';
Matches: John, Jane, Jack
Does not match: Bob, alice
- Find names ending with ‘n’
SELECT name
FROM users
WHERE name LIKE '%n';
Matches: John, Ethan
Does not match: Jane, Bob
- Find names with exactly 4 letters
SELECT name
FROM users
WHERE name LIKE '____';
Matches: John, Mary
Does not match: Ethan (5 letters)
- Find names containing ‘ar’ anywhere
SELECT name
FROM users
WHERE name LIKE '%ar%';
Matches: Mary, Carol
Does not match: John, Bob
Leave a Reply