Window functions

Window functions are functions which perform a computation across a set of rows which are related to the current row. This is comparable to aggregation functions, but window functions do not cause multiple rows to be grouped into a single row.

Window function call

Synopsis

The synopsis of a window function call is one of the following

  1. function_name ([expression [, expression ... ]])
  2. [ FILTER ( WHERE condition ) ]
  3. over_clause
  4. function_name ( * ) [ FILTER ( WHERE condition ) ] over_clause

where function_name is a name of a general-purpose window or aggregate function and expression is a column reference, scalar function or literal.

If FILTER is specified, then only the rows that met the WHERE condition are supplied to the window function. Only window functions that are aggregates accept the FILTER clause.

The OVER clause is what declares a function to be a window function.

The window function call that uses a wildcard instead of an expression as a function argument is supported only by the count(*) aggregate function.

Window definition

OVER

Synopsis

  1. OVER { window_name | ( [ window_definition ] ) }

where window_definition has the syntax

  1. window_definition:
  2. [ window_name ]
  3. [ PARTITION BY expression [, ...] ]
  4. [ ORDER BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ]
  5. [ { RANGE | ROWS } BETWEEN frame_start AND frame_end ]

The window_name refers to window_definition defined in the WINDOW clause.

The frame_start and frame_end can be one of

  1. UNBOUNDED PRECEDING
  2. offset PRECEDING
  3. CURRENT ROW
  4. offset FOLLOWING
  5. UNBOUNDED FOLLOWING

The default frame definition is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. If frame_end is omitted it defaults to CURRENT ROW.

frame_start cannot be FOLLOWING or UNBOUNDED FOLLOWING and frame_end cannot be PRECEDING or UNBOUNDED PRECEDING.

In RANGE mode if the frame_start is CURRENT ROW the frame starts with the current row’s first peer (a row that the window’s ORDER BY expression sorts as equal to the current row), while a frame_end of CURRENT ROW means the frame will end with the current’s row last peer row.

In ROWS mode CURRENT_ROW means the current row.

The offset PRECEDING and offset FOLLOWING options vary in meaning depending on the frame mode. In ROWS mode, the offset is an integer indicating that the frame start or end is offsetted by that many rows before or after the current row. In RANGE mode, the use of a custom offset option requires that there is exactly one ORDER BY column in the window definition. The frame contains those rows whose ordering column value is no more than offset minus (for PRECEDING) or plus (for FOLLOWING) the current row’s ordering column value. Because the value of offset is substracted/added to the values of the ordering column, only type combinations that support addition/substraction operations are allowed. For instance, when the ordering column is of type timestamp, the offset expression can be an interval.

The OVER clause defines the window containing the appropriate rows which will take part in the window function computation.

An empty OVER clause defines a window containing all the rows in the result set.

Example:

  1. cr> SELECT dept_id, COUNT(*) OVER() AS cnt FROM employees ORDER BY 1, 2;
  2. +---------+-----+
  3. | dept_id | cnt |
  4. +---------+-----+
  5. | 4001 | 18 |
  6. | 4001 | 18 |
  7. | 4001 | 18 |
  8. | 4002 | 18 |
  9. | 4002 | 18 |
  10. | 4002 | 18 |
  11. | 4002 | 18 |
  12. | 4003 | 18 |
  13. | 4003 | 18 |
  14. | 4003 | 18 |
  15. | 4003 | 18 |
  16. | 4003 | 18 |
  17. | 4004 | 18 |
  18. | 4004 | 18 |
  19. | 4004 | 18 |
  20. | 4006 | 18 |
  21. | 4006 | 18 |
  22. | 4006 | 18 |
  23. +---------+-----+
  24. SELECT 18 rows in set (... sec)

The PARTITION BY clause groups the rows within a window into partitions which are processed separately by the window function, each partition in turn becoming a window. If PARTITION BY is not specified, all the rows are considered a single partition.

Example:

  1. cr> SELECT dept_id, ROW_NUMBER() OVER(PARTITION BY dept_id) AS row_num
  2. ... FROM employees ORDER BY 1, 2;
  3. +---------+---------+
  4. | dept_id | row_num |
  5. +---------+---------+
  6. | 4001 | 1 |
  7. | 4001 | 2 |
  8. | 4001 | 3 |
  9. | 4002 | 1 |
  10. | 4002 | 2 |
  11. | 4002 | 3 |
  12. | 4002 | 4 |
  13. | 4003 | 1 |
  14. | 4003 | 2 |
  15. | 4003 | 3 |
  16. | 4003 | 4 |
  17. | 4003 | 5 |
  18. | 4004 | 1 |
  19. | 4004 | 2 |
  20. | 4004 | 3 |
  21. | 4006 | 1 |
  22. | 4006 | 2 |
  23. | 4006 | 3 |
  24. +---------+---------+
  25. SELECT 18 rows in set (... sec)

If ORDER BY is supplied the window definition consists of a range of rows starting with the first row in the partition and ending with the current row, plus any subsequent rows that are equal to the current row, which are the current row’s peers.

Example:

  1. cr> SELECT
  2. ... dept_id,
  3. ... sex,
  4. ... COUNT(*) OVER(PARTITION BY dept_id ORDER BY sex) AS cnt
  5. ... FROM employees
  6. ... ORDER BY 1, 2, 3
  7. +---------+-----+-----+
  8. | dept_id | sex | cnt |
  9. +---------+-----+-----+
  10. | 4001 | M | 3 |
  11. | 4001 | M | 3 |
  12. | 4001 | M | 3 |
  13. | 4002 | F | 1 |
  14. | 4002 | M | 4 |
  15. | 4002 | M | 4 |
  16. | 4002 | M | 4 |
  17. | 4003 | M | 5 |
  18. | 4003 | M | 5 |
  19. | 4003 | M | 5 |
  20. | 4003 | M | 5 |
  21. | 4003 | M | 5 |
  22. | 4004 | F | 1 |
  23. | 4004 | M | 3 |
  24. | 4004 | M | 3 |
  25. | 4006 | F | 1 |
  26. | 4006 | M | 3 |
  27. | 4006 | M | 3 |
  28. +---------+-----+-----+
  29. SELECT 18 rows in set (... sec)

Note

Taking into account the peers concept mentioned above, for an empty OVER clause all the rows in the result set are peers.

Note

Aggregation functions will be treated as window functions when used in conjunction with the OVER clause.

Note

Window definitions order or partitioned by an array column type are currently not supported.

In the UNBOUNDED FOLLOWING case the window for each row starts with each row and ends with the last row in the current partition. If the current row has peers the window will include (or start with) all the current row peers and end at the upper bound of the partition.

Example:

  1. cr> SELECT
  2. ... dept_id,
  3. ... sex,
  4. ... COUNT(*) OVER(
  5. ... PARTITION BY dept_id
  6. ... ORDER BY
  7. ... sex RANGE BETWEEN CURRENT ROW
  8. ... AND UNBOUNDED FOLLOWING
  9. ... ) partitionByDeptOrderBySex
  10. ... FROM employees
  11. ... ORDER BY 1, 2, 3
  12. +---------+-----+---------------------------+
  13. | dept_id | sex | partitionbydeptorderbysex |
  14. +---------+-----+---------------------------+
  15. | 4001 | M | 3 |
  16. | 4001 | M | 3 |
  17. | 4001 | M | 3 |
  18. | 4002 | F | 4 |
  19. | 4002 | M | 3 |
  20. | 4002 | M | 3 |
  21. | 4002 | M | 3 |
  22. | 4003 | M | 5 |
  23. | 4003 | M | 5 |
  24. | 4003 | M | 5 |
  25. | 4003 | M | 5 |
  26. | 4003 | M | 5 |
  27. | 4004 | F | 3 |
  28. | 4004 | M | 2 |
  29. | 4004 | M | 2 |
  30. | 4006 | F | 3 |
  31. | 4006 | M | 2 |
  32. | 4006 | M | 2 |
  33. +---------+-----+---------------------------+
  34. SELECT 18 rows in set (... sec)

Named windows

It is possible to define a list of named window definitions that can be referenced in OVER clauses. To do this, use the WINDOW clause in the SELECT clause.

Named windows are particularly useful when the same window definition could be used in multiple OVER clauses. For instance

  1. cr> SELECT
  2. ... x,
  3. ... FIRST_VALUE(x) OVER (w) AS "first",
  4. ... LAST_VALUE(x) OVER (w) AS "last"
  5. ... FROM (VALUES (1), (2), (3), (4)) AS t(x)
  6. ... WINDOW w AS (ORDER BY x)
  7. +---+-------+------+
  8. | x | first | last |
  9. +---+-------+------+
  10. | 1 | 1 | 1 |
  11. | 2 | 1 | 2 |
  12. | 3 | 1 | 3 |
  13. | 4 | 1 | 4 |
  14. +---+-------+------+
  15. SELECT 4 rows in set (... sec)

If a window_name is specified in the window definition of the OVER clause, then there must be a named window entry that matches the window_name in the window definition list of the WINDOW clause.

If the OVER clause has its own non-empty window definition and references a window definition from the WINDOW clause, then it can only add clauses from the referenced window, but not overwrite them.

  1. cr> SELECT
  2. ... x,
  3. ... LAST_VALUE(x) OVER (w ORDER BY x) AS y
  4. ... FROM (VALUES
  5. ... (1, 1),
  6. ... (2, 1),
  7. ... (3, 2),
  8. ... (4, 2) ) AS t(x, y)
  9. ... WINDOW w AS (PARTITION BY y)
  10. +---+---+
  11. | x | y |
  12. +---+---+
  13. | 1 | 1 |
  14. | 2 | 2 |
  15. | 3 | 3 |
  16. | 4 | 4 |
  17. +---+---+
  18. SELECT 4 rows in set (... sec)

Otherwise, an attempt to override the clauses of the referenced window by the window definition of the OVER clause will result in failure.

  1. cr> SELECT
  2. ... FIRST_VALUE(x) OVER (w ORDER BY x)
  3. ... FROM (VALUES(1), (2), (3), (4)) as t(x)
  4. ... WINDOW w AS (ORDER BY x)
  5. SQLParseException[Cannot override ORDER BY clause of window w]

It is not possible to define the PARTITION BY clause in the window definition of the OVER clause if it references a window definition from the WINDOW clause.

The window definitions in the WINDOW clause cannot define its own window frames, if they are referenced by non-empty window definitions of the OVER clauses.

The definition of the named window can itself begin with a window_name. In this case all the elements of interconnected named windows will be copied to the window definition of the OVER clause if it references the named window definition that has subsequent window references. The window definitions in the WINDOW clause permits only backward references.

  1. cr> SELECT
  2. ... x,
  3. ... ROW_NUMBER() OVER (w) AS y
  4. ... FROM (VALUES
  5. ... (1, 1),
  6. ... (3, 2),
  7. ... (2, 1)) AS t (x, y)
  8. ... WINDOW p AS (PARTITION BY y),
  9. ... w AS (p ORDER BY x)
  10. +---+---+
  11. | x | y |
  12. +---+---+
  13. | 1 | 1 |
  14. | 2 | 2 |
  15. | 3 | 1 |
  16. +---+---+
  17. SELECT 3 rows in set (... sec)

General-purpose window functions

row_number()

Returns the number of the current row within its window.

Example:

  1. cr> SELECT
  2. ... col1,
  3. ... ROW_NUMBER() OVER(ORDER BY col1) as row_num
  4. ... FROM (VALUES('x'), ('y'), ('z')) AS t;
  5. +------+---------+
  6. | col1 | row_num |
  7. +------+---------+
  8. | x | 1 |
  9. | y | 2 |
  10. | z | 3 |
  11. +------+---------+
  12. SELECT 3 rows in set (... sec)

first_value(arg)

