SQL Like
Example Table
We will use the following table named customers for our examples:
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(50),
city VARCHAR(50)
);
INSERT INTO customers (customer_id, customer_name, city) VALUES
(1, 'John Doe', 'New York'),
(2, 'Jane Smith', 'Los Angeles'),
(3, 'Emily Davis', 'Chicago'),
(4, 'Michael Brown', 'Houston'),
(5, 'Jessica White', 'Phoenix');
Customers Table
| customer_id | customer_name | city |
|---|---|---|
| 1 | John Doe | New York |
| 2 | Jane Smith | Los Angeles |
| 3 | Emily Davis | Chicago |
| 4 | Michael Brown | Houston |
| 5 | Jessica White | Phoenix |
Using SQL LIKE
SQL LIKE is used to search for a specified pattern in a column.
Example: Search for Names Starting with 'J'
To find customers whose names start with 'J', use the following query:
SELECT customer_name, city
FROM customers
WHERE customer_name LIKE 'J%';
Result:
| customer_name | John Doe |
|---|---|
| city | New York |
| customer_name | Jane Smith |
| city | Los Angeles |
| customer_name | Jessica White |
| city | Phoenix |
Example: Search for Names Ending with 's'
To find customers whose names end with 's', use the following query:
SELECT customer_name, city
FROM customers
WHERE customer_name LIKE '%s';
Result:
| customer_name | Jane Smith |
|---|---|
| city | Los Angeles |
| customer_name | Emily Davis |
| city | Chicago |
Example: Search for Names Containing 'it'
To find customers whose names contain 'it', use the following query:
SELECT customer_name, city
FROM customers
WHERE customer_name LIKE '%it%';
Result:
| customer_name | Jessica White |
|---|---|
| city | Phoenix |