SQL Server LIKE Operator
In SQL Server, the LIKE operator serves as a powerful tool for precisely this purpose. This operator allows users to perform wildcard-based searches, making it a versatile and efficient way to retrieve specific data from a database. Let's explore the ins and outs of the LIKE operator and its various applications in SQL Server.
LIKE Operator
The LIKE operator is primarily used within the WHERE clause of a SQL query to filter results based on specified patterns within a column. It allows users to employ two wildcard characters:- "%"- Represents any sequence of characters, including none.
- "_"- Represents any single character.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Here pattern is the string pattern you want to match. It can include the wildcard characters '%' and '_' .
-- Create the Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
LastName NVARCHAR(50)
);
-- Insert sample data into the Employees table
INSERT INTO Employees (EmployeeID, LastName)
VALUES (1, 'Smith');
VALUES (1, 'Smith');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (2, 'Johnson');
VALUES (2, 'Johnson');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (3, 'Williams');
VALUES (3, 'Williams');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (4, 'Jones');
VALUES (4, 'Jones');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (5, 'Brown');
VALUES (5, 'Brown');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (6, 'Davis');
VALUES (6, 'Davis');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (7, 'Miller');
VALUES (7, 'Miller');
INSERT INTO Employees (EmployeeID, LastName)
VALUES (8, 'Wilson');
VALUES (8, 'Wilson');
Examples:
1. Find all employees whose last names start with 'Smi':SELECT * FROM Employees
WHERE LastName LIKE 'Smi%';
2. Find all employees whose last names end with 'th':
3. Find all employees whose last names have 'ar' in any position:
SELECT * FROM Employees
WHERE LastName LIKE '_mi%';
SELECT * FROM Employees
WHERE LastName LIKE '__e%';
SELECT * FROM Employees
WHERE LastName LIKE '_____';
Output-