Interview Q&A / SQL & DBMS

BeginnerQuick answer1 min readUpdated 3 Oct 2026

In what order does SQL actually execute the clauses of a SELECT query?

SHORT ANSWER

The logical order is FROM and JOINs, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, then LIMIT. It differs from the written order, which is why a SELECT alias works in ORDER BY but not in WHERE.

Explain it simply

Think of a canteen kitchen. First the cook gathers the ingredients (FROM), throws out the bad ones (WHERE), groups what is left into plates (GROUP BY), removes small plates (HAVING), then writes the menu names on them (SELECT), and finally arranges them in order (ORDER BY) and serves only a few (LIMIT).

You write SELECT first, but the database reads it nearly last.

Example

sql
SELECT dept, COUNT(*) AS total
FROM employees
WHERE salary > 30000
GROUP BY dept
HAVING COUNT(*) > 2
ORDER BY total DESC
LIMIT 3;

Logical order here:

  1. FROM employees loads the rows.
  2. WHERE keeps salaries above 30000.
  3. GROUP BY makes one group per department.
  4. HAVING drops groups with 2 or fewer rows.
  5. SELECT computes dept and the alias total.
  6. ORDER BY total can use the alias because SELECT already ran.
  7. LIMIT cuts the result to 3 rows.

What to say in the interview

"A query is written SELECT first but evaluated FROM first: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. That is why WHERE cannot see a SELECT alias or an aggregate, while ORDER BY can. The optimizer may physically reorder work, but the result must match this logical order."

Common mistakes

  • Using a SELECT alias in WHERE. Repeat the expression or wrap the query in a subquery.
  • Filtering on COUNT(*) in WHERE instead of HAVING.

#sql#select#query-processing

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.