Pattern matching

Topic 1 of 5 in Working with values10 min readBeginnerFree course

Overview

= finds exact matches, but people rarely search that way. They type part of a name, the start of an email, or a word they half-remember. SQL’s answer is pattern matching: the LIKE operator with two simple wildcards, and — in PostgreSQL — full regular expressions when you need more power.

LIKE and its two wildcards

LIKE compares text with a pattern. Most characters in the pattern match themselves; two are special:

  • % matches any sequence of characters, including none;
  • _ matches exactly one character.

Pattern matching with LIKE. ‘Tea%’ means starts with Tea: it matches Tea and Teapot but not Green Tea. ‘%Tea’ means ends with Tea: it matches Green Tea but not Teapot. ‘%tea%’ means contains tea, case-sensitive: it matches Steam and Glass teapot but not Glass Teapot. ‘_ean’ means exactly one character then ean: it matches Bean and bean but not Clean. ILIKE ‘%tea%’ means contains tea in any case: it matches Glass Teapot and TEA but not Coffee. % matches any run of characters, including none; _ matches exactly one character. LIKE is case-sensitive in PostgreSQL and ILIKE ignores case; for complex patterns use regular expressions, ~ and ~*. A leading %, as in LIKE ‘%tea’, can’t use a normal index, so it reads every row.

Products whose name starts with “C”:

SQL
SELECT name FROM products WHERE name LIKE 'C%';
Text
       name        
-------------------
 Colombian Supremo
 Chamomile Calm
(2 rows)

Ends with “er”:

SQL
SELECT name FROM products WHERE name LIKE '%er';
Text
       name        
-------------------
 Pour-Over Dripper
 Burr Grinder
(2 rows)

Contains “ea” anywhere:

SQL
SELECT name FROM products WHERE name LIKE '%ea%';
Text
      name       
-----------------
 Assam Breakfast
 Glass Teapot
(2 rows)

Breakfast and Teapot both contain “ea”; Darjeeling doesn’t — it has “ee”.

Case: LIKE versus ILIKE

In PostgreSQL, LIKE is case-sensitive. Search for “tea” in lower case and the teapot isn’t found, because its name has a capital T:

SQL
SELECT name FROM products WHERE name LIKE '%tea%';
Text
 name 
------
(0 rows)

ILIKE (insensitive LIKE) ignores case:

SQL
SELECT name FROM products WHERE name ILIKE '%tea%';
Text
     name     
--------------
 Glass Teapot
(1 row)

ILIKE is a PostgreSQL extension. The portable way, which works in every database, is to lower-case both sides:

SQL
SELECT name FROM products WHERE lower(name) LIKE '%tea%';
Text
     name     
--------------
 Glass Teapot
(1 row)

Other databases: MySQL and SQL Server usually compare text case-insensitively by default, so LIKE already ignores case there. SQLite’s LIKE ignores case for ASCII letters. Check before relying on either behaviour.

The single-character wildcard

_ stands for exactly one character, so you can match by length or position:

SQL
SELECT first_name FROM customers WHERE first_name LIKE '___';
Text
 first_name 
------------
 Ben
 Dee
(2 rows)

Three underscores: first names exactly three characters long. Mix the wildcards for more specific patterns — here, any email whose second letter is “a”:

SQL
SELECT email FROM customers WHERE email LIKE '_a%';
Text
          email          
-------------------------
 farhan.ali@example.com
 jack.wilson@example.com
(2 rows)

NOT LIKE, and LIKE without wildcards

NOT LIKE keeps the rows that don’t match:

SQL
SELECT name FROM products
WHERE category_id = 2 AND name NOT LIKE '% %';
Text
 name 
------
(0 rows)

'% %' means “contains a space”, so NOT LIKE '% %' finds single-word names — and every tea has at least two words. (No rows is a perfectly good answer.)

A pattern with no wildcards matches only the exact text, so name LIKE 'Gift Card' is the same as name = 'Gift Card'. Use = when that’s what you mean; it’s clearer.

Matching a literal % or _

What if the text itself contains % or _ — say, you’re searching for “50%” in a product description? Put a backslash in front of the wildcard to make it literal:

SQL
SELECT '50% off'  LIKE '50\% off'  AS escaped_percent,
       '50 % off' LIKE '50% off'   AS wildcard_percent,
       'a_b'      LIKE 'a\_b'      AS escaped_underscore,
       'axb'      LIKE 'a\_b'      AS underscore_no_match;
