How to Fix Error “window function nth_value requires an OVER clause” in PostgreSQL

If you’re getting an error that reads “window function nth_value requires an OVER clause” in PostgreSQL, it’s because you’re calling the nth_value() function without an OVER clause.

PostgreSQL requires that you include an OVER clause any time you call a built in nonaggregate window function such as nth_value().

To fix this issue, add an OVER clause to your window function.

Continue reading

Using the RANK() Function to Add a “Rank” Column in PostgreSQL

PostgreSQL has a window function called rank() that returns the rank of the current row, with gaps.

“With gaps” means that it returns the same rank for any ties (i.e. two or more rows with the same value), but then subsequent ranks jump forward to account for the ties.

This means that there’s the potential for noncontiguous rank values. For example it could go 1, 2, 5, etc if several rows are ranked at 2. If there are no ties, then the rank values will be contiguous.

Continue reading

Add a Column of Row Numbers in PostgreSQL: The ROW_NUMBER() Function

In PostgreSQL, we can use the row_number() function to get each row’s number within its partition. This allows us to create a column with incrementing row numbers that reset with each new partition.

The row_number() function is a window function that’s specifically designed to return the number of the current row within its partition, starting at 1 and incrementing sequentially.

Continue reading