SQL LIKE Operator
The SQL LIKE operator is used for pattern matching within a WHERE clause, allowing you to filter records based on a specified pattern.
The LIKE operator is typically used with wildcard characters % and _ to match a sequence of characters or a single character, respectively.
In this tutorial, we will go through the SQL LIKE operator, its syntax, and how to use this clause in filtering operations in SQL statements, with well detailed examples.
Syntax of SQL LIKE Operator
The basic syntax of the SQL LIKE operator in a WHERE clause is as follows:
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
Each part of this syntax has a specific purpose:
- SELECT: Specifies the columns to retrieve from the table.
- FROM: Specifies the table from which to retrieve data.
- WHERE: Introduces the condition used to filter the data.
- LIKE: Checks if the specified pattern matches a column’s value.
- pattern: A sequence that uses wildcards to specify matching criteria.
The % wildcard represents zero or more characters, while _ represents a single character.
Step-by-Step Examples with MySQL
We’ll go through various examples demonstrating the LIKE operator in MySQL. Using MySQL 8.0 with MySQL Workbench, we’ll use a sample students table with fields id, name, age, grade, and locality.
Setup for Examples: Creating the Database and Table
1. Open MySQL Workbench and create a new database:
CREATE DATABASE school;
2. Select the school database:
USE school;
3. Create a table named students:
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
grade VARCHAR(10),
locality VARCHAR(50)
);
4. Insert some sample records to use in our examples:
INSERT INTO students (name, age, grade, locality)
VALUES
('Alice', 14, '8th', 'Northside'),
('Bob', 15, '9th', 'Westend'),
('Charlie', 14, '8th', 'Northside'),
('David', 16, '10th', 'Southend'),
('Eva', 15, '9th', 'Westend');
Examples: Using LIKE Operator in Queries
Now, let’s explore different scenarios of using the LIKE operator with this table.
