Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I introduce multiple conditions in LIKE operator?

Tags:

sql

oracle

I want to write an SQL statement like 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.

like image 682
Madhu Avatar asked Sep 07 '09 05:09

Madhu


People also ask

How do you do multiple conditions in like?

select * from employee where name like '%aa%' or name like '%bb% or name like '%cc%'..... Next row NAME Column Contains aa bb cc dd..... each value in the NAME column and put in the multiple like operator using OR condition.

How do you do multiple like conditions in SQL?

Using the LIKE operator, you can specify single or multiple conditions. This allows you to perform an action such as select, delete, and updating any columns or records that match the specified conditions. It is mainly paired with a where clause to set the conditions.

How can we use multiple values in like operator?

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.

Can we use multiple LIKE operator in SQL?

Not only LIKE, but you can also use multiple NOT LIKE conditions in SQL. You will get records of matching/non-matching characters with the LIKE – this you can achieve by percentile (%) wildcard character. Below use cases, help you know how to use single and multiple like conditions.


1 Answers

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); 
like image 130
Bill Karwin Avatar answered Oct 05 '22 05:10

Bill Karwin