MySQL Tutorial
LIKE
OperatorThe LIKE
operator is used for pattern matching in WHERE
clauses, helping you search for text-based data using wildcards.
LIKE
Wildcard |
Description |
---|---|
% |
Matches zero or more characters. |
_ |
Matches exactly one character. |
SELECT column_names FROM table_name WHERE column_name LIKE 'pattern';
Here are some examples showing different LIKE
operators with '%' and '_' wildcards:
Pattern |
Description |
Matches Examples |
---|---|---|
'A%' |
Starts with "A" |
Alice, Andrew, Adam |
'%n' |
Ends with "n" |
John, Ethan, Megan |
'%an%' |
Contains "an" anywhere |
Daniel, Jonathan, Mandy |
'____y' |
Exactly 5 characters, ending in "y" |
Emily, Jenny, Daisy |
'%son' |
Ends with "son" |
Jackson, Anderson |
'_o%' |
"o" as the second character |
Tom, Tony, Bob |
CAST(name AS BINARY) LIKE 'David%' |
Case-sensitive, starts with "David" |
David (not david or DAVID) |
'%\_admin%' |
Search for "_admin" (escape |
super_admin, user_admin |
Below is a selection from the "Students" table in the school_db database:
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
The following SQL statement selects all students with a name starting with "A":
The following SQL statement selects all students with a name ending with "e":
The following SQL statement selects all students with a name that have "an" in any position:
The following SQL statement selects all studenst with a name that have "o" in the second position:
The following SQL statement selects all studenst with a name that starts with "a" and are at least 3 characters in length:
The following SQL statement selects all studenst with a name that starts with "a" and ends with "e":
The following SQL statement selects all students with a name that does NOT start with "J":
The following SQL statement selects all students with a name that starts with case senstive "David":
Note
By default, LIKE
is case-insensitive in MySQL.