SpinTheMic
Pro

SQL · Beginner

In what order is a SQL query executed?

By Anurag Pandey, Lead Data Engineer ·

The short answer

Logically, a query runs FROM and JOIN, then WHERE, GROUP BY, HAVING, then SELECT (with window functions), DISTINCT, ORDER BY and finally LIMIT. The engine may physically do things differently, but results must match this order.

Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Say it like this

About 55 seconds out loud. Use it as a model, then put it in your own words.

The order I write a query in isn't the order it's processed. Logically, it starts with FROM and the joins, to build the set of rows. Then WHERE filters those rows. Then GROUP BY forms groups, and HAVING filters the groups. Only then does SELECT compute the output columns, including window functions, followed by DISTINCT. Then ORDER BY sorts the result, and LIMIT or OFFSET cuts it down. This explains a lot of common errors. In standard SQL, I can't use a SELECT alias in WHERE, because WHERE runs before SELECT, but I can use it in ORDER BY. It's also why I can't filter on a window function in WHERE. And this is the logical order: the optimizer is free to execute it differently, as long as the result is the same.

What interviewers look for

  • You list the clauses in the right logical order.
  • You use the order to explain a real error, like aliases in WHERE.
  • You separate logical order from what the optimizer actually does.

Common mistakes

  • Saying SELECT runs first because it is written first.
  • Claiming the database physically runs steps in exactly this order.
  • Forgetting where window functions sit: after grouping and HAVING, before ORDER BY.

Follow-up questions to expect

  1. 1Why can you use a SELECT alias in ORDER BY but not in WHERE?
  2. 2Where do window functions fit in this order?
  3. 3How would you filter rows on a window function result?
Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Checked against

All interview question guides