SQL Like Wildcard

Galaxy Glossary

How can I search for specific patterns of text in a database table using SQL?

The `LIKE` operator in SQL allows you to search for patterns within strings. Wildcards are used to represent unknown characters, making searches more flexible. This is crucial for filtering data based on partial matches.
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 in SQL is a powerful tool for searching for specific patterns within string data. It's essential for tasks like finding customer names containing a particular substring, filtering product descriptions, or locating records matching a specific date format. Instead of searching for an exact match, `LIKE` allows you to use wildcards to represent unknown characters. This makes it easier to find data that partially matches a given pattern. For example, you might want to find all customers whose names start with 'A', or all products whose descriptions contain the word 'red'. The `LIKE` operator is used in conjunction with wildcards, which are special characters that represent unknown parts of a string. The most common wildcards are the underscore (_) and the percentage sign (%). The underscore matches any single character, while the percentage sign matches any sequence of zero or more characters. This flexibility makes `LIKE` a fundamental part of data retrieval in SQL.

Why SQL Like Wildcard is important

The `LIKE` operator is crucial for flexible data retrieval. It allows developers to search for patterns within strings, which is essential for tasks like filtering data, reporting, and data analysis. Without `LIKE`, searching for partial matches would be significantly more complex and less efficient.

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 (CustomerID, FirstName, LastName) VALUES
(1, 'John', 'Doe'),
(2, 'Jane', 'Smith'),
(3, 'Peter', 'Jones');

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

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

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

Common Mistakes

Want to learn about other SQL terms?