SQL query return all from a table if X but not Y
We can build on your attempt:
SELECT od.order_id
FROM order_detail od
WHERE od.stock_code LIKE '0005-%' AND
NOT EXISTS (SELECT 1
FROM ORD_DETAIL od2
WHERE od2.order_id = od.order_id AND
od2.price_code LIKE 'PRC%'
);
The particular changes are:
- The condition on
stock_code
is in the outer query not the subquery. - The condition for price code is
NOT EXISTS
rather thanEXISTS
-- the order should not have such a row. - The condition in the subquery is
LIKE
notNOT LIKE
.
You could use aggregation and a having
clause with conditional expressions:
select order_id
from order_detail
group by order_id
having
max(case when stock_code like '0005-%' then 1 end) = 1
and max(case when price_code like 'PRC%' then 1 end) is null
This will give you all (unique) id
s for which (at least) a record exists where stock_code = '0005'
and no record exists where price_code
starts with 'PRC'
.