← Back to Chapters

MySQL Wildcards

? MySQL Wildcards

? Quick Overview

Wildcards in MySQL are used with the LIKE operator to search for specified patterns inside text columns. They allow flexible pattern matching (partial matches, fixed-length matches) which is useful for filtering results without full-text search.

? Key Concepts

  • % — matches zero or more characters (use for "contains", "starts with", "ends with").
  • _ — matches exactly one character (use for fixed-length patterns).
  • Case sensitivity — MySQL's default collation is usually case-insensitive, but behavior can vary by collation.
  • Performance — leading wildcards (e.g., %term) can prevent index usage and slow queries on large tables.

? Syntax / Theory

? View Code Example
-- General LIKE syntax
SELECT column_name
FROM table_name
WHERE column_name LIKE pattern;

? Code Examples

? View Code Example
-- Find records where the 'name' starts with 'A'
SELECT * FROM students
WHERE name LIKE 'A%';
? View Code Example
-- Find records where the 'name' ends with 'son'
SELECT * FROM students
WHERE name LIKE '%son';
? View Code Example
-- Find records where the 'name' contains 'an' anywhere
SELECT * FROM students
WHERE name LIKE '%an%';
? View Code Example
-- Match names with exactly 4 characters starting with 'J' (J + 3 single-character wildcards)
SELECT * FROM students
WHERE name LIKE 'J___';

? Live Output / Explanation

How patterns translate to matches

  • LIKE 'A%' matches A, Adam, Alice, etc.
  • LIKE '%son' matches Jackson, son, Emerson.
  • LIKE '%an%' matches any string containing an (e.g., Andrew, Susan).
  • LIKE 'J___' matches any 4-letter name starting with J (e.g., John, Jill).

✅ Tips & Best Practices

  • Prefer column LIKE 'term%' (no leading %) when possible to allow index use.
  • Escape wildcard characters if you need to search for literal % or _.
  • Test patterns on representative data — wildcard queries can return unexpectedly large sets.
  • For advanced needs (fuzzy matching, ranking), consider full-text search or external search engines.

? Try It Yourself

  • Write a query to find all records where the name starts with 'A' and contains exactly 3 characters.
  • Use LIKE to find records with a specific substring anywhere in the text (e.g., 'art').
  • Use the _ wildcard to match names with exactly 4 characters, not starting with a specific letter.