Skip to content
Advertisement

SQL where clause to check if all selected column value is in a subquery select

Does the select concept below can be translated into an sql select?

select S_ID from table1 where S_Type = TYPE and all S_ID in (select S_ID from table2)

The concept of this is like below:

item1, item2, and item3 should all be in (select ITEMS from table)

The select statement should only return a row/s if all S_ID is in (select S_ID from table2)

Advertisement

Answer

If you want S_IDs all of whose items are in the second table, then use aggregation

select t1.S_ID
from table1 t1
where t1.S_Type = 'TYPE' and
      t1.item in (select t2.item from table2 t2)
group by S_ID
having count(distinct t1.item) = (select count(distinct t2.item) from table2 t2);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement