When searching for names, product titles, or addresses, users rarely search for exact complete strings. Instead, they search for prefixes, substrings, or patterns. The LIKE operator combined with SQL Wildcards provides powerful text pattern matching capabilities directly within the database engine.
| Wildcard | Meaning | Example Pattern & Matching Strings |
|---|---|---|
| % (Percent) | Matches zero or more characters of any type. | 'A%' matches 'Aman', 'Amit', 'Ananya', or 'A'.'%com' matches 'google.com', 'veewom.com'. |
| _ (Underscore) | Matches exactly one single character. | 'R_j' matches 'Raj', 'Roj', 'Ruj' (not 'Raaj').'____' matches any exactly 4-letter string. |
-- 1. Find all students whose first name starts with 'A'
SELECT student_id, first_name, email
FROM students
WHERE first_name LIKE 'A%';
-- 2. Find all students whose email is on gmail.com
SELECT student_id, first_name, email
FROM students
WHERE email LIKE '%@gmail.com';
-- 3. Find students whose first name has 'a' as the second character
SELECT student_id, first_name
FROM students
WHERE first_name LIKE '_a%';
-- 4. Find students whose name contains 'an' anywhere
SELECT student_id, first_name
FROM students
WHERE first_name LIKE '%an%';
If your database stores literal percentage signs (e.g., '10% discount') or underscores (e.g., 'order_101'), define an explicit escape character:
-- Search for literal discount string containing '%'
SELECT product_name, discount_label
FROM products
WHERE discount_label LIKE '%10!%%' ESCAPE '!';
Next, let us learn how to filter sets and numeric ranges using SQL IN & BETWEEN Operators!
% matches zero, one, or multiple characters. _ matches exactly one single character.
A leading wildcard (%john) prevents the database optimizer from using a standard B-Tree index because the starting characters are unknown, forcing a Full Table Scan. A trailing wildcard (john%) can leverage an index range scan.
Use the ESCAPE keyword to define an escape character: WHERE code LIKE '%!%%' ESCAPE '!' treats the second percent sign as a literal character.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 24: IN & BETWEEN → Previous: ← DELETE Statement | Full Syllabus
Applying text pattern matching in row filtering.
Transforming text cases with UPPER/LOWER for comparisons.
Replacing slow LIKE %term% table scans with Inverted Indexes.
Why LIKE "%keyword" cannot use standard B-tree indexes.