Explain Like Operator in SQL
In SQL, the LIKE operator is used to search for a specified pattern in a column. It is often used with the WHERE clause to filter records based on pattern matching. The LIKE operator supports wildcard characters to help define the search pattern.
Here are the key wildcard characters you can use with the LIKE operator:
% – Represents zero or more characters.
_ – Represents a single character.
Examples and Output
Let's assume we have a table named Employees with the following data:
| EmployeeID |
FirstName |
LastName |
| 1 |
John |
Doe |
| 2 |
Jane |
Smith |
| 3 |
Jim |
Brown |
| 4 |
Jake |
Doe |
| 5 |
Jack |
Daniels |
Example 1: Using % Wildcard
SELECT * FROM Employees
WHERE LastName LIKE 'Doe%';
Output:
| EmployeeID |
FirstName |
LastName |
| 1 |
John |
Doe |
| 4 |
Jake |
Doe |
Explanation: This query selects all rows where the LastName starts with 'Doe'. The % wildcard represents any sequence of characters following 'Doe'.
Example 2: Using _ Wildcard
SELECT * FROM Employees
WHERE FirstName LIKE 'J__';
Output:
| EmployeeID |
FirstName |
LastName |
| 1 |
John |
Doe |
| 3 |
Jim |
Brown |
| 4 |
Jake |
Doe |
Explanation: This query selects all rows where the FirstName is exactly 3 characters long, starting with 'J'. The _ wildcard represents a single character.
Example 3: Combining % and _ Wildcards
SELECT * FROM Employees
WHERE LastName LIKE 'D_n%';
Output:
| EmployeeID |
FirstName |
LastName |
| 1 |
John |
Doe |
| 5 |
Jack |
Daniels |
Explanation: This query selects all rows where the LastName starts with 'D', followed by any single character (n), and then any sequence of characters (%).
These examples demonstrate how the LIKE operator can be used to perform flexible pattern matching in SQL queries.