Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to combine IN with LIKE in an SQL statement?

Tags:

sql

I am trying to find a way, if possible, to use IN and LIKE together. What I want to accomplish is putting a subquery that pulls up a list of data into an IN statement. The problem is the list of data contains wildcards. Is there any way to do this?

Just something I was curious on.

Example of data in the 2 tables

Parent table

ID    Office_Code   Employee_Name
1     GG234         Tom
2     GG654         Bill
3     PQ123         Chris

Second table

ID    Code_Wildcard
1     GG%
2     PQ%

Clarifying note (via third-party)

Since I'm seeing several responses which don't seems to address what Ziltoid asks, I thought I try clarifying what I think he means.

In SQL, "WHERE col IN (1,2,3)" is roughly the equivalent of "WHERE col = 1 OR col = 2 OR col = 3".

He's looking for something which I'll pseudo-code as

 WHERE col IN_LIKE ('A%', 'TH%E', '%C')

which would be roughly the equivalent of

 WHERE col LIKE 'A%' OR col LIKE 'TH%E' OR col LIKE '%C'

The Regex answers seem to come closest; the rest seem way off the mark.

like image 419
Ziltoid Avatar asked Mar 04 '09 14:03

Ziltoid


People also ask

Can you combine in and like in SQL?

Kevin is right, you cannot combine the in and like items as you've done it. Full text might help, but you'll still be building a string with multiple and statements for your CONTAINS (or other predicate) statement.

How do I create a multiple like condition in SQL?

Description. The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement. When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.

How use LIKE operator in SQL for multiple values?

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one or multiple characters. The underscore represents a single number or character.


2 Answers

I'm not sure which database you're using, but with Oracle you could accomplish something equivalent by aliasing your subquery in the FROM clause rather than using it in an IN clause. Using your example:

select p.*
from
  (select code_wildcard
   from second
   where id = 1) s
  join parent p
      on p.office_code like s.code_wildcard
like image 182
Shawn Loewen Avatar answered Sep 22 '22 11:09

Shawn Loewen


In MySQL, use REGEXP:

WHERE field1 REGEXP('(value1)|(value2)|(value3)')

Same in Oracle:

WHERE REGEXP_LIKE(field1, '(value1)|(value2)|(value3)')
like image 28
Quassnoi Avatar answered Sep 19 '22 11:09

Quassnoi