LIKE %abc% and Why Your Query Got 200 Times Slower

Beginner 4 min read Updated 30 Jul 2026 UPA AI Partner

A percent sign in the wrong place turns a 0.02-second query into a 4-second one. And nothing on screen tells you.

The problem

Find every employee whose name starts with “Ng”. Two wildcards do all the work:

  • %any number of characters, including none
  • _exactly one character
NHAN_VIENtenNguyễn AnTrần ÁnhLê NgânVũ NgaKẾT QUẢ TỪNG MẪUmẫukhớp'Ng%'Ngân'%ng%'Ngân, Nga'Ng_n'Ngân'%n'An, NgânLIKE
SELECT * FROM employees WHERE name LIKE 'Ng%';

Common mistakes

1. A leading %

WHERE name LIKE '%an%'

An index is sorted alphabetically, so it can only jump to a prefix. Starting with % forces a row-by-row scan. On five million rows that is the difference between 0.02 seconds and 4 seconds.

If you genuinely need mid-string search, use full-text search rather than bending LIKE to do it.

2. Assuming LIKE is case sensitive

It depends on the engine. MySQL is case-insensitive by default; PostgreSQL is case-sensitive. To be certain:

WHERE LOWER(name) LIKE 'ng%'     -- but this loses the index
WHERE name ILIKE 'ng%'           -- PostgreSQL, index-friendly with the right index

3. Forgetting to escape

Searching for a literal %:

WHERE promo_code LIKE '%\%%' ESCAPE '\'

4. Using LIKE for exact matching

WHERE code = 'A001'         -- fast
WHERE code LIKE 'A001'      -- slower, buys you nothing

When you need more: regular expressions

-- Names starting with a vowel (PostgreSQL)
WHERE name ~* '^[aeiou]'

-- MySQL
WHERE name REGEXP '^[aeiou]'

This is exactly the shape of HackerRank’s Weather Observation Station 6 through 12.

Practice

  • HackerRank — Weather Observation Station 6, 7, 8, 9, 10, 11, 12
  • LeetCode 1667 — Fix Names in a Table
  • LeetCode 1517 — Find Users With Valid E-Mails

Key takeaways

  • % matches any number of characters, _ matches exactly one.
  • LIKE 'x%' uses an index; LIKE '%x%' does not.
  • Case sensitivity varies by engine — check, do not guess.
  • Wrapping a column in LOWER() discards the index.
  • Use = for exact matches, not LIKE.

You have just learned LIKE và ký tự đại diện

Ready to practise?

Work through LIKE và ký tự đại diện exercises on real data, graded the moment you hit run.

Start practising →