
Prashant PatilWhen I first started learning SQL, my approach was very straightforward. I would begin with the...
When I first started learning SQL, my approach was very straightforward. I would begin with the SELECT statement, list the columns I wanted, add the FROM clause, and then shape the query based on the problem.
This worked well for simple queries. However, as problems became more complex, I repeatedly ran into the same issue: I had to rewrite queries from scratch because of small mistakes. This wasted time and slowed down my progress.
The core issue was simple — I was writing SQL in the order it appears, not in the order it executes.
Because of this, I:
While watching a developer solve multiple SQL problems, I noticed a pattern:
That is when I realized:
SQL is not executed in the order we write it.
Understanding this changed everything.
The actual execution order of SQL is:
Each step transforms the data before passing it to the next stage.
Selects the base table and performs joins.
Filters rows before grouping.
Groups rows based on column values.
Filters grouped data.
Chooses columns and applies calculations.
Removes duplicates.
Sorts results.
Restricts number of rows returned.
| order_id | customer | amount | city |
|---|---|---|---|
| 1 | A | 100 | Pune |
| 2 | B | 200 | Mumbai |
| 3 | A | 150 | Pune |
| 4 | C | 300 | Delhi |
| 5 | B | 250 | Mumbai |
Find total order amount per city where total > 200 and sort descending.
SELECT city, SUM(amount) AS total_amount
FROM orders
WHERE amount > 100
GROUP BY city
HAVING SUM(amount) > 200
ORDER BY total_amount DESC;
All rows are selected.
Filter amount > 100.
Remaining rows:
Groups formed:
Filter groups:
Result:
| city | total_amount |
|--------|-------------|
| Mumbai | 450 |
| Delhi | 300 |
Sorted descending:
Do not think in terms of writing SQL.
Think in terms of execution.
This will:
Understanding SQL execution order is a fundamental skill. Once you start thinking in execution steps instead of syntax order, your ability to write efficient and correct queries improves significantly.