InterviewPrepKit

Home / SQL / Aggregation & Grouping

Customers With Repeat Completed Orders

medium
Solving tips
  • WHERE filters individual rows before grouping; HAVING filters whole groups after aggregation.
  • You cannot put an aggregate like COUNT(*) in WHERE — that condition belongs in HAVING.
  • Combine both: WHERE narrows the rows that feed each group, HAVING keeps or drops the resulting groups.

Given an orders table, find customers who placed at least two completed orders. Cancelled orders must not count toward the total.

Schema

CREATE TABLE orders (
  order_id    INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  amount      NUMERIC NOT NULL,
  status      TEXT NOT NULL   -- 'completed' or 'cancelled'
);

Sample data:

order_idcustomer_idamountstatus
110050completed
210030completed
310020cancelled
410140completed
510260completed
610270completed
710210completed
810325cancelled

Task

Considering completed orders only, return:

  • customer_id
  • order_count — the number of completed orders for that customer

Include only customers whose completed order count is at least 2. Order by order_count descending, then customer_id ascending.

Expected output

customer_idorder_count
1023
1002
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.