In what logical order does SQL evaluate a query?
Options
- SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
- FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT (Correct option)
- ORDER BY, SELECT, FROM, WHERE, GROUP BY, HAVING
- WHERE, SELECT, FROM, HAVING, GROUP BY, ORDER BY
Answer
FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT
Why
You write SELECT first, but the database processes it later:
FROM/JOIN: choose and combine tables.WHERE: filter rows.GROUP BY: form groups.HAVING: filter groups.SELECT: compute columns and aliases.ORDER BY: sort.LIMIT: cut.
This explains why you cannot use a SELECT alias inside WHERE, but you can in ORDER BY.
Remember
FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.