Search code examples
sqlsql-likesql-in

Match a list of patterns using SQL IN and LIKE


Is it possible to match a list of patterns in SQL?

I know of the following way to match a single pattern:

SELECT * FROM table where title LIKE '%match%'

This can be expanded like:

SELECT * FROM table 
where title LIKE '%match%' OR title LIKE '%match2%'

... etc

I have a long list of patterns, is it possible to use 'IN' in any way, to make the code more readable?

Something more as this

SELECT * FROM table where title LIKE IN (match, match2, match3)

or am i forced to write lots of "OR"'s?

Edit: Was using SQL-Alchemy (Python library) to connect to Microsoft SQL Server.


Solution

  • Sure! There is a way to do it in Microsoft SQL Server.

    SELECT *
     FROM employees
     WHERE last_name LIKE 'match_' 
    

    where _ can be any other letter but also you can be more specific to more complicated patterns

     SELECT * FROM titles WHERE title LIKE '[a-t]itanic'
    

    Here you will get all those combinations aitanic etc. But I think that the easiest way to do it is just to match everything as you've said by %text% and applying OR