LIKE tests text against a pattern rather than an exact value. It goes in a WHERE clause, and the pattern uses two wildcards:
%matches any run of characters, including none at all._matches exactly one character.
SELECT column1, column2FROM table_nameWHERE column1 LIKE pattern;The examples use the Productions table from the example database.
Starts with, ends with, contains
Section titled “Starts with, ends with, contains”Titles that start with S:
SELECT Title FROM ProductionsWHERE Title LIKE 'S%';| Title |
|---|
| Saltmarsh |
| Six Bells |
Titles that end with s:
SELECT Title FROM ProductionsWHERE Title LIKE '%s';| Title |
|---|
| The Lantern Keepers |
| Six Bells |
Titles that contain “ar” anywhere:
SELECT Title FROM ProductionsWHERE Title LIKE '%ar%';| Title |
|---|
| Quarry Lane |
| Saltmarsh |
One character at a time
Section titled “One character at a time”Each _ stands for exactly one character, so '_a%' means “any first letter, then a, then anything”:
SELECT Title FROM ProductionsWHERE Title LIKE '_a%';| Title |
|---|
| Saltmarsh |
NOT LIKE
Section titled “NOT LIKE”NOT LIKE keeps the rows that do not match. Titles that do not begin with “The “:
SELECT Title FROM ProductionsWHERE Title NOT LIKE 'The %';| Title |
|---|
| Quarry Lane |
| Saltmarsh |
| Six Bells |
| Fennick’s Return |
Patterns at a glance
Section titled “Patterns at a glance”| Pattern | Matches values that |
|---|---|
'S%' |
start with S |
'%s' |
end with s |
'%ar%' |
contain “ar” anywhere |
'_a%' |
have a as the second character |
'S__%' |
start with S and are at least three characters long |
'S%l' |
start with S and end with l |
Microsoft Access and SQL Server offer more wildcards than these two; SQL Wildcards lists them.