← Back to SQL, page 5

sql-0098 · Medium mid

When is a subquery in the SELECT list a good choice, and when is a join with GROUP BY better?

A scalar subquery in SELECT is clear for one or two per-row lookups, such as an order count per customer, and it never multiplies rows. With several such columns, each subquery is a separate lookup, and a single join to a pre-aggregated derived table is often cheaper and easier to read. Correctness is the same when written well; the plan decides speed.

Full answer

Both versions below answer "each customer with their number of orders and total quantity bought".

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

With scalar subqueries in the select list:

sql
SELECT c.name,
       (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
       (SELECT COALESCE(SUM(i.qty), 0)
          FROM orders o JOIN order_items i ON i.order_id = o.id
         WHERE o.customer_id = c.id) AS items_bought
FROM customers c
ORDER BY c.name;
nameordersitems_bought
Ana28
Bilal211
Chloe14
Dev00

With a join to one pre-aggregated table:

sql
SELECT c.name,
       COALESCE(s.orders, 0)       AS orders,
       COALESCE(s.items_bought, 0) AS items_bought
FROM customers c
LEFT JOIN (
  SELECT o.customer_id,
         COUNT(DISTINCT o.id) AS orders,
         SUM(i.qty)           AS items_bought
  FROM orders o JOIN order_items i ON i.order_id = o.id
  GROUP BY o.customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;
nameordersitems_bought
Ana28
Bilal211
Chloe14
Dev00

Both are correct, and Dev gets 0 in both. Each has strengths.

Subqueries in SELECT keep the outer row count fixed: there is no way for them to duplicate customers. They read naturally, one column at a time. But each one is a separate correlated lookup, so five such columns mean five lookups per customer.

The join version computes all statistics in one pass over orders and items, then joins once. It scales better as the number of metrics grows, but you must aggregate before joining or you risk fan-out, and you need LEFT JOIN plus COALESCE to keep customers with no orders.

SQLite reports each scalar subquery in the plan:

sql
EXPLAIN QUERY PLAN
SELECT c.name,
       (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;
text
QUERY PLAN
SCAN c
CORRELATED SCALAR SUBQUERY 1
  SCAN o

A reasonable rule: one or two simple lookups, use a subquery; several metrics from the same child tables, pre-aggregate and join; and check the plan when the table is large.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT c.name,
       (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
       (SELECT COALESCE(SUM(i.qty), 0)
          FROM orders o JOIN order_items i ON i.order_id = o.id
         WHERE o.customer_id = c.id) AS items_bought
FROM customers c
ORDER BY c.name;

SELECT c.name,
       COALESCE(s.orders, 0)       AS orders,
       COALESCE(s.items_bought, 0) AS items_bought
FROM customers c
LEFT JOIN (
  SELECT o.customer_id,
         COUNT(DISTINCT o.id) AS orders,
         SUM(i.qty)           AS items_bought
  FROM orders o JOIN order_items i ON i.order_id = o.id
  GROUP BY o.customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;

EXPLAIN QUERY PLAN
SELECT c.name,
       (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Scalar subqueries in SELECT never multiply outer rows
  • Each one is a separate correlated lookup
  • One pre-aggregated join scales better for many metrics
  • LEFT JOIN plus COALESCE keeps parents with no children

Common mistakes

  • Joining child tables directly and summing, causing fan-out
  • Adding many correlated subqueries to one large query without checking the plan

Follow-ups

  • How would a LATERAL join help here in PostgreSQL?
  • How would you add the date of the latest order?

Tips

  • Mention fan-out as the main risk of the join version