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

Get record from SQL Server from two tables with optimized code

I have two tables – one is Product and the other is Productimage. In product image table, more than one image can exist of every product. Every image set ISDEAULT 1 or 0. Now I want every product from product table whose all image’s ISDEAULT is 0.

I wrote this query

SELECT DISTINCT(pd.ProductId) 
FROM Product pd
INNER JOIN ProductImage img ON img.ProductId =  pd.ProductId
WHERE NOT EXISTS (
    SELECT pdi.ProductId 
    FROM ProductImage pdi 
    WHERE pdi.IsDefault = 1 
    AND pdi.ProductId = pd.ProductId
)

It works correctly but my senior told me to use another approach.

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

Please give me optimized query

>Solution :

You can use conditional aggregation to check for IsDefault = 1

This means you are only querying the ProductImage table once

SELECT  pd.ProductId
FROM Product pd
JOIN ProductImage img ON img.ProductId =  pd.ProductId
GROUP BY
  pd.ProductId
HAVING COUNT(CASE WHEN img.IsDefault = 1 THEN 1 END) = 0;

If you don’t care if it has any ProductImage then you can just do

SELECT  pd.ProductId
FROM Product pd
WHERE NOT EXISTS (SELECT 1
    FROM ProductImage img
    WHERE img.ProductId =  pd.ProductId
    AND img.IsDefault = 1);
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