# 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.
2. Explain Like I'm 5
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 TraceLIKE & Wildcards Visual Simulator
SELECT * FROM users WHERE email LIKE '%@company.com';
SELECT * FROM users WHERE username LIKE 'admin_%';Active InputStep 1: Input & Parsing Stage
Initiating LIKE & Wildcards
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Searching for user emails matching a domain or finding product SKUs with specific prefix formats.
| id | |
|---|---|
| 1 | lucky@gmail.com (Matches %gmail.com) |
| 2 | rahul@yahoo.com (No match) |
| 3 | admin@gmail.com (Matches %gmail.com) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT id, username FROM users WHERE username LIKE 'john%';
SELECT id, name FROM products WHERE name ILIKE '%laptop%';
-- 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 '\';
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| % Wildcard | Matches zero, one, or multiple arbitrary characters. |
| _ Wildcard | Matches exactly one single character. |
| Leading Wildcard Index Invalidation | A pattern starting with % (e.g. '%search') cannot use a B-Tree index and forces a sequential scan. |
| B-Tree prefix indexability | LIKE queries with trailing wildcards (term%) use B-Tree indexes; leading wildcards (%term) force sequential scans. |
| Escape character syntax | To 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%';
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
Which of the following queries can efficiently utilize a standard B-Tree index on the name column?