Supported Functions
| Function | Description |
|---|---|
ROW NUMBER | Sequential row numbers |
RANK | Rank with gaps for ties |
DENSE RANK | Rank without gaps |
LAG | Previous row value |
LEAD | Next row value |
NTILE | Divide into buckets |
Basic Syntax
* to include all columns, or specify columns explicitly:
ROW NUMBER
Assign sequential numbers to rows.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, ROW_NUMBER() OVER (ORDER BY created_at) AS row_num FROM users |
With Partition
| Database | Output |
|---|---|
| PostgreSQL | SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num FROM users |
RANK
Assign rank with gaps for ties.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rank FROM products |
DENSE RANK
Assign rank without gaps for ties.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, DENSE_RANK() OVER (ORDER BY price DESC) AS dense_rank FROM products |
Rank Comparison
| Score | ROW NUMBER | RANK | DENSE RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
| 80 | 4 | 4 | 3 |
LAG
Access previous row value.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, LAG(amount) OVER (ORDER BY created_at) AS prev_amount FROM orders |
LEAD
Access next row value.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, LEAD(amount) OVER (ORDER BY created_at) AS next_amount FROM orders |
NTILE
Divide rows into buckets.| Database | Output |
|---|---|
| PostgreSQL | SELECT *, NTILE(4) OVER (ORDER BY salary) AS quartile FROM users |
Complete Example
MongoDB Note
MongoDB has limited window function support (5.0+). Complex window functions may require aggregation pipelines.Limitations
Current implementation supports:- PARTITION BY
- ORDER BY within OVER clause
- Frame clauses (
ROWS BETWEEN) FIRST_VALUE,LAST_VALUE- Aggregate functions as window functions (
SUM() OVER,AVG() OVER)

