Mastering SQL: The 6-Step Process Behind Every SELECT Query
This article walks through the complete lifecycle of a SQL SELECT statement—using simple Citizen and City tables—to illustrate the six processing stages (FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY/LIMIT), showing how each clause transforms the data step by step.
Use a simple example to explain the execution order of a SQL query.
Introduction
This article step‑by‑step explains how a relational database processes a SELECT statement.
Two sample tables are used: Citizen (citizen name and city_id) and City (city name and id).
The query aims to list the names of cities other than “San Bruno” that have at least two citizens, ordered alphabetically.
SELECT city.city_name AS City
FROM citizen
JOIN city ON citizen.city_id = city.city_id
WHERE city.city_name != 'San Bruno'
GROUP BY city.city_name
HAVING COUNT(*) >= 2
ORDER BY city.city_name ASC
LIMIT 2;Query processing steps
From / Join : Combine the two tables according to the ON condition.
Where : Filter rows that do not satisfy the condition (city name not “San Bruno”).
Group by : Group the remaining rows by city name.
Having : Keep only groups whose count is ≥ 2.
Select : Choose the columns to return (city_name as “City”).
Order by / Limit : Sort the result alphabetically and limit the output to two rows.
Step 1: From / Join
FROM citizen
JOIN cityThe FROM and JOIN clauses create the initial record set by pairing rows from the two tables.
ON citizen.city_id = city.city_idStep 2: Where
WHERE city.city_name != 'San Bruno'The WHERE clause removes rows that do not meet the condition.
Step 3: Group by
GROUP BY city.city_nameRows with the same city_name are grouped together.
Step 4: Having
HAVING COUNT(*) >= 2The HAVING clause filters groups, keeping only those with at least two citizens.
Step 5: Select
The SELECT clause outputs the city_name column with the alias “City”.
Step 6: Order by & Limit
The final step orders the result alphabetically and limits the number of rows to two.
Conclusion
The six stages—From/Join, Where, Group By, Having, Select, Order By/Limit—represent the full execution pipeline of a SQL SELECT statement.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
