How to Number Rows Within Each Group in SQL?
Using ROW_NUMBER() with PARTITION BY allows for effective ranking within groups, such as customers by date.
Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.
The formula
"Number rows within each group (e.g. rank orders per customer by date) using ROW_NUMBER() OVER(PARTITION BY)"
SELECT ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date) AS row_num FROM orders;
This SQL query assigns a unique sequential integer to rows within a partition of a result set.
Step-by-step breakdown
- ROW_NUMBER() generates a unique number for each row in the result set.
- OVER() defines the window for the row numbering operation.
- PARTITION BY specifies the column(s) to group the data (e.g., customer_id).
- ORDER BY determines the order of the rows within each partition (e.g., order_date).
Edge cases & warnings
- If there are ties in the ordering column, ROW_NUMBER() will still assign unique numbers.
- Using PARTITION BY with a single unique value results in a continuous sequence for all rows.
- If no ORDER BY is specified, the row numbering will be arbitrary.
Examples
"Customer ID: 1, Orders: [(2023-01-01), (2023-01-02), (2023-01-01)]"
Row Numbers: [1, 2, 3]
"Customer ID: 2, Orders: [(2023-01-03), (2023-01-04)]"
Row Numbers: [1, 2]
Frequently asked questions
What is the difference between ROW_NUMBER() and RANK()?
ROW_NUMBER() assigns a unique number to each row, while RANK() gives the same rank to tied rows.
Can I use ROW_NUMBER() without PARTITION BY?
Yes, but it will number all rows in the result set without grouping.
What happens if I change the ORDER BY clause?
Changing the ORDER BY clause will affect the sequence of the row numbers assigned.
Can't find what you need?
Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.