Query Order of Execution

noun

say it: “KWEER-ee OR-der uv ek-sih-KYOO-shun” /ˈkwɪəri ˈɔːrdər əv ˌɛksɪˈkjuːʃən/

The order the database works through a query's clauses: FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY.

What is Query Order of Execution in SQL?

Query Order of Execution — The order the database works through a query's clauses, which isn't the order you write them: FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY. It's why WHERE can't use a column alias but ORDER BY can.

SELECT CategoryID, COUNT(*) AS Products   -- 5
FROM Products                            -- 1
WHERE Discontinued = 0                   -- 2
GROUP BY CategoryID                      -- 3
HAVING COUNT(*) > 10                     -- 4
ORDER BY Products DESC;                  -- 6

In a sentence

  • “The query order of execution explains why WHERE can't use the alias I made in SELECT.”

Level: Journeyman · More SQL terms at this level

Updated