Text
 escaped_percent | wildcard_percent | escaped_underscore | underscore_no_match 
-----------------+------------------+--------------------+---------------------
 t               | t                | t                  | f
(1 row)

The first column is true because \% matched a real percent sign. The second shows why escaping matters: unescaped, % is a wildcard, so the pattern also matches “50 % off” — the % simply swallowed the extra characters. If backslashes are awkward (they’re common in file paths), choose your own escape character: LIKE '50!% off' ESCAPE '!'.

Regular expressions

For anything more complex, PostgreSQL supports POSIX regular expressions:

Operator Meaning
~ matches the regex (case-sensitive)
~* matches the regex, ignoring case
!~, !~* doesn’t match

Unlike LIKE, a regex matches anywhere in the text unless you anchor it with ^ (start) or $ (end). Products whose name starts with A, B, C or D:

SQL
SELECT name FROM products WHERE name ~ '^[A-D]' ORDER BY name;
Text
          name          
------------------------
 Assam Breakfast
 Burr Grinder
 Chamomile Calm
 Colombian Supremo
 Darjeeling First Flush
 Decaf House Blend
(6 rows)

Phone numbers in the UK or US format — a +, then 44 or 1, then a space:

SQL
SELECT first_name, phone
FROM customers
WHERE phone ~ '^\+(44|1) ';
Text
 first_name |      phone      
------------+-----------------
 Ben        | +44 7700 900123
 Grace      | +1 206 555 0147
(2 rows)

Regexes can also pull pieces out of text. substring(text FROM pattern) returns the part inside the brackets, and regexp_replace rewrites matches:

SQL
SELECT email,
       substring(email FROM '^([^@]+)@') AS user_name,
       regexp_replace(phone, '[^0-9]', '', 'g') AS digits_only
FROM customers
WHERE id <= 3;
Text
         email          | user_name  | digits_only  
------------------------+------------+--------------
 asha.rao@example.com   | asha.rao   | 919820011223
 ben.carter@example.com | ben.carter | 447700900123
 chen.wei@example.com   | chen.wei   | 
(3 rows)

[^@]+ means “one or more characters that aren’t @”, and 'g' means “replace every match, not just the first”. Regular expressions are a language of their own; for most searches, LIKE and ILIKE are all you need, and they’re easier to read.

Other databases: MySQL uses REGEXP / RLIKE, SQLite needs an extension, and SQL Server has no regex operator before SQL Server 2025. Standard SQL also defines SIMILAR TO, a hybrid of LIKE and regex that PostgreSQL supports but few people use.

Performance: the leading wildcard

LIKE 'Tea%' can use an index on name (with the right index type), because the database can jump to the part of the sorted index where names start with “Tea”. LIKE '%tea' and LIKE '%tea%' can’t — any row could match, so every row has to be checked. On the twelve-row products table that’s instant; on a table of fifty million product reviews, it isn’t.

For “contains” searches on large tables, PostgreSQL offers trigram indexes (the pg_trgm extension) and full-text search (to_tsvector, @@), which are beyond this course but worth knowing about. You’ll learn how indexes work in Indexes.

Tip: test a pattern quickly without a table: SELECT 'Glass Teapot' ILIKE '%tea%'; returns t or f.

Exercise

Build a customer search

Two requests from the support team. First: they half-remember a customer whose first name is exactly four letters long. Return the first_name and last_name of every customer whose first name has exactly four characters, sorted by first name, using LIKE with the _ wildcard (you should get Asha, Chen, Hugo, Isha and Jack). Second: return the name of every product whose name contains the letters tea in any capitalisation, sorted by name.

SQL
-- 1. First names with exactly four characters
SELECT first_name, last_name
FROM customers
WHERE first_name LIKE ___;

-- 2. Products containing "tea" in any case

Summary

  • LIKE matches text against a pattern: % stands for any run of characters (including none) and _ for exactly one.
  • LIKE is case-sensitive in PostgreSQL; ILIKE ignores case (or compare lower(column) LIKE lower(pattern) in other databases).
  • Without wildcards, LIKE behaves like =; NOT LIKE excludes matches.
  • Use ESCAPE (or a backslash) to match a literal % or _.
  • PostgreSQL regular expressions (~ and ~*) handle complex patterns; a leading % or regex can't use a normal index.