Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine IN operator with LIKE condition (or best way to get comparable results)

I need to select rows where a field begins with one of several different prefixes:

select * from table 
where field like 'ab%' 
  or field like 'cd%' 
  or field like "ef%" 
  or...

What is the best way to do this using SQL in Oracle or SQL Server? I'm looking for something like the following statements (which are incorrect):

select * from table where field like in ('ab%', 'cd%', 'ef%', ...)

or

select * from table where field like in (select foo from bar)

EDIT: I would like to see how this is done with either giving all the prefixes in one SELECT statement, of having all the prefixes stored in a helper table.

Length of the prefixes is not fixed.

like image 833
tputkonen Avatar asked Nov 27 '22 19:11

tputkonen


2 Answers

Joining your prefix table with your actual table would work in both SQL Server & Oracle.

DECLARE @Table TABLE (field VARCHAR(32))
DECLARE @Prefixes TABLE (prefix VARCHAR(32))

INSERT INTO @Table VALUES ('ABC')
INSERT INTO @Table VALUES ('DEF')
INSERT INTO @Table VALUES ('ABDEF')
INSERT INTO @Table VALUES ('DEFAB')
INSERT INTO @Table VALUES ('EFABD')

INSERT INTO @Prefixes VALUES ('AB%')
INSERT INTO @Prefixes VALUES ('DE%')

SELECT  t.*
FROM    @Table t
        INNER JOIN @Prefixes pf ON t.field LIKE pf.prefix 
like image 112
Lieven Keersmaekers Avatar answered Dec 10 '22 03:12

Lieven Keersmaekers


you can try regular expression

SELECT * from table where REGEXP_LIKE ( field, '^(ab|cd|ef)' );
like image 26
ghostdog74 Avatar answered Dec 10 '22 03:12

ghostdog74