GROUP BY

  • Purpose: Aggregates data into summary rows based on one or more columns.
  • Result: Returns one row per group.
  • Usage: Commonly used with aggregate functions like SUM(), COUNT(), AVG(), etc.
CategorySalesSaleDate
Electronics1002025-01-01
Electronics2002025-01-02
Electronics1502025-01-03
Furniture3002025-01-01
Furniture1002025-01-02
Furniture4002025-01-03
SELECT 
    Category,
    SUM(Sales) AS TotalSales
FROM 
    SalesTable
GROUP BY 
    Category;

\

Result:

CategoryTotalSales
Electronics450
Furniture800

Visual Representation for GROUP BY:

  • Electronics: 450
  • Furniture: 800

PARTITION BY

  • Purpose: Divides the result set into partitions (subsets) for a specific column, but it does not collapse rows like GROUP BY.
  • Result: All rows are retained, and aggregate functions are applied over each partition.
  • Usage: Commonly used with window functions like ROW_NUMBER(), RANK(), SUM() OVER().
SELECT 
    Category,
    Sales,
    SUM(Sales) OVER (PARTITION BY Category ORDER BY SaleDate) AS RunningTotal
FROM 
    SalesTable;

Result:

CategorySalesRunningTotal
Electronics100100
Electronics200300
Electronics150450
Furniture300300
Furniture100400
Furniture400800

A line chart showing the running totals for each category over time:

  • Electronics: 100 → 300 → 450
  • Furniture: 300 → 400 → 800

Key Differences:

FeatureGROUP BYPARTITION BY
Collapses rowsYes, groups rows into a single result row.No, retains all rows in the result set.
Aggregates scopeAcross groups.Across partitions, per row.
ResultOne row per group.One row per original row, with partition info.