← Back to SQL, page 7

sql-0124 · Hard senior

Can you use COUNT(DISTINCT ...) as a window function, for example a running count of distinct customers?

PostgreSQL rejects DISTINCT in window aggregates, and SQLite rejects it too. A common workaround is to mark each customer's first appearance with ROW_NUMBER() OVER (PARTITION BY customer ORDER BY date) = 1 and then take a running SUM of those flags. For a non-running distinct count per partition, DENSE_RANK forwards plus backwards minus 1 is a known trick.

Full answer

"How many distinct customers have we had up to each date?" sounds like a running COUNT(DISTINCT). Both engines refuse:

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);
sql
SELECT order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;  -- error on purpose
text
Error: DISTINCT is not supported for window functions
sql
SELECT order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;  -- error on purpose
text
Error: DISTINCT is not implemented for window functions

The workaround marks the first order of each customer, then runs a normal SUM over those marks:

sql
WITH firsts AS (
  SELECT id, order_date, customer_id,
         CASE WHEN ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) = 1
              THEN 1 ELSE 0 END AS is_first
  FROM orders
  WHERE customer_id IS NOT NULL
)
SELECT order_date, customer_id,
       SUM(is_first) OVER (ORDER BY order_date, id) AS distinct_customers_so_far
FROM firsts
ORDER BY order_date, id;
order_datecustomer_iddistinct_customers_so_far
2026-01-0511
2026-02-1111
2026-02-1422
2026-03-0133
2026-03-0923

A customer contributes 1 only on their first order, so the running sum counts each customer once. Ana's second order on 11 February adds 0. The guest order with no customer is excluded in WHERE.

For "distinct values in the whole partition" (not running), DENSE_RANK() OVER (ORDER BY x) + DENSE_RANK() OVER (ORDER BY x DESC) - 1 gives the distinct count on every row. It works because the two ranks of any value add up to the number of distinct values plus one.

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);

-- error on purpose
SELECT order_date, COUNT(DISTINCT customer_id) OVER (ORDER BY order_date) FROM orders;

WITH firsts AS (
  SELECT id, order_date, customer_id,
         CASE WHEN ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, id) = 1
              THEN 1 ELSE 0 END AS is_first
  FROM orders
  WHERE customer_id IS NOT NULL
)
SELECT order_date, customer_id,
       SUM(is_first) OVER (ORDER BY order_date, id) AS distinct_customers_so_far
FROM firsts
ORDER BY order_date, id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • COUNT(DISTINCT) is not allowed as a window function in SQLite or PostgreSQL
  • Flag first appearances with ROW_NUMBER, then SUM the flags
  • The DENSE_RANK up plus down minus 1 trick gives a partition distinct count
  • Exclude NULL keys explicitly

Common mistakes

  • Using COUNT(DISTINCT) OVER on an engine that does not support it and rewriting with a slow self join
  • Counting NULL customers as one more distinct customer

Follow-ups

  • How would you compute distinct customers per month?
  • Why does the DENSE_RANK trick work?

Tips

  • Explain why each customer contributes exactly once