Subscribe to How-To Geek

Search For Rows With Special Characters in SQL Server

While troubleshooting a programming problem today I noticed that you can’t use a LIKE search for string columns containing special characters like % or _ without using a special syntax. Figuring out the problem took only a few minutes, but remembering syntax is always easier if you write about it.

So yes, this post is solely for my benefit. Hopefully it will help somebody else too.

Let’s say you want to find any fields that contain the text “100%”, so you put together this query:

SELECT * FROM tablename WHERE fieldname LIKE ‘%100%%’

Instead of what you wanted, you’ll get all the rows that contain “100″ as well as the rows that contain “100%”.

The problem here is that SQL Server uses the percent sign, underscore, and square brackets as special characters. You simply can’t use them as a plain character in a LIKE query without escaping them.

Square Bracket Escape

You can surround the % or _ with square brackets to tell SQL Server that the character inside is a regular character.

SELECT * FROM tablename WHERE fieldname LIKE ‘%100[%]%’

T-SQL ESCAPE Syntax

Alternatively, you can append the ESCAPE operator onto your query, and add a \ character before the value you want to escape.

SELECT * FROM tablename WHERE fieldname LIKE ‘%100\%%’ ESCAPE ‘\’

The ESCAPE ‘\’ part of the query tells the SQL engine to interpret the character after the \ as a literal character instead of as a wildcard.

Personally I find the second method easier to deal with, and you can use it to escape a square bracket as well.

The Geek is the founder of How-To Geek and a geek enthusiast. This article was written on 11/8/07 and tagged with: The Geek Blog

Daily Email Updates

You can get our how-to articles in your inbox each day for free. Just enter your name and email below:


Name:
Email:
Similar Articles Featured Wiki Articles
Latest Software Reviews Quick Linux Tips
Geek Arcade Popular Forum Threads

Comments (2)

  1. Whatever-ishere

    thanks for the GREAT post! Very useful…

  2. Ashutosh Mahamia

    This write up was extremely beneficial for me . Thanks for writing it. Keep it up.


Leave a Comment




Leave your friendly comment here.

If you have a computer help question, click here to leave it on the forums instead.

Note: Your comment may not show up immediately on the site.

Sponsored Links
Getting Started
About How-To Geek
What Is That Process?
svchost.exe
jusched.exe
dwm.exe
ctfmon.exe
wmpnetwk.exe
wmpnscfg.exe
rundll32.exe
wfcrun32.exe
Ipoint.exe
Itype.exe
Wfica32.exe
Mobsync.exe
Cmd.exe
Dpupdchk.exe Adobe_Updater.exe

Copyright © 2006-2009 HowToGeek.com. All Rights Reserved.