In SQL I (sadly) often have to use "LIKE
" conditions due to databases that violate nearly every rule of normalization. I can't change that right now. But that's irrelevant to the question.
Further, I often use conditions like WHERE something in (1,1,2,3,5,8,13,21)
for better readability and flexibility of my SQL statements.
Is there any possible way to combine these two things without writing complicated sub-selects?
I want something as easy as WHERE something LIKE ('bla%', '%foo%', 'batz%')
instead of this:
WHERE something LIKE 'bla%'
OR something LIKE '%foo%'
OR something LIKE 'batz%'
I'm working with SQl Server and Oracle here but I'm interested if this is possible in any RDBMS at all.
In Oracle RBDMS you can achieve this behavior using REGEXP_LIKE function.
The following code will test if the string three is present in the list expression one|two|three|four|five (in which the pipe "|" symbol means OR logic operation).
Preceding expression is equivalent to:
So it will succeed.
On the other hand, the following test will fail.
There are several functions related to regular expressions (REGEXP_*) available in Oracle since 10g version. If you are an Oracle developer and interested this topic this should be a good beginning Using Regular Expressions with Oracle Database.
Starting with 2016, SQL Server includes a
STRING_SPLIT
function. I'm using SQL Server v17.4 and I got this to work for me:Use an inner join instead:
I was also wondering for something like that. I just tested using a combination of
SUBSTRING
andIN
and it is an effective solution for this kind of problem. Try the below query :One approach would be to store the conditions in a temp table (or table variable in SQL Server) and join to that like this:
In Teradata you can use
LIKE ANY ('%ABC%','%PQR%','%XYZ%')
. Below is an example which has produced the same results for me