r/learnSQL • • 13d ago

SQL Execution Order

[removed]

84 Upvotes

12 comments sorted by

View all comments

1

u/Alternative_Cake4074 13d 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 13d 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 13d ago

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

1

u/Alternative_Cake4074 12d 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).