Window Functions

CockroachDB supports the application of a function over a subset of the rows returned by a selection query. Such a function is known as a window function, and it allows you to compute values by operating on more than one row at a time. The subset of rows a window function operates on is known as a window frame.

For a complete list of supported window functions, see Functions and Operators.

Tip:

All aggregate functions can also be used as window functions. For more information, see the Examples below.

Note:

The examples on this page use the users, rides, and vehicles tables from our open-source fictional peer-to-peer ride-sharing application,MovR.

How window functions work

At a high level, window functions work by:

  • Creating a "virtual table" using a selection query.
  • Splitting that table into window frames using an OVER (PARTITION BY …) clause.
  • Applying the window function to each of the window frames created in step 2
    For example, consider this query:
  1. > SELECT DISTINCT(city),
  2. SUM(revenue) OVER (PARTITION BY city) AS city_revenue
  3. FROM rides
  4. ORDER BY city_revenue DESC;

Its operation can be described as follows (numbered steps listed here correspond to the numbers in the diagram below):

  • The outer SELECT DISTINCT(city) … FROM rides creates a "virtual table" on which the window functions will operate.
  • The window function SUM(revenue) OVER () operates on a window frame containing all rows of the query output.
  • The window function SUM(revenue) OVER (PARTITION BY city) operates on several window frames in turn; each frame contains the revenue columns for a different city (Amsterdam, Boston, L.A., etc.).
    Window function diagram

Caveats

The most important part of working with window functions is understanding what data will be in the frame that the window function will be operating on. By default, the window frame includes all of the rows of the partition. If you order the partition, the default frame includes all rows from the first row in the partition to the current row. In other words, adding an ORDER BY clause when you create the window frame (e.g., PARTITION BY x ORDER by y) has the following effects:

  • It makes the rows inside the window frame ordered.
  • It changes what rows the function is called on - no longer all of the rows in the window frame, but a subset between the "first" row and the current row.
    Another way of saying this is that you can run a window function on either:

  • All rows in the window frame created by the PARTITION BY clause, e.g., SELECT f(x) OVER () FROM z.

  • A subset of the rows in the window frame if the frame is created with SELECT f(x) OVER (PARTITION BY x ORDER BY y) FROM z.
    Because of this, you should be aware of the behavior of any aggregate function you use as a window function. If you are not seeing results you expect from a window function, this behavior may explain why. You may need to specify the frame boundaries explicitly using a frame clause such as ROWS BETWEEN <start> <end> [exclusion] (fully supported) or RANGE BETWEEN <start> <end> [exclusion] (only UNBOUNDED PRECEDING/CURRENT ROW/UNBOUNDED FOLLOWING supported).

Examples

Schema

