SQL-Engineering-Handbook

PARTITION BY

PARTITION BY diagram showing the result set split into independent windows

Overview

PARTITION BY splits the result set into independent groups (partitions) before a window function is applied. The window function then resets and recalculates separately within each partition – similar in spirit to GROUP BY, but without collapsing rows.

Learning Objectives

Prerequisites

Syntax

SELECT
    column_a,
    grouping_column,
    WINDOW_FUNCTION() OVER (
        PARTITION BY grouping_column
        ORDER BY sort_column
    ) AS result_column
FROM table_name;

Dataset Used

employes joined to departments on dept_id

Examples

See 04_partition_by.sql.

Real World Applications

Business Use Cases

Domain Scenario
HR Rank employees within their own department
Retail Rank products within their own category
Banking Rank transactions within their own account

Common Mistakes

Best Practices

Engineering Notes

PARTITION BY does not require a separate index from ORDER BY, but query planners benefit significantly from a composite index on (partition_column, order_column) for large tables, since it avoids a full sort per partition.

Practice Questions

  1. Assign row numbers within each department.
  2. Assign ranks within each department.
  3. Count employees in each department using a window function.
  4. Show the first employee from every department.
  5. Build a full department leaderboard combining ROW_NUMBER(), RANK(), and DENSE_RANK().

Difficulty

Intermediate

Estimated Time

25–30 minutes

Learning Outcomes

Next Topic

05_LAG_LEAD


Lesson Navigation

← Previous: 03_DENSE_RANKModule README → Next: 05_LAG_LEAD