CodeBlanks Logo Icon CodeBlanks

Pattern matching with LIKE

Search text with LIKE and the %, _ wildcards.

Pattern matching with LIKE

LIKE searches for a pattern in text. Two wildcards are used: % matches zero or more characters, _ matches exactly one character.

SELECT name FROM customers
WHERE name LIKE 'A%';

This returns all names starting with A. %a% finds names containing a.

name is selected from customers. WHERE keeps only the rows where name LIKE 'A%' holds.

Pattern matching with LIKE — details

The position of wildcards changes the meaning: 'A%' starts with A, '%a' ends with a, '%a%' contains a. Case sensitivity depends on the database.

Use _ for exactly one character: LIKE '_a%' finds values whose second letter is a.

Practice Pattern matching with LIKE

Select name from customers whose name contains the letter 'a'.

Starter code

query.sql
-- write a LIKE pattern
SELECT name
FROM customers
WHERE

Sample solution

query.sql
SELECT name
FROM customers
WHERE name LIKE '%a%'

Expected output

name
Ayşe
Alex
Ahmet

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Starts with A

Question
SELECT name FROM customers
WHERE name LIKE ____;
Answer
SELECT name FROM customers
WHERE name LIKE 'A%';

Explanation: LIKE 'A%' finds text that starts with A; % means any number of characters after it.

2 Pattern matching with LIKE: match the terms

Term Meaning
'A%' starts with A
'%a' ends with a
'%a%' contains a
'A_' A plus one letter

3 What does % match?

  • A space
  • Exactly one character
  • Zero or more characters Correct answer
  • A number

Explanation: % matches zero or more characters.

All lessons in Beginner