tags:

views:

312

answers:

2

I want to write similar SQL below

select * from tbl where col like ('ABC%','XYZ%','PQR%');

i know it can be done using OR. But i want to know is there any better solution.

+6  A: 

Here is an alternative way:


select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';

Here is the test code to verify:


create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col      |
+----------+
| ABCDEFG  |
| XYZ      |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)
Asaph
It is important to know the difference between UNION and UNION ALL. I'd suggest you UNION ALL would be better in this case.
David
Actually in this case UNION is the correct choice. UNION ALL would potentially include duplicates depending on what goes in the LIKE portion of the query. Imagine SELECT ... LIKE 'ABC%' ... UNION ALL SELECT ... LIKE 'ABCD%' would potentially return duplicates.
Asaph
+6  A: 

This is a good use of a temporary table.

CREATE TEMPORARY TABLE patterns (
  pattern VARCHAR(20)
);

INSERT INTO patterns VALUES ('ABC%'), ('XYZ%'), ('PQR%');

SELECT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);

In the example patterns, there's no way col could match more than one pattern, so you can be sure you'll see each row of tbl at most once in the result. But if your patterns are such that col could match more than one, you should use the DISTINCT query modifier.

SELECT DISTINCT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
Bill Karwin