Mastering SQL Window Functions: Types and Uses with Examples

What Are Window Functions in SQL?

Window functions in SQL allow you to perform calculations across a set of table rows related to the current row without collapsing them into a single result. Unlike aggregate functions (e.g., SUM, AVG), which combine rows into a single output, window functions maintain individual row details while providing insights across partitions of data.

ORACLE
Mastering Oracle Database Architecture: A Comprehensive Overview

Types of SQL Window Functions

1. Ranking Functions: Used for ranking rows within a partition.

  • ROW_NUMBER(): Assigns a unique sequential number to each row within a partition of a result set, starting at 1.
    • Syntax:
      • SELECT column1, ROW_NUMBER() OVER (PARTITION BY column2 ORDER BY column3) AS row_num FROM table_name;
  • RANK(): Provides a rank to each row within a partition with gaps when there are ties. Rows with the same value receive the same rank, and the next rank is skipped.
    • Syntax:
      • SELECT column1, RANK() OVER (PARTITION BY column2 ORDER BY column3) AS rank_num FROM table_name;
  • DENSE_RANK(): Similar to RANK() but without gaps. Rows with the same value receive the same rank, and the next rank continues without skipping.
    • Syntax:
      • SELECT column1, DENSE_RANK() OVER (PARTITION BY column2 ORDER BY column3) AS dense_rank_num FROM table_name;
  • NTILE(n): Divides rows into n equally sized groups within a partition and assigns a group number to each row, ranging from 1 to n.
    • Syntax:
      • SELECT column1, NTILE(4) OVER (ORDER BY column2) AS ntile_group FROM table_name;

2. Aggregate Window Functions: Offer cumulative results without grouping rows.

  • SUM(), AVG(), MIN(), MAX(): Performs aggregation on rows within the window frame (e.g., calculating the total, average, minimum, or maximum values).
    • Syntax (for SUM example):
      • SELECT column1, SUM(column2) OVER (PARTITION BY column3 ORDER BY column4) AS cumulative_sum FROM table_name;
  • COUNT(): Counts the number of rows within the partition or window frame.
    • Syntax:
      • SELECT column1, COUNT(column2) OVER (PARTITION BY column3 ORDER BY column4) AS row_count FROM table_name;

3. Value Window Functions: Help retrieve values from specific rows.

  • LAG(): Retrieves data from the previous row within the window frame, useful for comparing the current row with the previous one.
    • Syntax:
      • SELECT column1, LAG(column2, 1, 0) OVER (PARTITION BY column3 ORDER BY column4) AS previous_value FROM table_name;
  • LEAD(): Retrieves data from the following row within the window frame, allowing comparison with the next row.
    • Syntax:
      • SELECT column1, LEAD(column2, 1, 0) OVER (PARTITION BY column3 ORDER BY column4) AS next_value FROM table_name;
  • FIRST_VALUE(): Fetches the first value in the window frame for each row.
    • Syntax:
      • SELECT column1, FIRST_VALUE(column2) OVER (PARTITION BY column3 ORDER BY column4) AS first_value FROM table_name;
  • LAST_VALUE(): Fetches the last value in the window frame for each row.
    • Syntax:
      • SELECT column1, LAST_VALUE(column2) OVER (PARTITION BY column3 ORDER BY column4 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_value FROM table_name;
  • NTH_VALUE(n): Fetches the nth value in the window frame.
    • Syntax:
      • SELECT column1, NTH_VALUE(column2, n) OVER (PARTITION BY column3 ORDER BY column4) AS nth_value FROM table_name;

4. Analytic Functions: Perform statistical calculations.

  • PERCENT_RANK(): Calculates the relative rank of a row as a percentage of the total rows within the partition.
    • Syntax:
      • SELECT column1, PERCENT_RANK() OVER (PARTITION BY column2 ORDER BY column3) AS percent_rank FROM table_name;
  • CUME_DIST(): Shows the cumulative distribution of a row, indicating the proportion of rows with values less than or equal to the current row.
    • Syntax:
      • SELECT column1, CUME_DIST() OVER (PARTITION BY column2 ORDER BY column3) AS cumulative_distribution FROM table_name;
  • PERCENTILE_CONT and PERCENTILE_DISC: Calculate the continuous and discrete percentiles, respectively, based on a specified percentile value.
    • Syntax (PERCENTILE_CONT example):
      • SELECT column1, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column2) OVER (PARTITION BY column3) AS median_value FROM table_name;

Tips for Using SQL Window Functions Effectively

  • Choosing the Right Ranking Function: Start with ROW_NUMBER() or RANK() for ranking tasks. Use RANK() if you want gaps for ties, and DENSE_RANK() if you prefer continuous ranking without gaps.
  • Order Matters: When working with cumulative sums or averages, always use an ORDER BY clause in the OVER() statement to ensure accurate results.
  • Use LAG() and LEAD() Wisely: These functions are perfect for comparing the current row with previous or next rows, making them highly useful in trend analysis.
  • Mind the Performance: Window functions can be resource-intensive. Ensure proper indexing when dealing with large datasets to optimize performance.

Common Use Cases in Data Analysis

  • Running Totals: Window functions are great for calculating running totals, such as tracking cumulative sales month by month in financial reports.
  • Moving Averages: Ideal for analyzing trends, they help calculate moving averages, like understanding how stock prices change over time or smoothing out seasonal sales patterns.
  • Ranking Products: You can rank products based on sales within different regions, helping businesses identify top performers.
  • Trend Analysis: Window functions let you analyze trends without losing individual row details, making them invaluable for deep data analysis.
SQL query design patterns
SQL Query Design Patterns: Writing Efficient Queries

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements. If any queries feel free to contact us at ganeshpudi12@gmail.com

1 thought on “Mastering SQL Window Functions: Types and Uses with Examples”

Leave a Reply

Home
SQL
PLSQL
Interview Q&A