Skip to main content

Categories: Window

ROW_NUMBER

Returns a unique sequential number for each row within its partition, starting at 1. Rows with equal values receive different row numbers. Requires an ORDER BY clause in the OVER window specification.

Syntax​

ROW_NUMBER() OVER ( [PARTITION BY partition_expression] ORDER BY order_expression) → bigint​

  • partition_expression (optional): An expression that groups rows into partitions.
  • order_expression: An expression that specifies the order of the rows within each partition.

Examples

ROW_NUMBER example
SELECT "Category", 
"Descript",
"DayOfWeek",
ROW_NUMBER()
OVER (
PARTITION BY "Category"
ORDER BY "DayOfWeek")
FROM Samples."samples.dremio.com"."SF_incidents2016.json"
-- Category, Descript, DayOfWeek, EXPR$3
-- ARSON, ARSON, Friday, 1
-- ARSON, ARSON, Friday, 2
Number rows with tied values
SELECT val,
ROW_NUMBER()
OVER (
ORDER BY val)
FROM (VALUES (10), (20), (20), (30)) AS t(val)
-- val, EXPR$1
-- 10, 1
-- 20, 2
-- 20, 3
-- 30, 4
Number rows within partitions
SELECT name,
val,
ROW_NUMBER()
OVER (
PARTITION BY name
ORDER BY val)
FROM (VALUES ('Dremio', 10), ('Dremio', 30), ('Cloud', 20)) AS t(name, val)
-- name, val, EXPR$2
-- Cloud, 20, 1
-- Dremio, 10, 1
-- Dremio, 30, 2
Number rows with a NULL value
SELECT val,
ROW_NUMBER()
OVER (
ORDER BY val)
FROM (VALUES (10), (NULL), (20)) AS t(val)
-- val, EXPR$1
-- 10, 1
-- 20, 2
-- null, 3
Compare RANK, DENSE_RANK, and ROW_NUMBER
SELECT val,
RANK()
OVER (
ORDER BY val),
DENSE_RANK()
OVER (
ORDER BY val),
ROW_NUMBER()
OVER (
ORDER BY val)
FROM (VALUES (10), (20), (20), (30)) AS t(val)
-- val, EXPR$1, EXPR$2, EXPR$3
-- 10, 1, 1, 1
-- 20, 2, 2, 2
-- 20, 2, 2, 3
-- 30, 4, 3, 4

Usage Notes​

The returned rows are ordered exactly the same with each execution unless identical values are detected in the same partition. Rows containing identical values in the partition and ORDER BY columns receive different row numbers. The order of these row numbers can vary by execution, causing inconsistent query results.