SQL LIKE Operator with Examples – Using Wildcards

SQL Like operator can find string of text based on a certain pattern. It is most usually used in clause WHERE. But it can be applied in any part of SQL query, for example in SELECT, UPDATE or DELETE. T-SQL LIKE has the following syntax:

Syntax:

SELECT <Column 1>
FROM dbo.Table
WHERE <Column 1> LIKE <patern>;

Operator can be used to apply negatively restricted requirements. We would use NOT LIKE in this case but the principle is still the same.

Wildcards Used in LIKE Operator

Operator enables application of multiple wildcards that make us able to create text patterns.

1 Percent (wildcard %) – any text including empty text. The syntax to search for a pattern that begins with the character “D” would be as follows:

SELECT <Column 1>
FROM dbo.Table
WHERE <Column 1> LIKE 'D%';

2 Underscore (wildcard_) – Wildcard represents 1 character. We can represent any number of characters (use underscore multiple times and obviously combine with “%”). As an example – we want all values having letter X as its third letter. Every of 2 previous and n following characters can be arbitrary.

SELECT <Column 1>
FROM dbo.Table
WHERE <Column 1> LIKE '__D%';

3 List of characters [wildcard <list>] – If we would use previous step as an example except that we would want the 3rd character to be D or E, it would look like this:

SELECT <Column 1>
FROM dbo.Table
WHERE <Column 1> LIKE '__[DE]%';

4 Character range [wildcard <char>-<char>] – Wildcard of range type is separated by a dash. It can be used for numbers as for text characters. Below, you can see script syntax where we want first character to be a number, fourth character to be D and following characters to be arbitrary:

SELECT <Column 1>
FROM dbo.Table
WHERE <Column 1> LIKE '[0-9]__[D]%';

Conclusion: This tutorial describes how to use LIKE operator to find text string in sql that would adhere to some pattern. Patterns are searched for using WILDCARDS representative characters

Rate this post
Category: SQL Operators

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *