Wildcards
Wildcards are special characters used with the LIKE operator to search for patterns within text data, instead of requiring an exact match.
The Two Main Wildcards
- % - matches zero, one, or many characters
- _ - matches exactly one character
Using LIKE with %
-- Names starting with "Ri"
SELECT * FROM customers WHERE first_name LIKE 'Ri%';
-- Emails ending in "@gmail.com"
SELECT * FROM customers WHERE email LIKE '%@gmail.com';
-- Names containing "an" anywhere
SELECT * FROM customers WHERE first_name LIKE '%an%';
Using LIKE with _
-- Four-letter names starting with "R"
SELECT * FROM customers WHERE first_name LIKE 'R___';
Case Sensitivity
Whether LIKE is case-sensitive depends on the database system and its configured collation - MySQL is typically case-insensitive by default, while PostgreSQL's LIKE is case-sensitive (use ILIKE there instead).
Wildcard searches starting with % (like '%an%') can be slow on large tables since the database can't use a standard index efficiently - use them thoughtfully in performance-sensitive queries.