Which of the following is the correct sequence in a SELECT query?
2023
Which of the following is the correct sequence in a SELECT query?
Answer: A. SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY — CONCEPT: A SQL SELECT statement has two distinct clause orders — the WRITTEN (syntactic) order in which clauses must be typed, and the LOGICAL (execution)…
- A.
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
- B.
SELECT, WHERE, FROM, GROUP BY, HAVING, ORDER BY
- C.
SELECT, FROM, WHERE, HAVING, GROUP BY, ORDER BY
- D.
SELECT, FROM, WHERE, GROUP BY, ORDER BY, HAVING
Attempted by 2044 students.
Show answer & explanation
Correct answer: A
CONCEPT: A SQL SELECT statement has two distinct clause orders — the WRITTEN (syntactic) order in which clauses must be typed, and the LOGICAL (execution) order in which the database engine actually evaluates them. The syntactic order is fixed: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.
APPLICATION — why this is the written order:
SELECT names the columns/expressions to project — written first, though logically evaluated later.
FROM identifies the source table(s) that the rest of the clauses operate on.
WHERE filters individual rows against a condition, before any grouping happens — it needs the FROM tables already named.
GROUP BY collects the filtered rows into groups based on the specified columns.
HAVING filters groups — when GROUP BY is present, it filters the groups GROUP BY has formed, so whenever both clauses appear, HAVING is written after GROUP BY.
ORDER BY sorts the final, already filtered-and-grouped result set — it must be written last since it operates on the finished output.
CROSS-CHECK — why the other sequences break a specific dependency:
Writing WHERE before FROM breaks the rule that WHERE needs the FROM tables already named.
Writing HAVING before GROUP BY breaks the rule that, whenever both clauses appear, HAVING must follow GROUP BY since it filters the groups GROUP BY has already formed.
Writing HAVING after ORDER BY breaks the rule that ORDER BY sorts the finished, already grouped-and-filtered result, so HAVING must complete before ORDER BY.
RESULT: Hence SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY is the standard written (syntactic) order of a SELECT query.
Note: this question asks for the WRITTEN order of the clauses as typed, not the LOGICAL order in which the engine evaluates them (FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY) — that execution order is a separate, equally standard concept, but it does not match any of the four sequences offered here since none of them starts with FROM.
A video solution is available for this question — log in and enroll to watch it.