Windows Function

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Window functions are a group of SQL functions that perform calculations across a

set
of rows related to the current row within a result set. Common window functions
include:

1. `ROW_NUMBER()`: Assigns a unique number to each row in the result set based on
the specified ordering. It's often used for ranking or paging results.

2. `RANK()`: Assigns a unique rank to each row based on the specified ordering,
with
the same rank given to rows with the same values. It can create gaps in ranks.

3. `DENSE_RANK()`: Similar to `RANK()`, but without gaps in ranks for rows with the

same values.

4. `NTILE(n)`: Divides the result set into "n" roughly equal parts and assigns a
group number to each row. Useful for creating quantiles or percentile groups.

5. `SUM() OVER()`: Calculates a running total of a specific column's values for a


window defined by the `OVER` clause. You can specify an ordering and
partitioning
if needed.

6. `AVG() OVER()`: Calculates a running average of a specific column's values for a


window defined by the `OVER` clause.

7. `COUNT() OVER()`: Calculates a running count of rows for a window defined by the

`OVER` clause.

8. `MIN() OVER()`: Calculates the minimum value of a specific column within a


window
defined by the `OVER` clause.

9. `MAX() OVER()`: Calculates the maximum value of a specific column within a


window
defined by the `OVER` clause.

10. `LEAD()`: Retrieves the value from the next row within the result set, based on

the specified ordering. You can specify a default value.

11. `LAG()`: Retrieves the value from the previous row within the result set, based

on the specified ordering. You can specify a default value.

12. `FIRST_VALUE()`: Retrieves the value from the first row within a window defined

by the `OVER` clause.

13. `LAST_VALUE()`: Retrieves the value from the last row within a window defined
by
the `OVER` clause.

These are some of the most commonly used window functions in SQL.

They are particularly useful for performing complex analytical calculations on your
data, such as ranking, aggregating, and computing running totals or averages.

The exact set of window functions available may vary depending on the specific SQL
database system you are using, as some databases might offer additional proprietary

window functions.

You might also like