Like operator with indexes in SQL
· 2 min read
Introduction
The SQL LIKE operator is used in a WHERE clause to search for a specified pattern in a cloumn.
The performance and behavior of the LIKE operator in SQL change significantly when used alongside indexes.
1. Basic Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;
2. Wildcard Characters
The LIKE operator uses two main wildcards to define patterns:
%(Percent sign): Represents zero, one, or multiple characters._(Underscore): Represents a single character.
| Pattern | Description | Example |
|---|---|---|
a% | Starts with 'a' | apple, ant |
%a | Ends with 'a' | banana, data |
%or% | Contains 'or' at any position | orange, world |
_r% | Has 'r' in the second position | area, oracle |
a__% | Starts with 'a' and is at least 3 characters long | abc, anchor |
a%o | Starts with 'a' and ends with 'o' | audio, alumno |
3. Advanced Usage
- NOT LIKE: Used to exclude rows that match a specific pattern.
- Example:
WHERE name NOT LIKE 'A%'(finds names not starting with A).
- Example:
- ESCAPE Clause: To search for literal
%or_characters, you must use an escape charater.- Example:
WHERE discount LIKE '10!%' ESCAPE '!'finds values that literally contain '10%'.
- Example:
- Case Sensitive: By default,
LIKEbehavior depends on the database collation. In SQL Server, it is often case-insensitive, while in PostgreSQL, it is case-sensitive (useILIKEfor case-insensitive).
4. LIKE WITH INDEXES
Standard B-Tree indexes only optimize LIKE queries if the search pattern is left-anchored (starts with constant charaters).
- Index-friendly (
prefix%): A query likeWHERE name LIKE 'abc%'allows the database to perform an Index Seek. It treats the prefix as a range. - Index-Hostile (
%suffixor%middle%): Patterns starting with a wildcard, likeWHERE name LIKE '%abc', usually force a Full Table Scan or Full Index Scan because the engine cannot determine a starting point in the sorted index. - Optimize Tip: For non-prefix searches, consider using PostgeSQL Trigram GIN indexes or Full-Text Search features available in mordern RDBMS.
