The app for independent voices

๐—ฆ๐—ค๐—Ÿ ๐—ค๐˜‚๐—ฒ๐—ฟ๐—ถ๐—ฒ๐˜€ ๐——๐—ผ๐—ป'๐˜ ๐—ฆ๐˜๐—ฎ๐—ฟ๐˜ ๐—ช๐—ถ๐˜๐—ต ๐—ฆ๐—˜๐—Ÿ๐—˜๐—–๐—ง

We usually start with SQL by entering SELECT, but it is not executed first. SELECT actually gets executed as the 5th step.

This explains why some SQL statements work while others donโ€™t.

Here is the actual execution order:

๐Ÿญ. ๐—™๐—ฅ๐—ข๐— /๐—๐—ข๐—œ๐—ก โ€“ Tables are merged to form the basis of the data set. All ON conditions are assessed at this point

๐Ÿฎ. ๐—ช๐—›๐—˜๐—ฅ๐—˜ โ€“ Rows are filtered before any grouping takes place. You cannot refer to any aggregates at this point because none have been created yet

๐Ÿฏ. ๐—š๐—ฅ๐—ข๐—จ๐—ฃ ๐—•๐—ฌ โ€“ The remaining rows are grouped. After this step, you're working with groups rather than individual rows

๐Ÿฐ. ๐—›๐—”๐—ฉ๐—œ๐—ก๐—š โ€“ Groups get filtered. This is where you can filter on aggregate results like ๐—–๐—ข๐—จ๐—ก๐—ง(*) > ๐Ÿฑ

๐Ÿฑ. ๐—ฆ๐—˜๐—Ÿ๐—˜๐—–๐—ง โ€“ Columns are computed and returned. Window functions run here too

๐Ÿฒ. ๐—ข๐—ฅ๐——๐—˜๐—ฅ ๐—•๐—ฌ โ€“ Results are sorted. This runs after SELECT, so you can use aliases in your sorting

๐Ÿณ. ๐—Ÿ๐—œ๐— ๐—œ๐—ง โ€“ Output is capped to the specified row count

This order answers common debugging questions. Can you filter on a window function result in a WHERE clause? No, window functions run in SELECT, which happens after WHERE.

Can you use a GROUP BY alias in ORDER BY? Yes, ORDER BY runs last. This is also why ๐—ฃ๐—ผ๐˜€๐˜๐—ด๐—ฟ๐—ฒ๐˜€, ๐— ๐˜†๐—ฆ๐—ค๐—Ÿ, and ๐—ฆ๐—ค๐—Ÿ ๐—ฆ๐—ฒ๐—ฟ๐˜ƒ๐—ฒ๐—ฟ all reject ๐—ช๐—›๐—˜๐—ฅ๐—˜ ๐—–๐—ข๐—จ๐—ก๐—ง(*) > ๐Ÿฑ, as the aggregate doesn't exist at that stage.

Database engines optimize heavily and may reorder operations for performance. But this logical order determines what's valid SQL.

Feb 4
at
7:37 AM
Relevant people

Log in or sign up

Join the most interesting and insightful discussions.