Filtering and sorting
LIKE and pattern matching
Use SQL Server wildcards to match text patterns.
Lesson 15 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. Equality finds exact text. LIKE finds text that follows a pattern, such as every product name beginning with Desk.
Run the example
SELECT ProductID, ProductName
FROM dbo.Products
WHERE ProductName LIKE N'Desk%'
ORDER BY ProductID;Read it step by step
- ProductName LIKE N'Desk%' compares each name with a pattern. Desk is a literal prefix.
- The % wildcard stands for zero or more characters, so Desk Lamp and Desk Chair both match.
- ORDER BY ProductID gives a repeatable two-row result. The _ wildcard, by contrast, stands for exactly one character.
Check the result
| ProductID | ProductName |
|---|---|
| 6 | Desk Lamp |
| 13 | Desk Chair |
There are two matching products on dataset v1.0.0. A pattern of N'%Desk%' would mean contains Desk anywhere, while N'Desk%' specifically means starts with Desk. The database collation determines whether letter case matters.
Practice
Find customer first names beginning with A. Which records in the unmodified v1.0.0 dataset match?
Check your answer and expected result
Reveal answer
SELECT CustomerID, FirstName FROM dbo.Customers WHERE FirstName LIKE N'A%' ORDER BY CustomerID;| CustomerID | FirstName |
|---|---|
| 1 | Alex |
| 10 | Ada |
| 15 | Arjun |
Alex (ID 1), Ada (ID 10), and Arjun (ID 15) match.
Your progress
Reveal the check answer or reach the end to complete this lesson.