The tables used in the examples are shown below.

  1. > SHOW CREATE TABLE users;
  1. +-------+-------------------------------------------------------------+
  2. | Table | CreateTable |
  3. +-------+-------------------------------------------------------------+
  4. | users | CREATE TABLE users ( |
  5. | | id UUID NOT NULL, |
  6. | | city STRING NOT NULL, |
  7. | | name STRING NULL, |
  8. | | address STRING NULL, |
  9. | | credit_card STRING NULL, |
  10. | | CONSTRAINT "primary" PRIMARY KEY (city ASC, id ASC), |
  11. | | FAMILY "primary" (id, city, name, address, credit_card) |
  12. | | ) |
  13. +-------+-------------------------------------------------------------+
  1. > SHOW CREATE TABLE rides;
  1. +-------+--------------------------------------------------------------------------+
  2. | Table | CreateTable |
  3. +-------+--------------------------------------------------------------------------+
  4. | rides | CREATE TABLE rides ( |
  5. | | id UUID NOT NULL, |
  6. | | city STRING NOT NULL, |
  7. | | vehicle_city STRING NULL, |
  8. | | rider_id UUID NULL, |
  9. | | vehicle_id UUID NULL, |
  10. | | start_address STRING NULL, |
  11. | | end_address STRING NULL, |
  12. | | start_time TIMESTAMP NULL, |
  13. | | end_time TIMESTAMP NULL, |
  14. | | revenue FLOAT NULL, |
  15. | | CONSTRAINT "primary" PRIMARY KEY (city ASC, id ASC), |
  16. | | CONSTRAINT fk_city_ref_users FOREIGN KEY (city, rider_id) REFERENCES |
  17. | | users (city, id), |
  18. | | INDEX rides_auto_index_fk_city_ref_users (city ASC, rider_id ASC), |
  19. | | CONSTRAINT fk_vehicle_city_ref_vehicles FOREIGN KEY (vehicle_city, |
  20. | | vehicle_id) REFERENCES vehicles (city, id), |
  21. | | INDEX rides_auto_index_fk_vehicle_city_ref_vehicles (vehicle_city |
  22. | | ASC, vehicle_id ASC), |
  23. | | FAMILY "primary" (id, city, vehicle_city, rider_id, vehicle_id, |
  24. | | start_address, end_address, start_time, end_time, revenue), |
  25. | | CONSTRAINT check_vehicle_city_city CHECK (vehicle_city = city) |
  26. | | ) |
  27. +-------+--------------------------------------------------------------------------+
  1. > SHOW CREATE TABLE vehicles;
  1. +----------+------------------------------------------------------------------------------------------------+
  2. | Table | CreateTable |
  3. +----------+------------------------------------------------------------------------------------------------+
  4. | vehicles | CREATE TABLE vehicles ( +|
  5. | | id UUID NOT NULL, +|
  6. | | city STRING NOT NULL, +|
  7. | | type STRING NULL, +|
  8. | | owner_id UUID NULL, +|
  9. | | creation_time TIMESTAMP NULL, +|
  10. | | status STRING NULL, +|
  11. | | mycol STRING NULL, +|
  12. | | ext JSON NULL, +|
  13. | | CONSTRAINT "primary" PRIMARY KEY (city ASC, id ASC), +|
  14. | | CONSTRAINT fk_city_ref_users FOREIGN KEY (city, owner_id) REFERENCES users (city, id),+|
  15. | | INDEX vehicles_auto_index_fk_city_ref_users (city ASC, owner_id ASC), +|
  16. | | FAMILY "primary" (id, city, type, owner_id, creation_time, status, mycol, ext) +|
  17. | | ) |
  18. +----------+------------------------------------------------------------------------------------------------+
  19. (1 row)

Customers taking the most rides

To see which customers have taken the most rides, run:

  1. > SELECT * FROM
  2. (SELECT distinct(name) as "name",
  3. COUNT(*) OVER (PARTITION BY name) AS "number of rides"
  4. FROM users JOIN rides ON users.id = rides.rider_id)
  5. ORDER BY "number of rides" DESC LIMIT 10;
  1. +-------------------+-----------------+
  2. | name | number of rides |
  3. +-------------------+-----------------+
  4. | Michael Smith | 53 |
  5. | Michael Williams | 37 |
  6. | John Smith | 36 |
  7. | Jennifer Smith | 32 |
  8. | Michael Brown | 31 |
  9. | Michael Miller | 30 |
  10. | Christopher Smith | 29 |
  11. | James Johnson | 28 |
  12. | Jennifer Johnson | 27 |
  13. | Amanda Smith | 26 |
  14. +-------------------+-----------------+
  15. (10 rows)

Customers generating the most revenue

To see which customers have generated the most revenue, run:

  1. > SELECT DISTINCT name,
  2. SUM(revenue) OVER (PARTITION BY name) AS "total rider revenue"
  3. FROM users JOIN rides ON users.id = rides.rider_id
  4. ORDER BY "total rider revenue" DESC
  5. LIMIT 10;
  1. +------------------+---------------------+
  2. | name | total rider revenue |
  3. +------------------+---------------------+
  4. | Michael Smith | 2251.04 |
  5. | Jennifer Smith | 2114.55 |
  6. | Michael Williams | 2011.85 |
  7. | John Smith | 1826.43 |
  8. | Robert Johnson | 1652.99 |
  9. | Michael Miller | 1619.25 |
  10. | Robert Smith | 1534.11 |
  11. | Jennifer Johnson | 1506.50 |
  12. | Michael Brown | 1478.90 |
  13. | Michael Johnson | 1405.68 |
  14. +------------------+---------------------+
  15. (10 rows)

