Thuta Learning
SQL
BasicData & DatabasesBeginner

LIKE Operator

SQLLesson 1125 min

What you'll walk away with

  • Write patterns with % (any number of characters) and _ (exactly one character)
  • Explain that LIKE must match the whole string and is case-sensitive in PostgreSQL
  • Use ILIKE and know where it does not help (accents, other databases)
  • Escape % and _ to search for them as literal characters

Explain it simply

Explain it simply

The = operator means "exactly equal". But when a user types "phone" into a search box, they also want "Smartphone X" and "Desk Phone". LIKE checks a value against a pattern, and the pattern may contain two wildcards.

% means "any number of characters here, including none", and _ means "exactly one character". So 'A%' finds text starting with A, '%son' finds text ending in son, and '%market%' finds text containing market.

Problem → Why → Solution

The problem: search misses products that exist

After a product search moved from MySQL to PostgreSQL, customers complain that searching for "phone" no longer shows Phone Case Blue, even though the query did not change at all. A second query meant to find "50% off" promotions also returns "Save 500 kyat" and "50 percent faster".

search-bugs.sql
-- 1. Misses 'Phone Case Blue' in PostgreSQL: capital P
SELECT name FROM products WHERE name LIKE '%phone%';

-- 2. Meant "contains 50%", but % is a wildcard here
SELECT note FROM products WHERE note LIKE '%50%%';

Why does this happen?

In PostgreSQL, LIKE is case-sensitive: 'P' and 'p' are different characters. MySQL's default collations are case-insensitive, which is why the query used to work. In the second query all three % signs in '%50%%' are wildcards, so the pattern just means "contains 50". ILIKE and an escape character fix these two problems.

Core concept: the pattern must match the whole string

LIKE checks whether the entire value matches the pattern from start to end. Without wildcards, LIKE 'Ana' is the same as = 'Ana'; it does not mean "contains Ana". For "contains" you add % on both sides yourself: '%Ana%'. Because _ is exactly one character, sku LIKE 'PH-__' matches PH-01 but not PH-100.

PatternMatchesDoes not match
'A%'Ana Trujillo, Aalpine Outfitters (lowercase a)
'%son'Johnson, sonSonia, Johnsons
'%market%'Cardinal market, marketCardinal Market (capital M)
'An%o'Antonio Moreno, Ana TrujilloAna, Antonia
'PH-__'PH-01, PH-ABPH-1, PH-100, XPH-01

In PostgreSQL, LIKE is case-sensitive. PostgreSQL's own ILIKE matches without regard to case according to the active locale; it is not part of the SQL standard. Other databases have no ILIKE: in MySQL and SQL Server, whether LIKE cares about case depends on the column's collation, and their default collations are usually case-insensitive. For portable SQL, write lower(name) LIKE lower('%Phone%').

ILIKE only removes case differences, not accents: 'café' ILIKE 'cafe' is FALSE. Accent-insensitive search needs the unaccent extension or full-text search. Watch NULL too: NULL LIKE 'x%' is NULL, so both LIKE and NOT LIKE drop NULL rows. If those rows matter, add an explicit OR column IS NULL to the condition.

To search for % or _ as real characters, put the escape character in front of them. PostgreSQL's default escape character is the backslash, so '%50\%%' means "contains 50%". You can also choose your own with a clause such as ESCAPE '#'. Remember to escape % and _ inside user-typed search text before you place it in a pattern.

Mental model: line the pattern up, left to right
  1. Start at the first character
  2. Plain character: must match exactly
  3. _ : skip exactly one character
  4. % : skip any number of characters
  5. Pattern must end with the string

LIKE is case-sensitive, ILIKE is not; neither ignores accents.

General pattern

sql
WHERE text_column LIKE 'prefix%'         -- starts with
WHERE text_column LIKE '%suffix'         -- ends with
WHERE text_column LIKE '%word%'          -- contains
WHERE text_column LIKE 'AB-__'           -- AB- plus exactly two characters
WHERE text_column ILIKE '%word%'         -- contains, any case (PostgreSQL)
WHERE text_column LIKE '%100\%%'         -- contains the literal text 100%
WHERE text_column NOT LIKE 'tmp_%'       -- does not match (NULLs drop out)

