Link to home
Start Free TrialLog in
Avatar of rajeeva_nagaraj
rajeeva_nagaraj

asked on

SQL Query

Hi,

I have a table item_info which has following records



I need a query which can return only those items for which the commit_ind was never = 1

if you see the table, we can see that the item 2 has commit ind as 0 and the other record has commit ind as 1, i dont need such records, i want a query to return items for which commit_ind was never = 1.

Thanks in advance,
Rajeeva
Avatar of Naveen Kumar
Naveen Kumar
Flag of India image

can you try this :

select a.item_id from your_table a
where not exists ( select 1 from your_table b
where b.item_id = a.item_id
and b.commit_ind = 1 )

if you do not want duplicates item_ids in the output, then you can even use distinct along with it.

select distinct a.item_id from your_table a
where not exists ( select 1 from your_table b
where b.item_id = a.item_id
and b.commit_ind = 1 )

Thanks,
Can be formulated quite the way you say it in SQL:

Select Distinct ii1.item_id from item_info ii1
WHERE NOT EXISTS (SELECT * From item_info ii2 Where ii2.[item id] = ii1.[item id] AND ii2.commit_ind=1);

Bye, Olaf.
ASKER CERTIFIED SOLUTION
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rajeeva_nagaraj
rajeeva_nagaraj

ASKER

Thanks for you reply, both the queries were correct. I have chosen one because i wanted the result out of a single query.
Well, you choose against a good indicator the EXISTS query is better, because two people recommended it independent of each other. Anyway, the SUM solution is somewhat elegant, but less expandable to other situations.

Let me show you why it could take much longer than a query with a subquery. If you have many records for the same item id, the EXISTS will only need to find one exception to exclude an id, while the SUM will sum all. You think along the lines a partial sum being >0 already exits further summings, but negative summands are possibly making the final sum 0, so it isn't exited early, all records are summed.

You're having a self join being very explicit about what should not exist and it will be faster in more cases.

At least don't make such thumb rule decisions about which query is better. Never turn off thinking just because of an indicator.

Bye, Olaf.