Finding the Hidden Meaning: How to Escape Underscores in SQL Server Queries
- In SQL Server's
LIKE
operator, used for pattern matching in queries, certain characters have special meanings:%
: Matches zero or more of any character._
: Matches any single character.
When to Escape Underscores
- If you want to search for an actual underscore (
_
) within your data, you need to escape it. This is because the underscore is a wildcard by default.
Escaping Methods
-
Backslash ():
- Precede the underscore with a backslash (
\
) to treat it literally. - Example:
SELECT * FROM MyTable WHERE Name LIKE '%\_smith%' ESCAPE '\'
- Precede the underscore with a backslash (
-
Character Brackets ([]):
- Enclose the underscore within square brackets (
[]
) to treat it as a single character.
- Enclose the underscore within square brackets (
Choosing the Right Method
- Both methods achieve the same result.
- Backslash escaping is often preferred due to its wider compatibility across different database systems.
- Character bracket escaping might be more readable for simpler patterns.
Example:
Suppose you have a table named People
with a Name
column containing values like "John_Doe", "Jane_Smith", and "Alex Jones".
-
To find names containing an underscore, use:
SELECT * FROM People WHERE Name LIKE '%\_%';
This will return "John_Doe" and "Jane_Smith".
Additional Considerations
- The escape character you choose (
\
in this case) can be any valid character that won't conflict with your pattern. - Be mindful of escaping other special characters if they appear in your search pattern.
-- Find names containing an underscore
SELECT * FROM People WHERE Name LIKE '%\_% ESCAPE '\' ESCAPE '\';
-- Find names starting with "Alex_" (underscore included)
SELECT * FROM People WHERE Name LIKE '\_Alex%' ESCAPE '\';
Character Bracket Escape:
-- Find names containing an underscore
SELECT * FROM People WHERE Name LIKE '%[_%]';
-- Find names starting with "Alex_" (underscore included)
SELECT * FROM People WHERE Name LIKE '[_]Alex%';
Explanation:
- The
ESCAPE '\'
clause specifies the backslash (\
) as the escape character in both methods. - In the first example of each method,
%\_%
searches for any string containing an underscore (_
). - In the second example,
\_Alex%
(with backslash escape) or[_]Alex%
(with character bracket escape) searches for names starting with "Alex_" (including the underscore).
-
Regular Expressions (SQL Server 2017 and Later):
-
Avoiding
LIKE
Operator Altogether:
sql-server