Understanding SQL Query Execution Order: From FROM to LIMIT
The article explains the logical execution order of a SQL query—starting with FROM/JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT—using diagrams, code snippets, and practical examples to illustrate each step.
In this article, a senior architect explains the logical execution order of a SQL query, illustrating each step with diagrams and code examples.
SQL Execution Order
The engine processes the query in the following sequence: FROM/JOIN to determine table relationships, WHERE for initial filtering, GROUP BY to group rows, HAVING for group‑level filtering (including aggregate functions), SELECT to compute final columns (adding aggregate results), DISTINCT to remove duplicates, ORDER BY to sort the result set, and finally LIMIT to restrict the number of rows returned.
FROM, JOIN, WHERE
These clauses define the tables involved and the join conditions. from table1 join table2 on table1.id=table2.id Or using a comma list with a WHERE condition:
from table1, table2 where table1.id=table2.idGROUP BY
GROUP BY groups rows according to specified columns without filtering; the article shows an example of grouping by odd/even IDs.
HAVING and WHERE
HAVING can contain aggregate functions, while WHERE cannot. The article notes that using HAVING alone can replace WHERE for a smoother query.
100/2=50, splitting 100 into (10+10+...)/2 = 5+5+... = 50; the filtering condition remains unchanged, so grouping does not affect the result.
SELECT
After grouping, SELECT retrieves columns and aggregates, adding new fields for aggregate results.
select employee.id, distinct name, salary, avg(salary)ORDER BY
ORDER BY sorts the final result set, for example by id.
LIMIT
LIMIT is applied last to truncate the result set after sorting. The article warns that applying LIMIT before ORDER BY can yield incorrect rows.
The article also contains promotional messages encouraging readers to follow the public account, join a discussion group, and access interview‑question collections.
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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
