tags:

views:

54

answers:

2

I'm don't have much experience in writing SQL so maybe this is a fairly trivial question but right now I have a SQL query where need to do a 'like' on multiple fields, at present I do:

select * 
from tableX  
where col1 like '10%' 
   or col2 like '10%' 
   or col3 like '10%'  
   or col4 like '10%'  
   or col5 like '10%'  
   or col6 like '10%' 

Is there different, that is simpler or better, way of writing the SQL?

Thanks

+2  A: 
select * from tableX where col1 like '10%'
UNION
select * from tableX where col2 like '10%'
UNION
select * from tableX where col3 like '10%'
...

If you were comparing one col against multiple values, then there are other options, such as

SELECT *
FROM
   tableX t1
   JOIN
   tableFilter TF ON t1.col LIKE TF.FilterValue
gbn
A: 

By better do you mean faster?

I expect the following could be faster but sql might already optimize it:

select * 
from tableX  
where substring(col1,0,2) = '10' 
   or substring(col2,0,2) = '10' 
   or substring(col3,0,2) = '10' 
   or substring(col4,0,2) = '10' 
   or substring(col5,0,2) = '10' 
   or substring(col6,0,2) = '10' 

a lot depends on what you are doing, if you are doing this a lot and each column starts with a two character code then you might want to split that value into it's own column.

Hogan
The function on the column will remove any chance of index use. The LIKE will at least allow that (even with OR)
gbn
@gbn : you got me -- I've no idea how it would be possible to do anything other than a seek when using a LIKE. Are you saying that there is some way to query an index for column values like x? My understanding of an index is it has an order and it can find things of a value given that ordering. Please enlighten me.
Hogan
@Hogan: Like can seek, the substring will scan
gbn
@gbn: Can you provide a reference for this -- how can the like operator do a seek? There is no value for '10%' for it to seek to.
Hogan
1. http://myitforum.com/cs2/blogs/jnelson/archive/2007/11/16/108354.aspx 2. http://msdn.microsoft.com/en-us/library/ms998577.aspx "Avoid Expensive Operators Such as NOT LIKE"
gbn
Of course like can only use the index if you specify the first character.
HLGEM
@gbh, @HLGEM: Thanks, I stand corrected.
Hogan