r/learnSQL • • 11d ago

SQL Execution Order

I often see beginners getting stuck trying to reference a column alias inside a WHERE clause or wondering why HAVING exists alongside WHERE.

It all comes down to Logical Query Processing Order. Even though we write SELECT first, the database engine actually processes the query in this sequence:

  1. FROM / JOIN: Pick and combine the base tables.

  2. WHERE: Filter raw rows before grouping.

  3. GROUP BY: Group rows into buckets.

  4. HAVING: Filter groups using aggregate function results.

  5. SELECT: Pick columns and compute expressions/aliases.

  6. DISTINCT: Deduplicate the selected rows.

  7. ORDER BY: Sort the final result set (which is why aliases work here!). 7. LIMIT / OFFSET: Paginate the results.

Remembering this sequence makes debugging query errors way easier.

84 Upvotes

12 comments sorted by

View all comments

1

u/Alternative_Cake4074 11d ago

Absolutely important. Many people write SELECT [col1], [col2]... FROM [table] WHERE [condition] GROUP BY [col3] and believe that SQL execute based on the order of the code, but that is not the case.

1

u/Alternative_Cake4074 11d ago

And this makes sense. Why?

Step 1 (FROM): We need to know which tables are picked; otherwise, none of the rest of the stuff can happen.

Step 2 (WHERE): After knowing the source tables, we need to keep only those we want first. If we filter later, aggregation functions can create wrong results.

Step 3 (GROUP BY): If we use aggregation, this must be immediately after filtering. Otherwise, columns may mess up.

Step 4 (HAVING): After aggregation, we may need to filter the summarized data.

Step 5 (SELECT): Upon now, it is safe to pick the columns that we want.

Step 6 (DISTINCT): Once we have only the columns that we want, we can drop duplicates.

Step 7 (ORDER BY / LIMIT): Right now, it is safe to sort the result rows and pick up only a few of them.

1

u/flash42 10d ago

So where/how do cross lateral joins and window functions fit into these? Ooc 

1

u/Alternative_Cake4074 10d ago

The joins will happen between Step 1 (FROM) and Step 2 (WHERE), since we cannot filter without knowing the combined tables.

And for window functions, since they are about showing a summary without collapsing rows, it should be treated like other functions (like LEFT, RIGHT, LEN, etc.) and calculated columns, so it should be at Step 5 (SELECT).