The LIKE
and ILIKE
clauses in SQL are used for pattern matching in string data, enabling queries to find matches based on specific patterns within strings. The LIKE
operator is case-sensitive, while ILIKE
, available in some SQL dialects such as PostgreSQL, performs a case-insensitive match.
These operators are particularly useful in scenarios where precise matching is not feasible, such as searching user-generated content, filtering names in a customer database, or querying descriptions in a catalog. By using wildcard characters, such as %
(which matches any sequence of characters) and _
(which matches any single character), these operators can significantly enhance the flexibility of search functionalities in SQL queries.
Suppose you have a table named Books
with a column Title
that contains book titles. You want to find all books that contain the word “guide” in their title, regardless of case, and also books that start with “The”.
Books
TableBookID
(int)Title
(varchar)Here’s an example of using both LIKE
and ILIKE
in a query:
-- This example assumes the use of PostgreSQL for the ILIKE operator
SELECT
BookID,
Title
FROM
Books
WHERE
Title ILIKE '%guide%' -- Case-insensitive search for any titles containing "guide"
OR
Title LIKE 'The%' -- Case-sensitive search for titles starting with "The"
ORDER BY
Title;
BookID
and Title
: Selects the ID and the title of the book from the Books
table.Title ILIKE '%guide%'
: Searches for books where the title contains the word “guide” in any case. The %
wildcards mean that “guide” can appear anywhere in the title.Title LIKE 'The%'
: Looks for books where the title starts with “The”. Here, the %
wildcard allows for any characters to follow after “The”.Title
to make the output easy to browse.Assuming the Books
table contains the following entries:
The output of the query would be:
BookID | Title |
---|---|
1 | Guide to SQL |
3 | A Complete Guide to Cooking |
2 | The Great Outdoors |
5 | the quick guide |
ILIKE
condition.LIKE
condition.