What is the execution sequence when a query has CTEs, window functions, and GROUP BY?

Quick Overview

Asks for the logical order in which SQL evaluates CTEs, WHERE, GROUP BY, HAVING, window functions, ORDER BY and LIMIT. Tests whether you can predict what rows a window function sees, why you cannot filter on it in WHERE, and how logical order differs from the executed plan.

What is the execution sequence when a query has CTEs, window functions, and GROUP BY?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

What is the logical execution sequence when a SQL query has CTEs, window functions, and `GROUP BY`? ```hint Ask what each clause can see A window function looks across a set of rows. Work out which clauses must already have finished for that set to exist. ``` ```hint Test it with a filter Try writing `WHERE rn = 1` on a `ROW_NUMBER()` column in the same query and think about why the database refuses. ``` ### What a Strong Answer Covers - Where the CTEs sit relative to the main query - The logical order of the main query's clauses - The exact point at which window functions are evaluated, and what rows they see - What that order allows and forbids, such as filtering on a window result - The difference between logical order and the plan the optimizer actually runs ### Follow-up Questions - How would you return each customer's latest order using a window function? - Why does `SUM(SUM(amount)) OVER ()` work while `SUM(ROW_NUMBER() OVER (ORDER BY id))` fails? - What does `QUALIFY` do, and how would you get the same result in an engine that lacks it? - When does PostgreSQL materialize a CTE, and when does it inline it into the main query?

Overview: Asks for the logical order in which SQL evaluates CTEs, WHERE, GROUP BY, HAVING, window functions, ORDER BY and LIMIT. Tests whether you can predict what rows a window function sees, why you cannot filter on it in WHERE, and how logical order differs from the executed plan.

Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the logical execution sequence when a SQL query has CTEs, window functions, and GROUP BY?

What a Strong Answer Covers Guidance

  • Where the CTEs sit relative to the main query
  • The logical order of the main query's clauses
  • The exact point at which window functions are evaluated, and what rows they see
  • What that order allows and forbids, such as filtering on a window result
  • The difference between logical order and the plan the optimizer actually runs

Follow-up Questions Guidance

  • How would you return each customer's latest order using a window function?
  • Why does SUM(SUM(amount)) OVER () work while SUM(ROW_NUMBER() OVER (ORDER BY id)) fails?
  • What does QUALIFY do, and how would you get the same result in an engine that lacks it?
  • When does PostgreSQL materialize a CTE, and when does it inline it into the main query?