List of special characters for SQL LIKE clause
The LIKE
clause in SQL uses %
and _
as special characters, with %
matching any sequence of characters and _
matching any single character. To search these literals, they need to be escaped, typically with a backslash \
. Here's the syntax:
Searching for literal percent:
Searching for literal underscore:
The ESCAPE
character can be changed as deemed necessary.
Extended character matching and negation
A feature in some SQL flavors, []
and [^]
notations allow matching any single character within, or outside, a specified set respectively. However, not universally supported.
Search within character range:
Search outside character range:
The outcomes of using character sets could be affected by the database collation, changing how ranges are recognized.
Dialects of SQL: special symbols
Special characters can vary across SQL dialects. For instance, PostgreSQL provides SIMILAR TO
operator which enables regular expression patterns:
PostgreSQL's SIMILAR TO
This code uses special characters |
for alternatives, *
for repetitions, and +
and ()
for grouping.
Real-world use cases and potential pitfalls
The implementation of special characters boosts search capabilities but complicates DBMS portability. Be wary of:
- Escaping literals: Different databases escape
LIKE
wildcards differently ('\'
,'!'
,'[]'
). Check the documentation accordingly. - Case sensitivity: For instance, SQL Server is case insensitive by default, PostgreSQL isn't. A pattern like
'A%'
may yield different results. - Database collation: Impacts how ranges (
[a-c]%
) are interpreted in theLIKE
clause.
Rooms for caution
Ensure caution to prevent wildcard injection where unsanitised user input could introduce expensive wildcard searches.
Also, leading wildcards (LIKE '%term'
) can be performance-intensive, as they may need to perform full table scans.
Trust the Book (documentation)
This answer provides a rock-solid foundation, however, the official documentation for your database system will be the definitive guide. They might contain unique nuances or additional special characters.
Spreading Knowledge
Forge a community wiki for SQL LIKE clause special characters. This would be a living document on idiosyncrasies across different databases and a testament of your collaborative spirit.
Was this article helpful?