Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgress how to query with not in for multiple column

I want to select from table C all items ID where column A "item_a_id" and column B "item_b_id" not in result of another query.

currently I use this query twice , i didnt find a way how to query it without the using same query twice.

This is my query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * from table_c c
WHERE c.item_a_id NOT IN 
(
 SELECT a.item_id,b.item_id 
 FROM table_a a 
 JOIN table_b b on a.item_id = b.item_id
) 
AND c.item_b_id NOT IN 
(
 SELECT a.item_id,b.item_id 
 FROM table_a a 
 JOIN table_b b on a.item_id = b.item_id
) 

and this is how I want to improve it (ofc this is not sql syntax and just an example)

SELECT * from table_c c
WHERE c.item_a_id AND c.item_b_id NOT IN 
(
 SELECT a.item_id,b.item_id 
 FROM table_a a 
 JOIN table_b b on a.item_id = b.item_id
) 

>Solution :

You need to enclose the columns on the left hand side in parentheses:

WHERE (c.item_a_id, c.item_b_id) 
      NOT IN (SELECT a.item_id,b.item_id 
              FROM table_a a 
               JOIN table_b b on a.item_id = b.item_id) 

But typically NOT EXISTS conditions are faster than NOT IN

WHERE NOT EXISTS (SELECT *
                  FROM table_a a 
                    JOIN table_b b on a.item_id = b.item_id
                  WHERE a.item_id = c.item_a_id 
                    AND b.item_id = c.item_b_id)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading