SQL window functions and aggregate functions serve different purposes, though they both operate on sets of rows. Here’s an overview of each:
SQL Window Functions:
- Purpose: Window functions perform calculations across a set of rows related to the current row within a query result set. They allow you to perform calculations on a “window” of rows that are somehow related to the current row, without collapsing the result set into a single row.
- Examples: Commonly used window functions include
ROW_NUMBER()
, RANK()
, DENSE_RANK()
, LAG()
, LEAD()
, SUM() OVER()
, AVG() OVER()
, MAX() OVER()
, MIN() OVER()
, etc.
- Syntax: Window functions are typically used with an
OVER()
clause, which defines the window or set of rows over which the function operates. The OVER()
clause includes the partitioning and ordering specifications for the window.
- Usage: Window functions are used for tasks like ranking rows, calculating moving averages, identifying gaps or overlaps in data, and comparing values to adjacent rows.
SQL Aggregate Functions:
- Purpose: Aggregate functions perform a calculation on a set of values and return a single value. They collapse multiple rows into a single result.
- Examples: Common aggregate functions include
SUM()
, AVG()
, COUNT()
, MAX()
, MIN()
, etc.
- Usage: Aggregate functions are typically used to compute summary statistics such as totals, averages, counts, maximums, or minimums across a dataset.
Differences:
- Calculation Scope: Window functions operate on sets of rows related to the current row, whereas aggregate functions operate on entire sets of rows.
- Output: Window functions return multiple rows, while aggregate functions return a single result.
- Result Presentation: Window function results are presented alongside existing rows in the result set, whereas aggregate function results typically appear as a separate row or as part of the query result’s single row.
- Syntax: Window functions commonly use the
OVER()
clause, while aggregate functions are applied directly to columns or expressions in the SELECT
clause.
In summary, window functions are more flexible for analyzing and manipulating sets of rows relative to the current row, while aggregate functions are used to summarize entire sets of rows into single values. Both types of functions are powerful tools in SQL for different types of data analysis tasks.