Explain the use of the 'LIKE' operator in SQL.
Instruction: Provide an example of how to use the LIKE operator for pattern matching in a query.
Updated
Official answer
LIKE matches a string against a pattern. % represents zero or more characters; _ represents one character. To find names beginning with Ann, use a pattern such as Ann%.
This PostgreSQL example searches for the literal prefix A_, treating the underscore as data:
WITH products(name) AS (VALUES ('A_one'), ('ABone'), ('A_'), (NULL))
SELECT name
FROM products
WHERE name LIKE 'A!_%' ESCAPE '!'
ORDER BY name;
It returns A_ and A_one. A NULL input does not make the predicate true. Case and collation behavior depend on the database; PostgreSQL also has ILIKE for its case-insensitive pattern matching behavior.
Bind application pattern values. Binding prevents SQL injection but does not remove wildcard meaning; escape %, _ and the escape character when the user intends a literal search. Prefix and leading-wildcard searches can have different indexing options. Measure rather than assuming LIKE is always fast or understands word meaning.