Skip to content

Advanced SQL: Window Functions and CTEs

Common table expressions and window functions make complex analysis readable: running totals, rankings and period comparisons.

Editorial team 2 min read

Once you know the basics, two features transform what SQL can do: common table expressions and window functions.

Common Table Expressions (CTEs)

A CTE names an intermediate result, making complex queries readable:

WITH monthly AS (
    SELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue
    FROM orders
    GROUP BY 1
)
SELECT month, revenue
FROM monthly
ORDER BY month;

Window Functions

Window functions calculate across related rows without collapsing them into groups.

Running total:

SELECT month, revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total
FROM monthly;

Ranking within groups:

SELECT region, product, revenue,
       RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rank_in_region
FROM product_sales;

Comparing with the previous period:

SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly;

Moving average:

AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)

Useful Functions

ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, FIRST_VALUE, NTILE, and aggregates used with OVER.

Common Uses

Top-N per group, deduplication (keep the latest row per ID with ROW_NUMBER), cohort analysis, retention and period-over-period comparisons.

Tip

Syntax varies slightly between databases — check your platform's documentation for date functions and window-frame details.

More in Data science & analytics

All Data science & analytics guides →
Data science & analytics Guide · 2 min

Descriptive Statistics Essentials

Mean, median, mode, spread and shape: the summary numbers every analysis starts with, and when each one misleads.

Data science & analytics 2 min read 6 Mar 2026

Data science & analytics Guide · 2 min

Probability Basics for Data Work

The probability ideas analysts use every day: events, conditional probability, independence and Bayes' theorem.

Data science & analytics 2 min read 5 Mar 2026

Data science & analytics Guide · 2 min

Common Probability Distributions

Normal, binomial, Poisson, exponential and more: recognising the shapes data takes and what they imply.

Data science & analytics 2 min read 4 Mar 2026

Data science & analytics Guide · 2 min

Hypothesis Testing Explained

Null hypotheses, p-values and significance: what a hypothesis test tells you, and the misunderstandings to avoid.

Data science & analytics 2 min read 3 Mar 2026