0
0
SQLquery~5 mins

WHERE with LIKE pattern matching in SQL

Choose your learning style9 modes available
Introduction
The WHERE clause with LIKE helps you find rows where a text column matches a pattern. It is useful when you want to search for similar words or partial matches.
Finding all customers whose names start with 'Jo'.
Searching for products that contain the word 'book' anywhere in their name.
Filtering emails that end with '@example.com'.
Looking for addresses that include a specific street name.
Finding phone numbers that start with a certain area code.
Syntax
SQL
SELECT column1, column2 FROM table_name WHERE column_name LIKE 'pattern';
The pattern can include % which means any number of characters (including zero).
The pattern can include _ which means exactly one character.
Examples
Finds all employees whose names start with 'A'.
SQL
SELECT * FROM employees WHERE name LIKE 'A%';
Finds all products with 'book' anywhere in the description.
SQL
SELECT * FROM products WHERE description LIKE '%book%';
Finds all customers with emails ending in '@gmail.com'.
SQL
SELECT * FROM customers WHERE email LIKE '%@gmail.com';
Finds orders where the order_code has exactly three characters before '123'.
SQL
SELECT * FROM orders WHERE order_code LIKE '___123';
Sample Program
This creates a table of employees, inserts some names, and selects those whose names start with 'A'.
SQL
CREATE TABLE employees (
  id INT,
  name VARCHAR(50)
);

INSERT INTO employees (id, name) VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Anna'),
(4, 'Albert'),
(5, 'Brian');

SELECT * FROM employees WHERE name LIKE 'A%';
OutputSuccess
Important Notes
LIKE is case-insensitive in some databases (like MySQL) but case-sensitive in others (like PostgreSQL).
Using % at the start of the pattern can slow down the search because it cannot use indexes efficiently.
Use _ to match exactly one character when you want precise pattern matching.
Summary
WHERE with LIKE lets you search text columns using patterns.
% means any number of characters, _ means exactly one character.
It is useful for partial or flexible text matching in queries.