SQL / MySQL Intermediate Queries · 6 min read

SQL LIKE and Escaped Wildcards

Lesson 32 of 33 in the SQL / MySQL learning path.

How do I search lesson titles without treating a percent sign as a wildcard?

LIKE matches a pattern. Percent means any sequence. Underscore means one character.

A student who searches for 100% will match every title if you drop that percent into the pattern raw.

Syntax & Parameters

Syntax
WHERE title LIKE CONCAT('%', ?, '%')

Example

queries.sql
-- Bind the escaped term. Do not concatenate raw input.
SELECT id, title
FROM lessons
WHERE published_at IS NOT NULL
  AND title LIKE CONCAT('%', 'route', '%')
ORDER BY title;
-- Percent matches any sequence.
-- Underscore matches one character.
-- A search for 100% must escape the percent as \%.
-- ESCAPE '!' lets you write !% for a literal percent.
-- A leading wildcard cannot use a normal index on title.
-- Keep the bound pattern in the application, not in this sample text.

Expected Output

Published lessons whose titles contain route, such as Introduction to routes.

Line-by-Line Walkthrough

  1. Only published lessons are searched.
  2. The pattern surrounds route with percent signs.
  3. Titles containing route match.
  4. The sample uses a fixed word so the SQL is safe to read.
  5. Application code must bind the term.
  6. Escape percent and underscore in that term first.
  7. A leading wildcard is a scan.
  8. Add a full-text index if this search is hot.

Common Pitfalls & Security

Read the limits before you copy this.

  • A raw percent in the term matches everything.
  • Underscore matches one character, so a_b matches acb.
  • CONCAT of untrusted text is still injection if you skip binding.
  • A leading percent usually cannot use a btree index.

Best Practices & Modern Standards

Escape \, %, and _ in the user term, then bind the finished pattern.

Prefer a full-text index when title search is a main feature.

Real-World Use

The catalog search box finds lessons whose titles contain the typed word, and a search for 100% does not return every row.

Frequently Asked Questions

What does percent mean?

Any sequence of characters, including none.

What does underscore mean?

Exactly one character.

How do I match a literal percent?

Escape it, or use ESCAPE and a prefix of your choice.

Will this use an index?

Not when the pattern starts with a wildcard. Plan a full-text index for that search.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…