Add row numbers to query output

To add row numbers to the output, kick the previous query down into a subquery and run the row_number() window function.

  1. > SELECT row_number() OVER (), *
  2. FROM (
  3. SELECT DISTINCT
  4. name,
  5. sum(revenue) OVER (
  6. PARTITION BY name
  7. ) AS "total rider revenue"
  8. FROM users JOIN rides ON users.id = rides.rider_id
  9. ORDER BY "total rider revenue" DESC
  10. LIMIT 10
  11. );
  1. +------------+------------------+---------------------+
  2. | row_number | name | total rider revenue |
  3. +------------+------------------+---------------------+
  4. | 1 | Michael Smith | 2251.04 |
  5. | 2 | Jennifer Smith | 2114.55 |
  6. | 3 | Michael Williams | 2011.85 |
  7. | 4 | John Smith | 1826.43 |
  8. | 5 | Robert Johnson | 1652.99 |
  9. | 6 | Michael Miller | 1619.25 |
  10. | 7 | Robert Smith | 1534.11 |
  11. | 8 | Jennifer Johnson | 1506.50 |
  12. | 9 | Michael Brown | 1478.90 |
  13. | 10 | Michael Johnson | 1405.68 |
  14. +------------+------------------+---------------------+
  15. (10 rows)

Customers taking the most rides and generating the most revenue

To see which customers have taken the most rides while generating the most revenue, run:

  1. > SELECT * FROM (
  2. SELECT DISTINCT name,
  3. COUNT(*) OVER w AS "number of rides",
  4. (SUM(revenue) OVER w)::DECIMAL(100,2) AS "total rider revenue"
  5. FROM users JOIN rides ON users.ID = rides.rider_id
  6. WINDOW w AS (PARTITION BY name)
  7. )
  8. ORDER BY "number of rides" DESC,
  9. "total rider revenue" DESC
  10. LIMIT 10;
  1. +-------------------+-----------------+---------------------+
  2. | name | number of rides | total rider revenue |
  3. +-------------------+-----------------+---------------------+
  4. | Michael Smith | 53 | 2251.04 |
  5. | Michael Williams | 37 | 2011.85 |
  6. | John Smith | 36 | 1826.43 |
  7. | Jennifer Smith | 32 | 2114.55 |
  8. | Michael Brown | 31 | 1478.90 |
  9. | Michael Miller | 30 | 1619.25 |
  10. | Christopher Smith | 29 | 1380.18 |
  11. | James Johnson | 28 | 1378.78 |
  12. | Jennifer Johnson | 27 | 1506.50 |
  13. | Robert Johnson | 26 | 1652.99 |
  14. +-------------------+-----------------+---------------------+
  15. (10 rows)

Customers with the highest average revenue per ride

To see which customers have the highest average revenue per ride, run:

  1. > SELECT name,
  2. COUNT(*) OVER w AS "number of rides",
  3. AVG(revenue) OVER w AS "average revenue per ride"
  4. FROM users JOIN rides ON users.ID = rides.rider_id
  5. WINDOW w AS (PARTITION BY name)
  6. ORDER BY "average revenue per ride" DESC, "number of rides" ASC
  7. LIMIT 10;
  1. +---------------------+-----------------+--------------------------+
  2. | name | number of rides | average revenue per ride |
  3. +---------------------+-----------------+--------------------------+
  4. | Madison Jimenez | 1 | 100.00 |
  5. | David Webster | 1 | 100.00 |
  6. | Samantha Holmes | 1 | 100.00 |
  7. | Charles Marquez | 1 | 100.00 |
  8. | Briana Howell | 1 | 99.99 |
  9. | Michelle Williamson | 1 | 99.99 |
  10. | Shannon Weiss | 1 | 99.98 |
  11. | Justin Barry | 1 | 99.98 |
  12. | Paul Key | 1 | 99.97 |
  13. | Holly Gregory | 1 | 99.97 |
  14. +---------------------+-----------------+--------------------------+
  15. (10 rows)

