The "like" operator is used in a "where" clause to search for a specified pattern of characters using the wildcard mechanism in a column. Wildcard characters make the "like" operator more flexible than using = and != (Not Equal To) string comparison operators. To search for a character string using one or more wildcard characters in a LIKE query, simply include the wildcards in a string literal along with the portion of the string. So let's take a look at a practical example of how to use a like operator to search in SQL Server. The example is developed in SQL Server 2012 using the SQL Server Management Studio.
Wildcard Characters
There are four types of wildcard characters in SQL Server:
- Percent sign (%)
- Underscore (_)
- Bracket ([])
- Caret (^)
Creating a Table in SQL Server
The table looks as in the following figure:
Now we perform searching on the above table using wildcard characters.
Like with Percent sign (%)
It is used to search any string of zero or more characters.
- SELECT * FROM UserDetail WHERE FirstName LIKE 'ra%'
-
- SELECT * FROM UserDetail WHERE FirstName LIKE '%n'
-
- SELECT * FROM UserDetail WHERE FirstName LIKE '%an%'
The result table will show the following information:
Like with Underscore (_)
It is used to search for a single character.
- SELECT * FROM UserDetail WHERE FirstName LIKE 'rah_'
-
-
- SELECT * FROM UserDetail WHERE FirstName LIKE '_ahu'
-
-
- SELECT * FROM UserDetail WHERE FirstName LIKE '__e'
-
The result table will show the following information:
Like with Bracket ([])
It is used to search for any single character within the specified range.
- SELECT * FROM UserDetail WHERE FirstName LIKE '[rc]%'
-
-
- SELECT * FROMUserDetail WHERE FirstName LIKE '[rc]%u'
-
-
- SELECT * FROM UserDetail WHERE FirstName LIKE 'R[a]%'
-
The result table will show the following information:
Like with Caret (^)
It is used to search for any single character that is not the specified character.
- SELECT * FROM UserDetail WHERE FirstName LIKE 'R[^H]%'
-
- SELECT * FROM UserDetail WHERE FirstName LIKE '%N[^R]'
-
The result table will show the following information: