Skip to content
  • LIKE & Pattern Matching · SQL

LIKE & Pattern Matching

LearnViaNotes @learnvianotes· 2 min read

LIKE matches text against a simple pattern with two wildcards; regular expressions are available as dialect extensions.

WildcardMatchesExampleMatches…
%Any sequence of 0+ characters'A%'Asha, Arjun
_Exactly one character'_a%'Ravi, Karan, Sara (second letter a)
SQL
SELECT name FROM employees WHERE name LIKE 'A%'   ORDER BY name;
SELECT name FROM employees WHERE name LIKE '_a%'  ORDER BY name;
SELECT name FROM employees WHERE name LIKE '%an%' ORDER BY name;
Output
name
-----
Arjun
Asha

name
-----
Karan
Ravi
Sara

name
-----
Karan

Case sensitivity

SQLite's LIKE is case-insensitive for ASCII letters; PostgreSQL's LIKE is case-sensitive (use ILIKE); MySQL/SQL Server follow the column collation (usually insensitive). Portable trick: compare lowercased values.

SQL
SELECT name FROM employees WHERE name LIKE 'a%' ORDER BY name;              -- SQLite: matches A
SELECT name FROM employees WHERE name GLOB 'a*' ORDER BY name;              -- GLOB: case-sensitive
SELECT name FROM employees WHERE lower(name) LIKE 'a%' ORDER BY name;       -- portable
Output
name
-----
Arjun
Asha

name
----

name
-----
Arjun
Asha

Matching a literal % or _

SQL
CREATE TABLE promos (code TEXT);
INSERT INTO promos VALUES ('SAVE10%'), ('SAVE10'), ('FLAT_50'), ('FLATX50');

SELECT code FROM promos WHERE code LIKE '%\%' ESCAPE '\' ORDER BY code;
SELECT code FROM promos WHERE code LIKE 'FLAT\_%' ESCAPE '\' ORDER BY code;
SELECT code FROM promos WHERE code LIKE 'FLAT_%' ORDER BY code;          -- _ is a wildcard!
Output
code
-------
SAVE10%

code
-------
FLAT_50

code
-------
FLATX50
FLAT_50

Regular expressions (dialects)

PostgreSQL / MySQL / Oracle
SELECT name FROM employees WHERE name ~ '^[AEIOU]';          -- PostgreSQL (~* = case-insensitive)
SELECT name FROM employees WHERE name REGEXP '^[AEIOU]';     -- MySQL
SELECT name FROM employees WHERE REGEXP_LIKE(name, '^[AEIOU]');  -- Oracle / MySQL 8

Find names that start and end with a vowel.

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report