SQL LIKE
This is a tutorial for the SQL LIKE operator, with examples.The LIKE operator is used to test character data to see if it matches a given pattern.
Sample Data
The examples in this article need some sample data. The following script creates and populates the test table:Matching Multiple Characters
The simplest, and most common, use is with the % wildcard character. This matches zero, one or more characters.The most efficient way, which will use an index if one exists, is to precede the % with as many characters as are known:
This returns:
abcde
abcee
abcfe
abcge
Any number of wildcards can be included:
This returns:
abcfe
Matching a Single Character
The underscore character (_) represents one, and exactly one, character:This returns
abcde
Matching a Selection or Range of Characters
A list of characters within square brackets means that the character at that position must be one of those listed. For example:returns:
abcde
abcee
abcfe
You may also specify a range using the hyphen (-):
returns:
abcee
abcfe
abcge
And the ^ character means NOT one of the characters specified:
returns:
abcge
Escape Characters
An escape character allows you to tell the query parser to treat a wildcard as a normal character, and not interpret it as a wildcard. First add a new row:Suppose you want rows starting with the characters "ab%". This doesn't work:
Because it matches all these rows:
abcde
abcee
abcfe
abcge
ab% off
The trick is to specify that the first % is to be treated as the character "%". This is done by placing another character just before it. In my example I will use "*" as the escape character, but any character not in the string will do. Try the following:
Summary
This article has described, with the aid of examples, how to use the SQL LIKE operator.For a further explanation of how it can affect performance, I have covered its use in SQL WHERE Clause Optimization.
Not found what you're looking for?
Use this search box. It is tuned for SQL Server searches. Try it and see!Do you have a question about SQL Server? Would you like to answer a question?
Go to the SQL FAQ to get started.

