InterviewPrepKit

Home / SQL / Subqueries & CTEs

Customers Who Never Ordered

medium
Solving tips
  • `NOT EXISTS` is the safe way to express anti-joins: it evaluates to true or false per row and is never derailed by NULLs in the subquery.
  • `NOT IN` against a subquery that can produce a NULL is a classic trap — a single NULL makes the whole `NOT IN` predicate return unknown for every row, so you get zero results.
  • For the positive case (customers who did order), `IN` and `EXISTS` are logically equivalent and both correct; the difference only bites with the negated forms and NULLs.

Return the customers who have never placed an order. The orders table intentionally contains a row with a NULL customer, which is what makes the naive NOT IN approach fail.

Schema

CREATE TABLE customers (
    id   integer PRIMARY KEY,
    name text    NOT NULL
);

CREATE TABLE orders (
    id          integer PRIMARY KEY,
    customer_id integer,        -- nullable: an order can be unattributed
    amount      integer NOT NULL
);

Sample data — customers:

idname
1Ana
2Ben
3Cy
4Dee

Sample data — orders:

idcustomer_idamount
1011250
102190
1033400
104NULL150

Task

Return the name of every customer who has no matching row in orders. Order by name ascending. Expected column: name.

Expected output

Ana (id 1) and Cy (id 3) have orders; Ben and Dee do not. The NULL customer on order 104 belongs to nobody and must not suppress the answer.

name
Ben
Dee
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.