tags:

views:

79

answers:

2

I have to select all the records where:

where FIELD2 like '%value21%'
or FIELD2 like '%value22%'
or FIELD2 like '%value23%'
-- repeat up to
or FIELD2 like '%value29%'

Here, value21, ..., value29 are parameters which the user can put in a form before submitting the query. They are (not subsequent) numerical codes, and FIELD2 is a database column holding a string value.

Which is the most compact form to write down my SQL query?

Note: this is related to an earlier question, but this needs LIKE rather than equals.

+6  A: 

I'm afraid you're stuck with:

  WHERE (FIELD2 LIKE '%value21' OR 
         FIELD2 LIKE '%value22' OR 
         FIELD2 LIKE '%value23' ...)

at least in standard SQL (your particular engine might offer some form of full-text indexing that would help).

A query like this often indicates a normalization problem in your database design with multiple values stored in a single field value. If that's true in your case and you have any degree of control over the database schema, I advise fixing the problem as soon as possible. Otherwise check your medical coverage to make sure it covers SQL-induced psychosis — this can drive you crazy.

Larry Lustig
+1 for "I advise fixing the problem as soon as possible". Good advice
Chris Lively
Uh, are there problems you would not recommend fixing?
Robus
@Robus: any where the solution is more costly than the continuing problem.
Mark Bannister
A: 

One way:

select Field1, Field2 from Table where Field2 like '%val%'
UNION
select Field1, Field2 from Table where Field2 like '%val2%'
UNION
select Field1, Field2 from Table where Field2 like '%val2%'

etc.

Chris Lively
Not UNION ALL, I think, since some rows may match several different conditions. I think a "regular" UNION as long as the PK is included in the list of selected fields.
Larry Lustig
@Larry: adjusted accordingly. thanks
Chris Lively