The pattern is a single-quoted string that can combine % and _ freely. ILIKE is a PostgreSQL extension. A backslash makes % a literal character. NOT LIKE inverts the match but still never returns NULL rows.

Example: customers starting with A, LIKE vs ILIKE

Among the six customers, alpine Outfitters was typed with a lowercase a, which happens all the time in real data entry. Run the same pattern (starts with A) with LIKE and with ILIKE and compare the row counts.

CREATE TABLE customers (
  customer_id   integer PRIMARY KEY,
  customer_name text NOT NULL,
  country       text
);
INSERT INTO customers VALUES
  (1, 'Alfreds Futterkiste', 'Germany'),
  (2, 'Ana Trujillo',        'Mexico'),
  (3, 'Antonio Moreno',      'Mexico'),
  (4, 'Around the Horn',     'UK'),
  (5, 'Berglunds snabbköp',  'Sweden'),
  (6, 'alpine Outfitters',   'Austria');
-- Starts with a capital A (LIKE is case-sensitive)
SELECT customer_name, country
FROM customers
WHERE customer_name LIKE 'A%'
ORDER BY customer_id;

-- Starts with A or a (ILIKE, PostgreSQL only)
SELECT customer_name, country
FROM customers
WHERE customer_name ILIKE 'a%'
ORDER BY customer_id;

Code breakdown

  1. Prefix patternWHERE customer_name LIKE 'A%'

    The first character must be a capital A, and % accepts everything after it. alpine Outfitters starts with a lowercase a and is left out, as is Berglunds snabbköp.

  2. ILIKEWHERE customer_name ILIKE 'a%'

    ILIKE ignores case, so 'a%' and 'A%' give the same result. Now alpine Outfitters is included, making five rows.

  3. Stable orderORDER BY customer_id;

    Sorting by customer_id lets you compare the two results line by line. Sorting by customer_name would put alpine last under the "C" collation but near the top under a linguistic collation.

You should see
    customer_name    | country
---------------------+---------
 Alfreds Futterkiste | Germany
 Ana Trujillo        | Mexico
 Antonio Moreno      | Mexico
 Around the Horn     | UK
(4 rows)

    customer_name    | country
---------------------+---------
 Alfreds Futterkiste | Germany
 Ana Trujillo        | Mexico
 Antonio Moreno      | Mexico
 Around the Horn     | UK
 alpine Outfitters   | Austria
(5 rows)

Searching for a literal %

Let's fix the promotion query from the problem section. A backslash before the middle % turns it into a real character, leaving only "50% off" and "Now 50% cheaper". If you dislike backslashes, choose another character with an ESCAPE clause.

escape.sql
SELECT sku, note FROM products WHERE note LIKE '%50\%%';
SELECT sku, note FROM products WHERE note LIKE '%50#%%' ESCAPE '#';
-- both return PH-01 and PH-02 only

LIKE and indexes

A prefix pattern like 'abc%' can use a B-tree index, but when the database collation is not "C" the index must be created with the text_pattern_ops operator class. Patterns with a leading %, such as '%abc' and '%abc%', cannot use a B-tree index at all, so every row is read. For those, use a GIN trigram index from the pg_trgm extension, which speeds up both LIKE and ILIKE.

like-indexes.sql
-- prefix searches (name LIKE 'Desk%') under any collation
CREATE INDEX products_name_prefix_idx ON products (name text_pattern_ops);

-- contains searches would use pg_trgm (an extension, installed separately):
-- CREATE EXTENSION pg_trgm;
-- CREATE INDEX products_name_trgm_idx ON products USING gin (name gin_trgm_ops);

In real projects

Where this shows up in real projects

The "find customer" box in most admin panels is a query shaped like WHERE name ILIKE '%' || $1 || '%'. Because $1 is a parameter there is no SQL injection, but if the user types % or _ it still acts as a wildcard, so the backend escapes those characters first. Up to a few thousand products this is enough; at millions of rows teams add a pg_trgm index.

LIKE is also common in data cleanup: WHERE email NOT LIKE '%_@_%._%' finds malformed emails, and WHERE sku LIKE 'TMP-%' finds leftover test data. Once a feature needs relevance ranking or word forms such as run and running, teams move to PostgreSQL full-text search (tsvector) or a dedicated search engine.

Common mistakes

Common mistakes

1. Assuming LIKE means "contains"

WHERE name LIKE 'phone' only matches a name that is exactly phone, so Smartphone X is not found. Put the % where you mean it: '%phone%' for contains, 'phone%' for starts with.

2. Expecting LIKE to ignore case in PostgreSQL

This is the top surprise for queries coming from MySQL or SQL Server. In PostgreSQL, LIKE '%phone%' does not find Phone Case Blue. Use ILIKE, or lower(name) LIKE '%phone%' when the SQL must run on both systems.

3. Expecting NOT LIKE to return NULL rows

WHERE note NOT LIKE '%50%' does not return Phone Case Blue, whose note is NULL, because NULL NOT LIKE ... is NULL. If those rows belong in the result, add OR note IS NULL inside parentheses.

Best practices

Best practices

  • Send user-typed search text only as a parameter, and escape %, _ and backslash inside it.
  • In a PostgreSQL-only project use ILIKE for case-insensitive search; when several databases must be supported, use lower(...) LIKE.
  • Each time you write NOT LIKE on a nullable column, decide whether NULL rows belong in the result, and write a test row with NULL to prove it.
  • Before shipping a '%...%' search on a big table, check it with EXPLAIN and add a pg_trgm index if needed.

Mini challenge

Mini challenge: product search

Write two queries on the products table: first, products whose name contains phone in any case and whose sku is PH- followed by exactly two characters; second, products whose note contains the literal text "50%".

  • The first query returns PH-01, PH-02 and PH-15 (not PH-100)
  • The second query returns only PH-01 and PH-02
  • Both queries are sorted by sku
product-search.sql
CREATE TABLE products (
  sku  text PRIMARY KEY,
  name text NOT NULL,
  note text
);
INSERT INTO products VALUES
  ('PH-01',  'Smartphone X',    'Spring sale: 50% off'),
  ('PH-15',  'Phone Case Blue', NULL),
  ('PH-100', 'Headphones Pro',  'Save 500 kyat'),
  ('LP-01',  'Laptop Air',      '50 percent faster'),
  ('PH-02',  'Desk Phone',      'Now 50% cheaper');

-- TODO 1: name contains "phone" in any case,
--         sku = 'PH-' + exactly two characters
SELECT sku, name
FROM products;

-- TODO 2: note contains the literal text 50%
--         ('Save 500 kyat' and '50 percent faster' must NOT match)

Expected: Query 1: PH-01 Smartphone X, PH-02 Desk Phone, PH-15 Phone Case Blue. Query 2: PH-01 (Spring sale: 50% off) and PH-02 (Now 50% cheaper).

Show hint

Use ILIKE for any case, and two underscores for exactly two characters. Put a backslash before the % you mean literally: '%50\%%'.

Show solution
product-search.sql
SELECT sku, name
FROM products
WHERE name ILIKE '%phone%'
  AND sku LIKE 'PH-__'
ORDER BY sku;

SELECT sku, note
FROM products
WHERE note LIKE '%50\%%'
ORDER BY sku;

Quick quiz 1 / 3

The customers table contains 'Around the Horn'. In PostgreSQL, does WHERE customer_name LIKE '%horn' return that row?

Quick quiz 2 / 3

Which sku does sku LIKE 'PH-__' match?

Quick quiz 3 / 3

In PostgreSQL, which condition finds notes containing the literal text "100%"?

What to remember

  • % is any number of characters, _ is exactly one, and the pattern must match the whole string.
  • In PostgreSQL, LIKE is case-sensitive and ILIKE (PostgreSQL only) is not; neither ignores accents.
  • Escape % and _ with a backslash or an ESCAPE clause to search for them literally.
  • NULL rows drop out of both LIKE and NOT LIKE.
  • A leading % cannot use a B-tree index; large tables need pg_trgm.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

LIKE Operator | Thuta Learning