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

Select The Top Row Per Group

Use `ROW_NUMBER()` to rank rows within each group and keep only the highest-ranked row.

Docker-validated Not currently validation-green

Keep the latest order per customer

Each customer's rows are ranked newest-first, then only row_num = 1 is kept.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (id INT, customer VARCHAR(50), created_at DATE);

INSERT INTO
  orders (id, customer, created_at)
VALUES
  (1, 'Ada', '2024-01-01'),
  (2, 'Ada', '2024-02-01'),
  (3, 'Linus', '2024-01-15'),
  (4, 'Linus', '2024-03-01');
Shared across supported engines.
SQL
WITH
  ranked AS (
    SELECT
      id,
      customer,
      created_at,
      ROW_NUMBER() OVER (
        PARTITION BY
          customer
        ORDER BY
          created_at DESC,
          id DESC
      ) AS row_num
    FROM
      orders
  )
SELECT
  customer,
  id,
  created_at
FROM
  ranked
WHERE
  row_num = 1
ORDER BY
  customer;
Returned rows for the shared example.
customeridcreated_at
Ada22024-02-01
Linus42024-03-01

The same ranking pattern and final result validate across all supported engines here.

Where this command helps.

  • keeping the latest order per customer
  • selecting the highest score or newest event within each group

What the command is doing.

Top-N-per-group queries are one of the most useful applications of window functions. By partitioning rows into groups and numbering them in the right order, you can keep the latest, highest, or otherwise best row per group.