RE:cord

[SQL] Finding Unsold Products (한 번도 팔리지 않은 제품 찾기) (IS NULL / NOT EXIST) 본문

SQL

[SQL] Finding Unsold Products (한 번도 팔리지 않은 제품 찾기) (IS NULL / NOT EXIST)

beie 2024. 12. 14. 18:41

<1>

IS NULL

SELECT PRO.ProductID, SOD.ProductID, PRO.Name
FROM Production.Product AS PRO
	LEFT JOIN Sales.SalesOrderDetail AS SOD
	ON PRO.ProductID = SOD.ProductID
WHERE SOD.ProductID IS NULL

 

<2>

NOT EXISTS

SELECT P.ProductID, P.Name
FROM Production.Product AS P
WHERE NOT EXISTS (
    SELECT 1
    FROM Sales.SalesOrderDetail AS SOD
    WHERE SOD.ProductID = P.ProductID
)

* Using SELECT 1 is more efficient than SELECT *, as we do not need all columns when using subqueries to check for the existence of rows.