On this page
  1. ROW NUMBER
  2. Syntax & Overview
  3. Notes & Best Practices
  4. Example

ROW NUMBER

Prev: `CAST` | Up: functions | Next: `RANK`
Rel: functions, Aggregations, CTEs & Window Functions
Ref: PostgreSQL — SQL Commands
Tags: #public #databases #sql #functions #tier/core


Syntax & Overview

ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)

Assigns a unique sequential integer (1, 2, 3...) per partition.

Notes & Best Practices

Example

WITH ranked AS (
  SELECT user_id, id AS order_id,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
  FROM orders
)
SELECT user_id, order_id FROM ranked WHERE rn = 1;

Linked from

Related notes