Stop 03 · Filtering DataTopics · 6/8

LIKE and Wildcards

Part of the SQL Roadmap

In short

Sometimes you only know part of a value: names starting with "Sh", emails ending in a college domain, product names containing "masala". LIKE matches text by pattern.

LIKE matches text patterns: % stands for any number of characters and _ for exactly one. Case sensitivity depends on the database and collation, and PostgreSQL offers ILIKE for case-insensitive matching.

The jaadu flips through a fat paper phone diary with a magnifying glass, tracing names that share the same first letters.

Think of it like this

Searching your contacts

You remember a friend's name started with "Sh" but not whether it was Shreya or Shubham. You type "Sh" and your phone shows everyone who matches. LIKE 'Sh%' is that search: % stands for "anything after this".

Watch it happen

Matching names against patterns

Shreya
0
Shubham
1
Ashish
2
Sanjay
3
Sharma
4

1/5Five values in a name column.

The big ideas

What you need to know

% means any run of characters

Zero or more. 'Sh%' starts with Sh, '%pur' ends with pur, '%masala%' contains masala.

_ means exactly one character

Handy for fixed-length codes: LIKE 'MH__' matches MH12 and MH14 but not MH1.

Case depends on the database

PostgreSQL LIKE is case-sensitive and has ILIKE. MySQL with its default collation ignores case.

Leading % is slow

LIKE 'Sh%' can use an index. LIKE '%sh%' has to scan every row.

See it in code

Walk through the code

sql
1SELECT name FROM customers WHERE name LIKE 'Sh%';2 3SELECT product_name FROM products WHERE product_name ILIKE '%masala%';4 5SELECT email FROM students WHERE email LIKE '%@iitb.ac.in';6 7SELECT vehicle_no FROM vehicles WHERE vehicle_no LIKE 'MH__AB%';8 9-- Find a literal % sign, like "50% off"10SELECT title FROM offers WHERE title LIKE '%50\% off%';

1/5Names starting with Sh.

ILIKE is PostgreSQL only. In MySQL, plain LIKE already ignores case under the default collation, or use LOWER(name) LIKE '%masala%' anywhere. Backslash is the default escape character in both.

Save yourself the pain

Common mistakes

Oops

WHERE name LIKE 'Sh' expecting names that start with Sh.

Do this instead

Without a wildcard, LIKE behaves like =. Write 'Sh%'.

Oops

Using = with wildcards: WHERE name = 'Sh%'.

Do this instead

Wildcards only work with LIKE. = looks for the literal text Sh%.

Your mission

Pattern hunt

~20 min

Quick check

Which pattern matches "Kanpur" and "Jaipur" but not "Puri"?

Go deeper

  1. 1Find emails ending in gmail.com and names starting with 'A'.
  2. 2Check whether LIKE is case-sensitive in your database.
  3. 3Learn why a pattern starting with % usually cannot use an index.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge