SQL Server: How to Combine LIKE and IN Operators in a Query

SQL Server: How to Combine LIKE and IN Operators in a Query

You can use the combination of LIKE and IN in SQL to search for values that match a pattern and are contained in a list of values. Here’s an example:

sql
SELECT * FROM my_table
WHERE column1 LIKE '%pattern%'
AND column2 IN ('value1', 'value2', 'value3');

In this example, LIKE ‘%pattern%’ searches for values in column1 that contain the word “pattern”. The % is a wildcard that matches any number of characters before or after the word “pattern”.

The IN (‘value1’, ‘value2’, ‘value3’) clause checks if the value in column2 is one of the values in the list (‘value1’, ‘value2’, ‘value3’).

Together, these clauses will return all rows where column1 contains the word “pattern” and column2 has one of the specified values.

You can also use the NOT keyword to negate either or both conditions:

sql
SELECT * FROM my_table
WHERE column1 NOT LIKE '%pattern%'
OR column2 NOT IN ('value1', 'value2', 'value3');

This example returns all rows where column1 does not contain the word “pattern” or column2 does not have one of the specified values.

Al Mahbub Khan
Written by Al Mahbub Khan Full-Stack Developer & Adobe Certified Magento Developer

Full-stack developer at Scylla Technologies (USA), working remotely from Bangladesh. Adobe Certified Magento Developer.