Skip to content
Back to 50 Concepts
Topic 15 of 50query-executionBeginner

# Topic 15: LIKE & Wildcards

Pattern matching with % and _, case-insensitive ILIKE in PostgreSQL, escape characters, and B-Tree prefix indexability.

1. Definition

The LIKE operator matches string patterns using wildcards: % represents zero or more characters, while _ represents exactly one character.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

LIKE is like playing Hangman or typing a search with an asterisk (*). "%smith" finds any name ending in smith, while "_at" finds cat, bat, and hat.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

LIKE & Wildcards Visual Simulator

Step 1 of 3
SQL>SELECT * FROM users WHERE email LIKE '%@company.com'; SELECT * FROM users WHERE username LIKE 'admin_%';Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for LIKE & Wildcards
SQL Input

Initiating LIKE & Wildcards

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Telephone Directory: You can instantly find "Smith, J" because the book is sorted by the first letter, but you cannot quickly find all people whose name ends in "ith".

4. Real-World Example

Searching for user emails matching a domain or finding product SKUs with specific prefix formats.

Users
idemail
1lucky@gmail.com (Matches %gmail.com)
2rahul@yahoo.com (No match)
3admin@gmail.com (Matches %gmail.com)
Relational walkthrough: WHERE email LIKE '%@gmail.com' filters for Gmail accounts.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Prefix Match (Indexable with B-Tree)
SELECT id, username FROM users WHERE username LIKE 'john%';
Prefix matches can use a standard B-Tree index scan.
Step 2: Case-insensitive search with ILIKE (PostgreSQL)
SELECT id, name FROM products WHERE name ILIKE '%laptop%';
Matches Laptop, LAPTOP, and laptop.
Step 3: Single character wildcard _ and escape characters
-- Match 3-letter codes starting with A and ending with Z:
SELECT code FROM coupons WHERE code LIKE 'A_Z';

-- Match literal percentage sign using ESCAPE:
SELECT id, discount FROM promotions WHERE discount LIKE '50\%' ESCAPE '\';
Use escape sequences when matching literal % or _ symbols.

6. Important Rules & Behaviors

RuleBehavioral Explanation
% WildcardMatches zero, one, or multiple arbitrary characters.
_ WildcardMatches exactly one single character.
Leading Wildcard Index InvalidationA pattern starting with % (e.g. '%search') cannot use a B-Tree index and forces a sequential scan.
B-Tree prefix indexabilityLIKE queries with trailing wildcards (term%) use B-Tree indexes; leading wildcards (%term) force sequential scans.
Escape character syntaxTo match literal % or _ characters, use the ESCAPE clause or backslash escaping.

7. Deep Dive: B-Tree Indexing vs Trigram (GIN) Full-Text Search

Standard B-Tree indexes only support prefix matches (LIKE "abc%"). When you need suffix or substring matching (LIKE "%abc%"), you must use a GIN index with the pg_trgm extension in PostgreSQL.

-- Enable trigram extension in Postgres:
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- Create GIN trigram index for fast %substring% searches:
CREATE INDEX idx_products_name_trgm ON products USING gin (name gin_trgm_ops);

-- Now this uses an index instead of a full table scan!
SELECT * FROM products WHERE name ILIKE '%macbook%';
Caution: Without GIN trigrams, every LIKE "%query%" query scans every single disk page of the table.

8. Advantages & Disadvantages

Advantages

  • •Built-in pattern matching without complex external search engines.
  • •Prefix matches (LIKE "abc%") execute in O(log N) using B-Trees.

Disadvantages & Trade-offs

  • •Leading wildcards (%abc) force full table scans on B-Tree indexes.

9. Common Interview Questions

Q1.Why can a B-Tree index be used for LIKE 'abc%' but NOT for LIKE '%abc'?

A B-Tree index stores strings sorted in alphabetical order from left to right. When given 'abc%', the engine knows the exact starting prefix: it navigates the tree to 'abc' in O(log N) and scans forward until strings no longer start with 'abc'. When given '%abc', the first character could be anything from A to Z: the B-Tree sort order provides zero filtering advantage, forcing a full sequential scan of every page.

Q2.How do you perform fast substring searching (LIKE '%pattern%') on large tables in PostgreSQL?

Standard B-Tree indexes cannot satisfy leading wildcards. In PostgreSQL, you use the pg_trgm (Trigram) extension with a GIN (Generalized Inverted Index) or GiST index: CREATE INDEX idx_users_name_trgm ON users USING gin (name gin_trgm_ops); Trigrams split strings into 3-character slices, allowing the GIN index to satisfy arbitrary substring matches in milliseconds.

Q3.What is the difference between LIKE and ILIKE in PostgreSQL?

LIKE is case-sensitive ('Apple' LIKE 'app%' evaluates to FALSE). ILIKE is a PostgreSQL-specific extension that performs case-insensitive pattern matching ('Apple' ILIKE 'app%' evaluates to TRUE). To index ILIKE queries in standard ANSI engines, you must create a functional index on LOWER(col) and query WHERE LOWER(col) LIKE 'app%'.

Q4.How do you search for literal percentage (%) or underscore (_) characters in LIKE?

Because % and _ are wildcards, you must escape them. In standard SQL, you specify an ESCAPE character: WHERE code LIKE '10$%' ESCAPE '$'; or in PostgreSQL using backslash: WHERE code LIKE '10\%';

Q5.What is the difference between SQL LIKE and Full-Text Search (tsvector / MATCH AGAINST)?

LIKE performs raw character pattern matching without linguistic understanding. Full-Text Search parses text into lexemes, performs stemming (mapping "running" to "run"), strips stop words ("the", "is"), supports relevance ranking (ts_rank), and uses inverted indexes (GIN), making it vastly superior for natural language search.

10. Interview-Ready Answer

“LIKE enables wildcard string searches using % and _. Prefix searches (abc%) can leverage standard B-Tree index scans, whereas arbitrary substring searches (%abc%) require GIN trigram indexes to prevent full table scans.”

11. Quick Test

Scenario Question:

Which of the following queries can efficiently utilize a standard B-Tree index on the name column?

Select your answer: