Background
The window function is a special class of built-in functions. Similar to the aggregation function, it also does calculations on multiple input rows to get a single data value. The difference is that the window function processes the input data within a specific window, rather than using the “group by” method. The data in each window can be sorted and grouped using the over() clause. The window function computes a separate value for each row, rather than computing one value for each group. This flexibility allows users to add additional columns to the select clause and further filter the result set. The window function can only appear in the select list and the outermost position of a clause. It takes effect at the end of the query, that is, after thejoin, where, and group by operations are performed. The window function is often used to analyze trends, calculate outliers, and perform bucketing analyses on large-scale data.
Usage
Syntax
PARTITION BY clause
The Partition By clause is similar to Group By. It groups the input rows by one or more specified columns. Rows with the same value are grouped together.ORDER BY clause
TheOrder By clause is basically the same as the outer Order By. It defines the order of the input rows. If Partition By is specified, Order By defines the order within each Partition grouping. The only difference is that Order By n (n is a positive integer) in the OVER clause is equivalent to no operation, whereas n in the outer Order By indicates sorting by the nth column.
Example:
This example shows adding an id column to the select list with values of 1, 2, 3, etc., sorted by the date_and_time column in the events table.
Window clause
The window clause is used to specify a range of rows for operations (the preceding and following rows based on the current row). It supports the following syntaxes: AVG(), COUNT(), FIRST_VALUE(), LAST_VALUE(), and SUM(). For MAX() and MIN(), the window clause can specify the start toUNBOUNDED PRECEDING.
Syntax:
Window function sample table
This section creates a sample tablescores. You can use this table to test many window functions below.
Function examples
This section describes the window functions supported in the database.AVG()
Calculates the average value of a field in a given window. This function ignores NULL values. Syntax:DISTINCT is supported from StarRocks v4.0. When specified, AVG() calculates the average of only distinct values in the window.
Note
Window frame limitation:
When using AVG(DISTINCT) as a window function, only RANGE frames are supported. ROWS frames are NOT supported.
Examples
Example 1: Basic usage
The following example uses stock data as an example.
12.87500000 in the first row is the average value of closing prices on “2014-10-02” (12.86), its previous day “2014-10-01” (null), and its following day “2014-10-03” (12.89).
Example 2: Using AVG(DISTINCT) over overall window
This example uses the data in the Sample table scores.
Calculate the average of distinct scores across all rows:
(80 + 85 + 90) / 3).
Example 3: Using AVG(DISTINCT) over framed window with RANGE frame
This example uses the data in the Sample table scores.
Calculate the average of distinct scores within each subject partition using a RANGE frame:
ARRAY_AGG()
Aggregates values (including NULL values) in a window into an array. You can use the optionalORDER BY clause to sort the elements within the array.
This function is supported from v3.4.
Tip
Window frame limitation:
ARRAY_AGG() as a window function only supports RANGE window frames. ROWS window frames are NOT supported. If no window frame is specified, the default RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is used.
Syntax:
expr: The expression to aggregate. It can be a column of any supported data type.DISTINCT: Optional. Eliminates duplicate values from the result array.ORDER BY: Optional. Specifies the order of elements within the array.
- ROWS frames are NOT supported. Only RANGE frames can be used with ARRAY_AGG() as a window function. Using ROWS frames will result in an error.
- NULL values are included in the result array.
- When
DISTINCTis specified, duplicate values are removed from the array. - When
ORDER BYis specified within ARRAY_AGG(), the elements in the resulting array are sorted accordingly.
scores.
Example 1: Basic usage
Collect all scores within each subject partition:
score value (tom and amy both have 80) receive the same array due to the RANGE frame semantics.
Example 2: ARRAY_AGG(DISTINCT) over window
Collect distinct scores within each subject partition:
stock_ticker table, collect stock symbols in a moving window:
COUNT()
Calculates the total number of rows that meet the specified conditions in a give window. Syntax:DISTINCT is supported from StarRocks v4.0. When specified, COUNT() counts only distinct values in the window.
Note
Window frame limitation:
When using COUNT(DISTINCT) as a window function, only RANGE frames are supported. ROWS frames are NOT supported. For example:
scores.
Example 1: Basic usage
Count the occurrence of math scores that are greater than 90 from the current row to the first row in the math partition. This example uses the data in the Sample table scores.
CUME_DIST()
The CUME_DIST() function calculates the cumulative distribution of a value within a partition or window, indicating its relative position as a percentage in the partition. It is often used to calculate the distribution of highest or lowest values in a group.- If data is sorted in ascending order, this function calculates the percentage of values less than or equal to the value in the current row.
- If data is sorted in descending order, this function calculates the percentage of values greater than or equal to the value in the current row.
partition_by_clause: optional. If this clause is not specified, the entire result set is processed as a single partition.order_by_clause: This function must be used with ORDER BY to sort partition rows into the desired order.
subject group. This example uses the data in the Sample table scores.
- For
cume_distin the first row, theNULLgroup has only one row, and only this row itself meets the condition of “less than or equal to the current row”. The cumulative distribution is 1。 - For
cume_distin the second row, theenglishgroup has five rows, and only this row itself (NULL) meets the condition of “less than or equal to the current row”. The cumulative distribution is 0.2. - For
cume_distin the third row, theenglishgroup has five rows, and two rows (85 and NULL) meet the condition of “less than or equal to the current row”. The cumulative distribution is 0.4.
DENSE_RANK()
The DENSE_RANK() function is used to represent rankings. Unlike RANK(), DENSE_RANK() does not have vacant numbers. For example, if there are two 1s, the third number of DENSE_RANK() is still 2, whereas the third number of RANK() is 3. Syntax:scores.
FIRST_VALUE()
FIRST_VALUE() returns the first value of the window range. Syntax:IGNORE NULLS is supported from v2.5.0. It is used to determine whether NULL values of expr are eliminated from the calculation. By default, NULL values are included, which means NULL is returned if the first value in the filtered result is NULL. If you specify IGNORE NULLS, the first non-null value in the filtered result is returned. If all the values are NULL, NULL is returned even if you specify IGNORE NULLS.
ARRAY types are supported from StarRocks v3.5. You can use FIRST_VALUE() with ARRAY columns to get the first array value in the window.
Examples
Example 1: Basic usage
Return the first score value for each member in each group (descending order), grouping by subject. This example uses the data in the Sample table scores.
[1,11] is returned for all rows in the window.
LAST_VALUE()
LAST_VALUE() returns the last value of the window range. It is the opposite of FIRST_VALUE(). Syntax:IGNORE NULLS is supported from v2.5.0. It is used to determine whether NULL values of expr are eliminated from the calculation. By default, NULL values are included, which means NULL is returned if the last value in the filtered result is NULL. If you specify IGNORE NULLS, the last non-null value in the filtered result is returned. If all the values are NULL, NULL is returned even if you specify IGNORE NULLS.
By default, LAST_VALUE() calculates rows between unbounded preceding and current row, which compares the current row with all its preceding rows. If you want to show only one value for each partition, use rows between unbounded preceding and unbounded following after ORDER BY.
ARRAY types are supported from StarRocks v3.5. You can use LAST_VALUE() with ARRAY columns to get the last array value in the window.
Examples
Example 1: Basic usage
Returns the last score for each member in the group (descending order), grouping by subject. This example uses the data in the Sample table scores.
[5,55] is returned for all rows in the window.
LAG()
Returns the value of the row that lags the current row byoffset rows. This function is often used to compare values between rows and filter data.
LAG() can be used to query data of the following types:
- Numeric: TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, DECIMAL
- String: CHAR, VARCHAR
- Date: DATE, DATETIME
- BITMAP and HLL are supported from StarRocks v2.5.
- ARRAY types are supported from StarRocks v3.5.
expr: the field you want to compute.offset: the offset. It must be a positive integer. If this parameter is not specified, 1 is the default.default: the default value returned if no matching row is found. If this parameter is not specified, NULL is the default.defaultsupports any expression whose type is compatible withexpr, since version 4.0, default no longer has to be a constant—it can be a column name.IGNORE NULLSis supported from v3.0. It is used to determine whether NULL values ofexprare included in the result. By default, NULL values are included whenoffsetrows are counted, which means NULL is returned if the value of the destination row is NULL. See Example 1. If you specify IGNORE NULLS, NULL values are ignored whenoffsetrows are counted and the system continues to search foroffsetnon-null values. Ifoffsetnon-null values cannot be found, NULL ordefault(if specified) is returned. See Example 2.
offset is 2, which means traversing the previous two rows; default is 0, which means 0 is returned if no matching rows are found.
Output:
arr2 is returned.
LEAD()
Returns the value of the row that leads the current row byoffset rows. This function is often used to compare values between rows and filter data.
Data types that can be queried by LEAD() are the same as those supported by LAG().
Syntax:
expr: the field you want to compute.offset: the offset. It must be a positive integer. If this parameter is not specified, 1 is the default.default: the default value returned if no matching row is found. If this parameter is not specified, NULL is the default.defaultsupports any expression whose type is compatible withexpr, since version 4.0, default no longer has to be a constant—it can be a column name.IGNORE NULLSis supported from v3.0. It is used to determine whether NULL values ofexprare included in the result. By default, NULL values are included whenoffsetrows are counted, which means NULL is returned if the value of the destination row is NULL. See Example 1. If you specify IGNORE NULLS, NULL values are ignored whenoffsetrows are counted and the system continues to search foroffsetnon-null values. Ifoffsetnon-null values cannot be found, NULL ordefault(if specified) is returned. See Example 2.
offset is 2, which means traversing the subsequent two rows; default is 0, which means 0 is returned if no matching rows are found.
Output:
arr2 is returned.
MAX()
Returns the maximum value of the specified rows in the current window. Syntax:scores.
math subject.
rows between n preceding and n following, which means you can capture n rows before the current row and n rows after the current row.
Example statement:
MIN()
Returns the minimum value of the specified rows in the current window. Syntax:scores.
rows between n preceding and n following, which means you can capture n rows before the current row and n rows after the current row.
Example statement:
NTILE()
NTILE() function divides the sorted rows in a partition by the specified number ofnum_buckets as equally as possible, stores the divided rows in the respective buckets, starting from 1 [1, 2, ..., num_buckets], and returns the bucket number that each row is in.
About the size of the bucket:
- If the row counts can be divided by the specified number of
num_bucketsexactly, all the buckets will be of the same size. - If the row counts cannot be divided by the specified number of
num_bucketsexactly, there will be buckets of two different sizes. The difference between sizes is 1. The buckets with more rows will be listed ahead of the one with fewer rows.
num_buckets: Number of the buckets to be created. The value must be a constant positive integer whose maximum is 2^63 - 1.
Window clause is not allowed in NTILE() function.
NTILE() function returns BIGINT type of data.
Examples
The following example divides all rows in the partition into two buckets. This example uses the data in the Sample table scores.
num_buckets is 2:
- For the first row, this partition has only this record and it is assigned to only one bucket.
- For rows 2 to 7, the partition has 6 records and the first 3 records are assigned to bucket 1 and other 3 records are assigned to bucket 2.
PERCENT_RANK()
Calculates the relative rank of a row within a result set as a percentage. PERCENT_RANK() is calculated using the following formula, whereRank represents the rank of the current row in the partition.
score within the group of math. This example uses the data in the Sample table scores.
RANK()
The RANK() function is used to represent rankings. Unlike DENSE_RANK(), RANK() will appear as a vacant number. For example, if two tied 1s appear, the third number of RANK() will be 3 instead of 2. Syntax:scores.
ROW_NUMBER()
Returns a continuously increasing integer starting from 1 for each row of a Partition. Unlike RANK() and DENSE_RANK(), the value returned by ROW_NUMBER() does not repeat or have gaps and is continuously incremented. Syntax:scores.
QUALIFY()
The QUALIFY clause filters the results of window functions. In a SELECT statement, you can use the QUALIFY clause to apply conditions to a column to filter results. QUALIFY is analogous to the HAVING clause in aggregate functions. This function is supported from v2.5. QUALIFY simplifies the writing of SELECT statements. Before QUALIFY is used, a SELECT statement may go like this:<column_list>: columns from which you want to obtain data.
<data_source>: The data source is generally a table.
<window_function>: The QUALIFY clause can only be followed by a window function, including ROW_NUMBER(), RANK(), and DENSE_RANK().
Examples
item and the first row in each partition is returned.
item and the row with the highest sales in each partition is returned.
- QUALIFY supports only the following three window functions: ROW_NUMBER(), RANK(), and DENSE_RANK().
- The execution order of clauses in a query with QUALIFY is evaluated in the following order:
- FROM
- WHERE
- GROUP BY
- HAVING
- Window
- QUALIFY
- DISTINCT
- ORDER BY
- LIMIT
SUM()
Calculates the sum of specified rows. Syntax:DISTINCT is supported from StarRocks v4.0. When specified, SUM() sums only distinct values in the window.
Note
Window frame limitation:
When using SUM(DISTINCT) as a window function, only RANGE frames are supported. ROWS frames are NOT supported.
Examples
These examples use the data in the Sample table scores.
Example 1: Basic usage
Group data by subject and calculate the sum of scores of all rows within the group.
VARIANCE, VAR_POP, VARIANCE_POP
Returns the population variance of an expression. VAR_POP and VARIANCE_POP are aliases of VARIANCE. These functions can be used as window functions since v2.5.10. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
VAR_SAMP, VARIANCE_SAMP
Returns the sample variance of an expression. These functions can be used as window functions since v2.5.10. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
STD, STDDEV, STDDEV_POP
Returns the standard deviation of an expression. These functions can be used as window functions since v2.5.10. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
STDDEV_SAMP
Returns the sample standard deviation of an expression. This function can be used as a window function since v2.5.10. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
COVAR_SAMP
Returns the sample covariance of two expressions. This function is supported from v2.5.10. It is also an aggregate function. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
COVAR_POP
Returns the population covariance of two expressions. This function is supported from v2.5.10. It is also an aggregate function. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.
CORR
Returns the Pearson correlation coefficient between two expressions. This function is supported from v2.5.10. It is also an aggregate function. Syntax:expr is a table column, it must evaluate to TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, or DECIMAL.
Examples
This example uses the data in the Sample table scores.