sqlcmd.net validated sql reference
intermediate windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate A Running Count With COUNT OVER

Use COUNT as a window function to number how many rows have appeared up to the current row.

Docker-validated Not currently validation-green

Show the cumulative number of signups by date

Each row counts all rows from the start of the ordered result through the current row. The id tiebreaker makes the two Jan 3 rows deterministic.

Rows loaded before the example query runs.
Setup
CREATE TABLE signups (id INT, signup_date VARCHAR(10));

INSERT INTO
  signups
VALUES
  (1, '2024-01-01'),
  (2, '2024-01-03'),
  (3, '2024-01-03'),
  (4, '2024-01-05');
Shared across supported engines.
SQL
SELECT
  id,
  signup_date,
  COUNT(*) OVER (
    ORDER BY
      signup_date,
      id ROWS BETWEEN UNBOUNDED PRECEDING
      AND CURRENT ROW
  ) AS running_count
FROM
  signups
ORDER BY
  signup_date,
  id;
Returned rows for the shared example.
idsignup_daterunning_count
12024-01-011
22024-01-032
32024-01-033
42024-01-054

The explicit ROWS frame makes ties deterministic with the id tiebreaker.

Where this command helps.

  • showing cumulative signups over time
  • counting events seen so far without losing row detail

What the command is doing.

COUNT(*) OVER (ORDER BY ...) computes a cumulative row count while preserving the original rows. Unlike ROW_NUMBER, a running count can be filtered with CASE to count only rows meeting a condition, and unlike GROUP BY, it does not collapse rows.