InterviewPrepKit

Home / SQL / Joins

Anti-Join: Products Never Ordered (NOT EXISTS vs NOT IN)

medium
Solving tips
  • An anti-join returns rows on one side that have no match on the other; NOT EXISTS with a correlated subquery is the safe idiom.
  • Avoid NOT IN when the subquery column can contain NULL, because a single NULL makes the whole predicate return no rows.
  • NOT EXISTS, LEFT JOIN ... IS NULL, and (NULL-free) NOT IN are the three interchangeable ways to write an anti-join.

Find the products that have never been ordered. Note that some order rows have a NULL product_id, which is exactly what breaks a naive NOT IN.

Schema

CREATE TABLE products (
    id           INT PRIMARY KEY,
    product_name VARCHAR(50) NOT NULL
);

CREATE TABLE orders (
    id         INT PRIMARY KEY,
    product_id INT REFERENCES products(id)
);

products

idproduct_name
100Keyboard
200Mouse
300Monitor
400Webcam

orders

idproduct_id
1100
2100
3300
4NULL

Task

Return the products that appear in no order, with columns product_id (the product’s id) and product_name. Order by product_id ascending.

Expected output

product_idproduct_name
200Mouse
400Webcam
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.