Sobes.tech
Middle

What is the difference between a window function and the GROUP BY operator?

sobes.tech AI

Answer from AI

The window function operates on a set of rows related to the current row (window) and returns a single value for each row. The GROUP BY operator groups identical values into one set and returns a single aggregated value for each group.

-- Example of a window function: numbering rows within a group
SELECT
    order_id,
    order_date,
    ROW_NUMBER() OVER (PARTITION BY order_date ORDER BY order_id) as row_num_in_day
FROM orders;
-- Example of GROUP BY: counting the number of orders by date
SELECT
    order_date,
    COUNT(order_id) as orders_count
FROM orders
GROUP BY order_date;
Feature Window Function GROUP BY
Number of rows in result Preserves all rows of the original set Reduces the number of rows to the number of groups
Application Calculations "per group" without collapsing it Aggregation and collapsing of groups
Syntax Uses OVER() Uses GROUP BY
Access to rows Access to individual rows within windows Access only to the aggregated value of the group