Returns the argument value evaluated at the first row within the window.

Its return type is the type of its argument.

Example:

  1. cr> SELECT
  2. ... col1,
  3. ... FIRST_VALUE(col1) OVER (ORDER BY col1) AS value
  4. ... FROM (VALUES('x'), ('y'), ('y'), ('z')) AS t;
  5. +------+-------+
  6. | col1 | value |
  7. +------+-------+
  8. | x | x |
  9. | y | x |
  10. | y | x |
  11. | z | x |
  12. +------+-------+
  13. SELECT 4 rows in set (... sec)

last_value(arg)

Returns the argument value evaluated at the last row within the window.

Its return type is the type of its argument.

Example:

  1. cr> SELECT
  2. ... col1,
  3. ... LAST_VALUE(col1) OVER(ORDER BY col1) AS value
  4. ... FROM (VALUES('x'), ('y'), ('y'), ('z')) AS t;
  5. +------+-------+
  6. | col1 | value |
  7. +------+-------+
  8. | x | x |
  9. | y | y |
  10. | y | y |
  11. | z | z |
  12. +------+-------+
  13. SELECT 4 rows in set (... sec)

nth_value(arg, number)

Returns the argument value evaluated at row that is the nth row within the window. NULL is returned if the nth row doesn’t exist in the window.

Its return type is the type of its first argument.

Example:

  1. cr> SELECT
  2. ... col1,
  3. ... NTH_VALUE(col1, 3) OVER(ORDER BY col1) AS val
  4. ... FROM (VALUES ('x'), ('y'), ('y'), ('z')) AS t;
  5. +------+------+
  6. | col1 | val |
  7. +------+------+
  8. | x | NULL |
  9. | y | y |
  10. | y | y |
  11. | z | y |
  12. +------+------+
  13. SELECT 4 rows in set (... sec)

lag(arg [, offset [, default] ])

Synopsis

  1. lag(argument any [, offset integer [, default any]])

Returns the argument value evaluated at the row that precedes the current row by the offset within the partition. If there is no such row, the return value is default. If offset or default arguments are missing, they default to 1 and null, respectively.

Both offset and default are evaluated with respect to the current row.

If offset is 0, then argument value is evaluated for the current row.

The default and argument data types must match.

Example:

  1. cr> SELECT
  2. ... dept_id,
  3. ... year,
  4. ... budget,
  5. ... LAG(budget) OVER(
  6. ... PARTITION BY dept_id) prev_budget
  7. ... FROM (VALUES
  8. ... (1, 2017, 45000),
  9. ... (1, 2018, 35000),
  10. ... (2, 2017, 15000),
  11. ... (2, 2018, 65000),
  12. ... (2, 2019, 12000))
  13. ... as t (dept_id, year, budget);
  14. +---------+------+--------+-------------+
  15. | dept_id | year | budget | prev_budget |
  16. +---------+------+--------+-------------+
  17. | 1 | 2017 | 45000 | NULL |
  18. | 1 | 2018 | 35000 | 45000 |
  19. | 2 | 2017 | 15000 | NULL |
  20. | 2 | 2018 | 65000 | 15000 |
  21. | 2 | 2019 | 12000 | 65000 |
  22. +---------+------+--------+-------------+
  23. SELECT 5 rows in set (... sec)

lead(arg [, offset [, default] ])

Synopsis

  1. lead(argument any [, offset integer [, default any]])

The lead function is the counterpart of the lag window function as it allows the evaluation of the argument at rows that follow the current row. lead returns the argument value evaluated at the row that follows the current row by the offset within the partition. If there is no such row, the return value is default. If offset or default arguments are missing, they default to 1 or null, respectively.

Both offset and default are evaluated with respect to the current row.

If offset is 0, then argument value is evaluated for the current row.

The default and argument data types must match.

