SQL Server Like operator

I have been using SQL Server for almost 10 years, and I just learned something new using the LIKE operator. You can search any single character within a specified range by using a bracket [ ]. Lets look below to see what I mean.

Most people know how to do a wildcard search where you provide the first letter or letters of what you are searching for. Below, I am searching for any city that starts with the letter W.

If you want to search for multiple letters you need to either use a union or union all and this just repeats code.

You can also use the OR command, but this can get confusing if you nest multiple items in the WHERE clause.

This is what I learned. If you use LIKE with the [ ]’s, you can search multiple letters all in the same statement.

Below I am querying all cities that start with a W R or B. Look how easy that is.

If you want to search a range of letters, check this out.

Below, I am searching for all cities between the letters M and P. So in this example it is going to return cities that start with these letters: M, N, O, P.

A lot of you might know this trick already, but I found it by READING THE DOCUMENTATION! You can find everything in the docs and then you can experiment and see what things do.

To read more about the LIKE command, follow this link: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-ver15

Happy reading!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s