LEFT JOIN vs. WHERE NOT EXITS

My solution:

first create a query showing all the products from order in 1997-04:

select distinct order_details.productid, products.productname 
from order_details 
inner join orders on orders.orderid=order_details.orderid 
inner join products on order_details.productid=products.productid 
where orders.orderdate between '1997-04-01' and '1997-04-30' 
order by productid;

Then select all products leaving out the products that where sold in 1997-04:

select p.productid, p.productname
from products p
left join (
  select order_details.productid 
  from order_details 
  inner join orders on orders.orderid=order_details.orderid 
  inner join products on order_details.productid=products.productid 
  where orders.orderdate between '1997-04-01' and '1997-04-30' 
  ) x on x.productid = p.productid
where x.productid is null
order by p.productid
;

output:

 productid |         productname
-----------+------------------------------
         3 | Aniseed Syrup
         5 | Chef Anton's Gumbo Mix
         6 | Grandma's Boysenberry Spread
        11 | Queso Cabrales
        12 | Queso Manchego La Pastora
        17 | Alice Mutton
        19 | Teatime Chocolate Biscuits
        22 | Gustaf's Knõckebr÷d
        26 | Gumbõr Gummibõrchen
        34 | Sasquatch Ale
        36 | Inlagd Sill
        37 | Gravad lax
        50 | Valkoinen suklaa
        51 | Manjimup Dried Apples
        55 | PÔtÚ chinois
        57 | Ravioli Angelo
        58 | Escargots de Bourgogne
        63 | Vegie-spread
        64 | Wimmers gute Semmelkn÷del
        71 | Flotemysost
        73 | R÷d Kaviar
        74 | Longlife Tofu
        76 | Lakkalik÷÷ri
(23 rows)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top