How SQL Engine Read Your Query (SQL Operation Order)
Hello friend. Today we talk about SQL operation order. When we code SQL, we
type SELECT first. But SQL engine brain not read like that. It
read different way from top to bottom.
If you not know real execution order, you will have big bug like using Alias name in WHERE clause and get error.
Real Execution Order Step by Step
- FROM and JOIN: This is first step. SQL must find table and combine table before do anything.
- WHERE: SQL filter row data right now. Not match, it throw away.
- GROUP BY: Now it group data that same same together.
- HAVING: Filter group data again (WHERE cannot filter group, so we use HAVING here).
- SELECT: Yes! Step 5 then SQL finally look at SELECT column that we write at line 1.
- DISTINCT: Remove duplicate row.
- ORDER BY: Sort A to Z or Z to A.
- LIMIT / OFFSET: Cut data to show only top 10 or do pagination.
Example SQL Query
Look at this code. We write SELECT on line 1, but SQL brain read FROM first.
SELECT d.department_name, COUNT(s.student_id) AS total_stu -- Step 5
FROM tbDepartments d -- Step 1
JOIN tbEnrollments s ON d.department_id = s.department_id -- Step 1
WHERE s.is_active = 1 -- Step 2
GROUP BY d.department_name -- Step 3
HAVING COUNT(s.student_id) > 10 -- Step 4
ORDER BY total_stu DESC -- Step 7
LIMIT 5; -- Step 8
Why remember this?
Example: In SELECT you put COUNT(s.student_id) AS total_stu. If
you try to use total_stu in WHERE clause, it show error! Why?
Because step 2 (WHERE) run before step 5 (SELECT). The brain of SQL not yet
know the name total_stu.
But you can use total_stu in ORDER BY, because step 7 run after
step 5.
That is all friend. Remember this logic, you write SQL no error. Happy coding!
🤔 Common Questions from Students
1. Why do we write SELECT first if SQL reads it 5th?
SQL is designed to read like an English sentence ("Select this data from this table"). It focuses on what you want to see, not how the computer gets it. The SQL engine automatically processes it in the correct logical order behind the scenes.
2. What is the difference between WHERE and HAVING?
WHERE filters individual row data before they are grouped
together (Step 2).
HAVING filters the data after it
is grouped by the GROUP BY clause (Step 4). You cannot use
aggregate functions like SUM() or COUNT() in
WHERE.
3. Can I use an alias from SELECT in my ORDER BY clause?
Yes, you can! Because ORDER BY (Step 7) runs after
SELECT (Step 5), the SQL engine already knows the alias
name you created.
4. Does this order apply to MySQL, SQL Server, and Oracle?
Yes! This logical order of operations is standard across almost all relational databases (RDBMS). While database engines make hidden optimizations for speed, they always follow this logical flow to prevent errors.