SQL Like

Galaxy Glossary

How do I filter data in a SQL table based on patterns?

The `LIKE` operator in SQL allows you to search for data that matches a specific pattern. It's a powerful tool for filtering results based on partial matches or specific character sequences. This is crucial for tasks like finding records containing certain keywords or matching specific formats.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `LIKE` operator is a fundamental part of SQL for filtering data based on patterns. It's used in `WHERE` clauses to select rows where a column value matches a specified pattern. This pattern can include literal characters, wildcards (`%` and `_`), and character classes. This flexibility makes `LIKE` a valuable tool for searching within databases. For instance, you might want to find all customers whose names start with 'A', or all products containing the word 'shirt'. The `LIKE` operator enables these searches efficiently. It's important to understand that `LIKE` is case-sensitive in many SQL implementations, unless case-insensitive collation is used. This means 'apple' and 'Apple' would be considered different matches. Also, the `LIKE` operator is generally less efficient than using indexed columns for exact matches. For optimal performance, consider using indexed columns whenever possible.

Why SQL Like is important

The `LIKE` operator is crucial for data retrieval in SQL. It allows for flexible searching, enabling developers to find specific data based on patterns rather than exact matches. This is essential for tasks like searching for records containing keywords, filtering by specific formats, or finding data with partial matches.

Example Usage


-- Sample tables
CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50)
);

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    OrderDate DATE,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- Sample data (insert into Customers and Orders tables)
INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES
(1, 'John', 'Doe'),
(2, 'Jane', 'Smith');

INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES
(101, 1, '2023-10-26'),
(102, 2, '2023-10-27');

-- INNER JOIN example
SELECT
    c.FirstName,
    c.LastName,
    o.OrderID,
    o.OrderDate
FROM
    Customers c
INNER JOIN
    Orders o ON c.CustomerID = o.CustomerID;

Common Mistakes

Want to learn about other SQL terms?