Skip to content

Lesson 18 ยท Querying and Performance

Analytical SQL for Warehouses

Query a warehouse with analytical SQL: subtotals with ROLLUP and CUBE, window functions, period comparisons, shares of total and OLAP operations.

A good model makes basic queries simple. Analysts also need subtotals, rankings, running totals and comparisons with earlier periods. SQL handles these well, mostly with grouping extensions and window functions.

OLAP operations in plain words

The traditional picture of OLAP is a data cube: measures arranged along dimensions. You do not need a special cube product to use its vocabulary.

Moving around the data

Roll up City to country
Drill down Year to month
1 / 2

A pivot turns values of one dimension into columns. In SQL, rolling up and drilling down mostly mean changing the GROUP BY list, while slicing and dicing are WHERE filters.

Subtotals

Many databases offer ROLLUP, CUBE and GROUPING SETS. SQLite does not, so this is read-only:

SQL
-- Read-only: supported by many warehouse platforms, not by SQLite
SELECT region, category, SUM(amount) AS revenue
FROM sales
GROUP BY ROLLUP (region, category);

ROLLUP (region, category) returns detail by region and category, a subtotal per region and a grand total. CUBE returns subtotals for every combination of the listed columns. GROUPING SETS lets you list exactly the groupings you want. Subtotal rows show NULL in rolled-up columns; the GROUPING() function tells them apart from real NULL data.

You can build the same result with UNION ALL:

SQL Stand-in for ROLLUP with UNION ALL

Press Run (or Ctrl + Enter) to see the result here.

Window functions

An aggregate with GROUP BY collapses rows. A window function calculates across related rows while keeping each row. PARTITION BY splits the rows into groups, ORDER BY orders them, and an optional frame limits which rows are used. The SQL tutorial covers window functions in depth.

SQL Running totals, change and share

Press Run (or Ctrl + Enter) to see the result here.

In the first two months of each category, the three-row moving average uses fewer than three rows. Label it or filter it out if that would mislead.

Rows are not periods

LAG looks at the previous row. If a month has no sales, there may be no row, and "previous row" is no longer "previous month". Start from a complete calendar, from your date dimension, and join facts to it.

SQL Fill missing months before comparing

Press Run (or Ctrl + Enter) to see the result here.

April is now compared with March's zero, not with February. Use zero only when "no rows" truly means "no sales". If March data failed to load, zero would be wrong, so check freshness first.

For year-over-year comparisons, join to the same period one year earlier using date dimension columns. Compare like with like: a month that is only partly over should be compared with the same number of days.

Ranking and top-N

ROW_NUMBER, RANK and DENSE_RANK differ in how they treat ties. To keep the top products per region, rank in a common table expression and filter in the outer query. Add a second ordering column when you need a repeatable order for ties.

Pivoting

A portable pivot uses conditional aggregation:

SQL
-- Read-only pattern: one column per value
SELECT category,
       SUM(CASE WHEN month = '2026-01' THEN revenue ELSE 0 END) AS jan,
       SUM(CASE WHEN month = '2026-02' THEN revenue ELSE 0 END) AS feb
FROM monthly_sales
GROUP BY category;

Some platforms also have a PIVOT clause, with varying syntax.

Build queries in steps

Long analytical queries are easier to trust when you build them from named common table expressions. A useful pattern has three stages:

  1. Filter and join: produce the rows at a known grain.
  2. Aggregate: summarize to the grain of the report, such as month and category.
  3. Window: add running totals, shares or rankings over those summary rows.

Run each stage on its own while developing, and check its row count. If the first stage returns more rows than the fact table contains, a join has multiplied them.

Where filters go matters

Window functions are calculated after WHERE. If you filter to April and then call LAG, there is no March row left to compare with. Calculate the window in an inner query over a wider range, and filter in the outer query:

SQL
-- Read-only pattern: calculate first, then filter
WITH with_previous AS (
  SELECT month, revenue,
         LAG(revenue) OVER (ORDER BY month) AS previous_month
  FROM monthly_total
)
SELECT * FROM with_previous
WHERE month = '2026-04';

The same idea applies to a "share of total": decide whether the total should include rows that the report hides.

Year to date

A year-to-date figure is a running total that restarts each year. Partition the window by year and order by month. For a fiscal year, partition by the fiscal year column from the date dimension instead. When comparing this year to date with last year to date, cut both at the same point, and say what that point is. An in-progress period compared with a complete one can easily look like a decline.

Percentage change safely

For percentage change, divide the difference by the earlier value and protect the divisor with NULLIF. When the earlier value is zero or missing, there is no meaningful percentage. Show it as blank with an explanation instead of inventing 0% or 100%. Negative starting values also make percentages hard to read, so show the absolute change next to them.

Check an analytical result

Analytical queries can be wrong while looking tidy, so verify them with quick cross-checks. Does the grand total equal a simple SUM over the filtered facts? Do shares within each group add up to 100%, allowing for rounding? Does the last value of a running total equal the group's total? Does the number of output rows match the number of periods multiplied by the number of groups you expect?

Pick one group and calculate it by hand from a few detail rows. This takes minutes and often reveals a wrong partition column or a missing period.

Common mistakes

Adding an ORDER BY inside OVER changes the default frame, so a total can become a running total. When the frame matters, write it explicitly. With RANGE, which is the default in standard SQL when a window is ordered, tied rows are included together.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does moving from city totals to country totals do?

    Rolling up moves to a coarser level of a hierarchy.
  2. 2. How does a window function differ from an aggregate with GROUP BY?

    Windows add calculations without collapsing rows.
  3. 3. Why join facts to a complete calendar before using LAG?

    LAG works on rows, not on calendar periods.
  4. 4. What does CUBE return compared with ROLLUP over the same columns?

    ROLLUP follows the column order as a hierarchy; CUBE covers all combinations.

Summary

  • Roll up, drill down, slice, dice and pivot describe ways to explore data.
  • ROLLUP, CUBE and GROUPING SETS create subtotals where supported.
  • Window functions give running totals, changes, shares and rankings.
  • Use a complete calendar and fair period comparisons.

Next: Partitioning, Clustering and Columnar Performance

Your progress is saved in this browser. No account needed.