Example:

  1. cr> SELECT
  2. ... dept_id,
  3. ... year,
  4. ... budget,
  5. ... LEAD(budget) OVER(
  6. ... PARTITION BY dept_id) next_budget
  7. ... FROM (VALUES
  8. ... (1, 2017, 45000),
  9. ... (1, 2018, 35000),
  10. ... (2, 2017, 15000),
  11. ... (2, 2018, 65000),
  12. ... (2, 2019, 12000))
  13. ... as t (dept_id, year, budget);
  14. +---------+------+--------+-------------+
  15. | dept_id | year | budget | next_budget |
  16. +---------+------+--------+-------------+
  17. | 1 | 2017 | 45000 | 35000 |
  18. | 1 | 2018 | 35000 | NULL |
  19. | 2 | 2017 | 15000 | 65000 |
  20. | 2 | 2018 | 65000 | 12000 |
  21. | 2 | 2019 | 12000 | NULL |
  22. +---------+------+--------+-------------+
  23. SELECT 5 rows in set (... sec)

rank()

Synopsis

  1. rank()

Returns the rank of every row within a partition of a result set.

Within each partition, the rank of the first row is 1. Subsequent tied rows are given the same rank, and the potential rank of the next row is incremented. Because of this, ranks may not be sequential.

Example:

  1. cr> SELECT
  2. ... name,
  3. ... department_id,
  4. ... salary,
  5. ... RANK() OVER (ORDER BY salary desc) as salary_rank
  6. ... FROM (VALUES
  7. ... ('Bobson Dugnutt', 1, 2000),
  8. ... ('Todd Bonzalez', 2, 2500),
  9. ... ('Jess Brewer', 1, 2500),
  10. ... ('Safwan Buchanan', 1, 1900),
  11. ... ('Hal Dodd', 1, 2500),
  12. ... ('Gillian Hawes', 2, 2000))
  13. ... as t (name, department_id, salary);
  14. +-----------------+---------------+--------+-------------+
  15. | name | department_id | salary | salary_rank |
  16. +-----------------+---------------+--------+-------------+
  17. | Todd Bonzalez | 2 | 2500 | 1 |
  18. | Jess Brewer | 1 | 2500 | 1 |
  19. | Hal Dodd | 1 | 2500 | 1 |
  20. | Bobson Dugnutt | 1 | 2000 | 4 |
  21. | Gillian Hawes | 2 | 2000 | 4 |
  22. | Safwan Buchanan | 1 | 1900 | 6 |
  23. +-----------------+---------------+--------+-------------+
  24. SELECT 6 rows in set (... sec)

dense_rank()

Synopsis

  1. dense_rank()

Returns the rank of every row within a partition of a result set, similar to rank. However, unlike rank, dense_rank always returns sequential rank values.

Within each partition, the rank of the first row is 1. Subsequent tied rows are given the same rank.

Example:

  1. cr> SELECT
  2. ... name,
  3. ... department_id,
  4. ... salary,
  5. ... DENSE_RANK() OVER (ORDER BY salary desc) as salary_rank
  6. ... FROM (VALUES
  7. ... ('Bobson Dugnutt', 1, 2000),
  8. ... ('Todd Bonzalez', 2, 2500),
  9. ... ('Jess Brewer', 1, 2500),
  10. ... ('Safwan Buchanan', 1, 1900),
  11. ... ('Hal Dodd', 1, 2500),
  12. ... ('Gillian Hawes', 2, 2000))
  13. ... as t (name, department_id, salary);
  14. +-----------------+---------------+--------+-------------+
  15. | name | department_id | salary | salary_rank |
  16. +-----------------+---------------+--------+-------------+
  17. | Todd Bonzalez | 2 | 2500 | 1 |
  18. | Jess Brewer | 1 | 2500 | 1 |
  19. | Hal Dodd | 1 | 2500 | 1 |
  20. | Bobson Dugnutt | 1 | 2000 | 2 |
  21. | Gillian Hawes | 2 | 2000 | 2 |
  22. | Safwan Buchanan | 1 | 1900 | 3 |
  23. +-----------------+---------------+--------+-------------+
  24. SELECT 6 rows in set (... sec)

Aggregate window functions

See Aggregation.