SQL and databases

Stage 2 · Lesson 8 of 8

The logical order a query runs in

Querying one table

You write a query in the order SELECT, FROM, WHERE, , HAVING, . The database works through it in a different logical : FROM and joins first, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT or TOP.

This order explains many confusing errors. A you name in SELECT does not exist yet when WHERE runs, but it does exist by ORDER BY. WHERE runs before grouping, so it cannot filter on a total such as a COUNT or SUM, which is why HAVING exists.

run after WHERE, so you cannot filter on them directly. Keep this list in your head through the next two stages.

Common trapmemorising syntax without this model, then guessing when an error says a column does not exist.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CoursePaid
    Grokking SQL for Tech Interviews

    Design Gurus · Intermediate · Subscription

    The basics, order of execution and functions chapters, each followed by graded problems

  • CourseFree
    SQLBolt

    SQLBolt · Beginner

    Free: Lessons 1 to 4, 8, 9 and 12 cover SELECT, filtering, sorting, NULLs, expressions and query order

Practise

Keep handy

  • The SELECT page and the functions and operators chapter

  • Its SQL pages give quick examples and note where MySQL and SQL Server syntax differ

Also worth your time

Mark this stage as not done?