Customers with the highest average revenue per ride, given more than five rides

To see which customers have the highest average revenue per ride, given that they have taken at least 3 rides, run:

  1. > SELECT * FROM (
  2. SELECT DISTINCT name,
  3. COUNT(*) OVER w AS "number of rides",
  4. (AVG(revenue) OVER w)::DECIMAL(100,2) AS "average revenue per ride"
  5. FROM users JOIN rides ON users.ID = rides.rider_id
  6. WINDOW w AS (PARTITION BY name)
  7. )
  8. WHERE "number of rides" >= 5
  9. ORDER BY "average revenue per ride" DESC
  10. LIMIT 10;
  1. +------------------+-----------------+--------------------------+
  2. | name | number of rides | average revenue per ride |
  3. +------------------+-----------------+--------------------------+
  4. | Richard Wilson | 5 | 88.22 |
  5. | Rachel Johnson | 6 | 86.42 |
  6. | Kenneth Wilson | 5 | 85.26 |
  7. | Benjamin Avila | 5 | 85.23 |
  8. | Katie Evans | 5 | 85.10 |
  9. | Steven Griffith | 5 | 84.64 |
  10. | Phillip Moore | 5 | 84.22 |
  11. | Cheryl Adams | 5 | 83.85 |
  12. | Patrick Baker | 5 | 83.63 |
  13. | Stephen Gonzalez | 6 | 83.59 |
  14. +------------------+-----------------+--------------------------+
  15. (10 rows)

Total number of riders, and total revenue

To find out the total number of riders and total revenue generated thus far by the app, run:

  1. > SELECT
  2. COUNT("name") AS "total # of riders",
  3. SUM("total rider revenue") AS "total revenue" FROM (
  4. SELECT name,
  5. SUM(revenue) OVER (PARTITION BY name) AS "total rider revenue"
  6. FROM users JOIN rides ON users.id = rides.rider_id
  7. ORDER BY "total rider revenue" DESC
  8. LIMIT (SELECT count(distinct(rider_id)) FROM rides)
  9. );
  1. +-------------------+---------------+
  2. | total # of riders | total revenue |
  3. +-------------------+---------------+
  4. | 63117 | 15772911.41 |
  5. +-------------------+---------------+
  6. (1 row)

How many vehicles of each type

  1. > SELECT DISTINCT type, COUNT(*) OVER (PARTITION BY type) AS cnt FROM vehicles ORDER BY cnt DESC;
  1. +------------+-------+
  2. | type | cnt |
  3. +------------+-------+
  4. | bike | 33377 |
  5. | scooter | 33315 |
  6. | skateboard | 33307 |
  7. +------------+-------+
  8. (3 rows)

How much revenue per city

  1. > SELECT DISTINCT(city), SUM(revenue) OVER (PARTITION BY city) AS city_revenue FROM rides ORDER BY city_revenue DESC;
  1. +---------------+--------------+
  2. | (city) | city_revenue |
  3. +---------------+--------------+
  4. | paris | 567144.48 |
  5. | washington dc | 567011.74 |
  6. | amsterdam | 564211.74 |
  7. | new york | 561420.67 |
  8. | rome | 560464.52 |
  9. | boston | 559465.75 |
  10. | san francisco | 558807.13 |
  11. | los angeles | 558805.45 |
  12. | seattle | 555452.08 |
  13. +---------------+--------------+
  14. (9 rows)

See also

Was this page helpful?
YesNo