Romesh
Romesh

Reputation: 2274

Shorten SQL Syntax of LIKE Clause to IN Clause

In SQL, Is there any way to Shorten syntax From

Select * from TableName
where ColumnName like '%A%' or ColumnName like '%B' or ColumnName like 'C%'

To

Select * from TableName
where ColumnName in ('%A%','%B','C%')

It is not feasible to write same column name in Where clause with OR again and again.

Upvotes: 0

Views: 213

Answers (1)

gbn
gbn

Reputation: 432200

No there isn't a way to combine LIKE with IN directly

There are ways around this, like this example for SQL Server

Select *
from
   TableName T
   JOIN
   (VALUES ('%A%'),('%B'),('C%')) AS X(Expression) ON T.ColumnName LIKE X.Expression

This changes multiple OR search conditions into rows and a JOIN

Or you can use a UNION to combine several queries in one

Select * from TableName
where ColumnName like '%A%'
union
Select * from TableName
where ColumnName like '%B'
union
Select * from TableName
where ColumnName like 'C%'

Upvotes: 2

Related Questions