CodeBlanks Logo Icon CodeBlanks

What is a window function?

Compute per row with OVER.

What is a window function?

A window function computes over a set of rows (a window). It returns results without collapsing rows.

SELECT name, price,
  RANK() OVER (ORDER BY price DESC) AS rk
FROM products;

This query gives each product a price rank.

name, price, RANK() OVER (ORDER BY price DESC) AS rk is selected from products. RANK() is a window function: it computes a value for each row over the window defined in OVER (…), without collapsing rows.

What is a window function? — details

A window function does not collapse like GROUP BY. Each row gets its own window result.

This lets you see each product's own price and the average price of all products on the same row, which GROUP BY cannot do.

Practice What is a window function?

Find each product's price rank with RANK() OVER (ORDER BY price DESC).

Starter code

query.sql
-- window function
SELECT name, price,
  RANK()

Sample solution

query.sql
SELECT name, price,
  RANK() OVER (ORDER BY price DESC) AS rk
FROM products;

Expected output

name    price  rk
Laptop  1500   1
Telefon 800    2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a window function do to rows?

  • Does not collapse them Correct answer
  • Collapses them
  • Deletes them
  • Sorts them

Explanation: A window function does not collapse rows.

2 Add OVER

Question
RANK() ____ (ORDER BY price DESC)
Answer
RANK() OVER (ORDER BY price DESC)

Explanation: Window functions are written with OVER; the ORDER BY inside OVER sets the ranking order.

3 What is a window function: match the terms

Term Meaning
window window
OVER over
RANK rank
no collapse preserves

All lessons in Advanced