简体   繁体   中英

How to write a select query which will return records if condition in where clause satisfies all the values

I have a requirement where I need to write a select query which will return records if condition in where clause satisfies all the values.

for eg:

I have employee table, with three reocords, lets assume Name is the one column( having three records 'A', 'B', 'C')

select * from emp where Name in ('A', 'B', 'D') --- it should not return any values as D value is not there, please suggest me the select query

using IN will return rows where any of the conditions are met, as if you used OR.

select * from emp where Name in ('A', 'B', 'D')

is equal to:

select * from emp where Name = 'A' OR Name = 'B' OR Name = 'D'

If your emp-table only has 'A', 'B' and 'C', the result should be: 'A' and 'B' rows.

If you want result to show none records or all records, that is not easy with a single SQL select, you will have to use Oracle/PLSQL if-then-else, something like this:

IF (select count(*) from emp where name in ('A', 'B', 'C')) = 3 THEN
    select * from emp where name in ('A', 'B', 'C')
ELSE
    select * from emp where name is null
END IF;

The else-part here is added just to return an empty dataset, assuming none records has NULL value in the name column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM