Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 17/ 160
01. SQL Foundations & Relational Concepts

Pattern Matching (LIKE, ILIKE, Wildcards % and _)

Search text with LIKE/ILIKE wildcards and know when indexes still help.

BeginnerLIKE · ILIKE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

% means "anything here" and _ means "exactly one letter here". LIKE checks whether text fits that shape.

Think of it like…

Looking up words in a dictionary: "words starting with pre" is a quick flip to the right page. "Words containing ord" means reading every page.

Where you’ve seen it

A product search: WHERE name ILIKE 'sams%' can use an index and is fast. WHERE name ILIKE '%galaxy%' on 5 million products is a full scan, so production search uses a trigram index (pg_trgm) or full-text search instead.

Words you’ll hear

%
Any number of characters, including zero.
_
Exactly one character.
ILIKE
Case-insensitive LIKE in PostgreSQL (MySQL depends on collation).
ESCAPE
Treat % or _ literally, as in LIKE '50\%%' ESCAPE '\'.

Visual diagram

Loading interactive diagram

Theory & example queries

Writing patterns

'Ra%' starts with Ra, '%son' ends with son, '%an%' contains an, '_a%' has 'a' as the second character, and '___' is exactly three characters. LIKE compares the whole string, so 'Ra' without wildcards behaves like equality.

Case sensitivity depends on the database: PostgreSQL LIKE is case-sensitive (use ILIKE or LOWER(col) LIKE 'ra%'), while MySQL with its default case-insensitive collations isn't. NOT LIKE excludes rows where the column is NULL, just like other comparisons. For more complex rules, regular expressions (~ in PostgreSQL, REGEXP in MySQL) go further.

Finding test accountsQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  email4FROM5  users6WHERE7  email ILIKE '%+test@%'8  OR email LIKE 'qa\_%' ESCAPE '\';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative matching accounts2 sample rows
Representative matching accounts
idemail
17asha+test@example.com
28qa_automation@example.com

Note: Sample rows satisfy the unescaped +test@ pattern or the literal qa_ prefix. LIKE/ILIKE case rules and matching sets are dialect- and collation-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The second pattern treats the underscore literally.

Key takeaway: % = anything, _ = one character; check your database's case rules.

Performance and safe user input

A B-tree index stores values sorted, so a fixed prefix ('sams%') becomes a range scan. In PostgreSQL with a non-C collation, the index must be created with text_pattern_ops (or varchar_pattern_ops) to support LIKE. A leading wildcard can't use it at all. For substring search, PostgreSQL's pg_trgm extension with a GIN index makes LIKE '%galaxy%' and ILIKE fast; for word-based search, full-text search is better.

When the pattern comes from a user, pass it as a parameter (never concatenate it into SQL), and escape their % and _ characters so they're matched literally. Otherwise a search for "50%" matches everything starting with 50.

A trigram index for contains-searchQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE EXTENSION IF NOT EXISTS pg_trgm;23CREATE INDEX ON products USING gin (name gin_trgm_ops);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command responses2 sample rows
Representative command responses
statementstatus
CREATE EXTENSIONCREATE EXTENSION
CREATE INDEXCREATE INDEX

Note: PostgreSQL returns these statuses on a successful setup. Whether a later %galaxy% query uses the GIN index depends on the planner, selectivity and table size.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Then WHERE name ILIKE '%galaxy%' can use the index.

Key takeaway: Prefix patterns use B-trees; substring patterns need trigram or full-text indexes.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Choose the pattern shape

Decide whether you need starts-with, ends-with or contains, and whether case should matter.

SQL at this stepReadable preview
1starts-with 'Ra%' · contains '%an%'
What to watch at this step
Fastest
starts-with
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

LIKE matches text against a pattern with two wildcards: % for any sequence of characters (including none) and _ for exactly one character. name LIKE 'Ra%' finds names starting with Ra. ILIKE is PostgreSQL's case-insensitive version. A pattern with a fixed prefix can use an index; a pattern starting with % can't use a normal one.

Why it matters: Search boxes, filters and data-cleaning queries all use LIKE, and its performance surprises people: '%term%' on a large table is a full scan. User input inside LIKE patterns also needs care, because a user typing % matches everything.

When to reach for it

  • Autocomplete with starts-with patterns
  • Filtering by email domain or code prefix
  • Ad-hoc data exploration

When to avoid or be careful

  • '%term%' on big tables without a trigram index
  • Concatenating user input into LIKE patterns
  • Relying on LIKE being case-insensitive across databases

LIKE vs regular expressions vs full-text search

LIKE / ILIKE
Best for: Simple starts-with, ends-with and contains matching

Strengths: Simple, portable; prefix patterns can use B-trees.

Watch out: Leading wildcards scan unless you add a trigram index.

Regular expressions (~, REGEXP)
Best for: Complex validation and extraction rules

Strengths: Very expressive.

Watch out: Harder to read; usually can't use indexes.

Full-text search (tsvector)
Best for: Searching words in descriptions and articles

Strengths: Stemming, ranking and fast GIN indexes.

Watch out: Matches words, not arbitrary substrings; more setup.

Interview signals & numbers to know

When this topic comes up

  • “Search products by name”
  • “Why is this LIKE query slow?”
  • “Names starting with …”
  • Case-insensitive search
  • Autocomplete

Benchmarks & rules of thumb

% -
zero or more characters
_ -
exactly one character
pg_trgm -
extension for fast contains-search

Common mistakes & follow-ups

Common interview mistakes

  • Expecting LIKE '%term%' to use a normal index.
  • Forgetting that _ is a wildcard, so 'qa_%' also matches 'qax…'.
  • Assuming LIKE ignores case in PostgreSQL the way it does in MySQL.

Likely interviewer follow-ups

  • Why can LIKE 'abc%' use an index but LIKE '%abc' can't?
  • How would you make a contains-search fast on millions of rows?
  • How do you safely use user input in a LIKE pattern?
Interview tip: Give the wildcard rules in one line, then talk about indexes and escaping user input. Those two points are what separate a production answer from a syntax answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Pattern Matching (LIKE, ILIKE, Wildcards % and _) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Logical & Range Operators (AND, OR, NOT, BETWEEN, IN)
Next topic
Handling NULL Values (IS NULL, IS NOT NULL, Three-Valued Logic)