WINDOW Functions

This is used with The OVER() and PARTITION BY() Function.

General Syntax

WINDOW_FUNCTION() OVER (
    [PARTITION BY partition_expression]
    ORDER BY order_expression
) as new_column_name
PARTITION BY vs GROUP BY

The PARTITION BY clause works similar to how The GROUP BY Clause works in aggregated queries. Each partition is then treated independnetly by the window function.

Order of Execution

The expressions within the ORDER BY clause are evaluated in the order they are specified. The ORDER BY clause can include multiple expressions, and each expression is evaluated in the order they appear.

Types of Window Functions

Pasted image 20240907203201.png

Example using ROW_NUMBER():

The ROW_NUMBER() function is a window function in SQL that assigns a unique sequential integer to each row within a partition of a result set.

ROW_NUMBER() OVER (
SELECT 
    order_id,
    customer_id,
    order_date,
    ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS row_num
FROM 
    Orders;
Powered by Forestry.md