SQL Cookbook Lesson
How to use LIKE in SQL
Learn how to use LIKE in SQL with examples and explanations from SQLPad.
Problem
The issue at hand is to understand the usage of the LIKE operator in SQL. The LIKE operator is used in the WHERE clause to search for a specified pattern in a column.
Sample Data
Consider the following table named Employees:
| ID | Name | JobRole |
|---|---|---|
| 1 | John Doe | Developer |
| 2 | Jane Smith | Designer |
| 3 | Mike Harvey | Tester |
| 4 | Sara Lee | Developer |
| 5 | Tom Cruise | Product Owner |
MySQL Solution
SELECT * FROM Employees
WHERE Name LIKE '%o%';
PostgreSQL Solution
The solution remains the same for PostgreSQL.
SELECT * FROM Employees
WHERE Name LIKE '%o%';
Explanation
The LIKE operator in SQL is used to filter results based on a pattern in a WHERE clause. The % character is used as a wildcard character to represent any number of characters (including zero characters).
In our solutions, we are selecting all columns from the Employees table where the Name contains the character 'o'. This is represented by the pattern '%o%'. The '%' before and after the 'o' means any characters can come before or after the 'o'.
For example, in the MySQL and PostgreSQL solutions, the query will return the following rows:
| ID | Name | JobRole |
|---|---|---|
| 1 | John Doe | Developer |
| 5 | Tom Cruise | Product Owner |
Because 'John Doe' and 'Tom Cruise' are the only names that contain the letter 'o'.