tic tic - 1 year ago 65
SQL Question

How to write an SQL statement to use "LIKE" for nine different values?

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%'

, ...,
are parameters which the user can put in a form before submitting the query. They are (not subsequent) numerical codes, and
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
rather than equals.

Answer Source

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.