SQLIntermediate#queries

What is the logical order of execution of a SELECT query?

FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. This is why a SELECT alias cannot be used in WHERE but can be used in ORDER BY.

Example
SELECT dept_id, COUNT(*) AS c
FROM employees
WHERE active = 1
GROUP BY dept_id
HAVING COUNT(*) > 2
ORDER BY c DESC
LIMIT 5;

Related Questions

1
SQLBeginner#keys

Primary key vs unique key vs foreign key?

Open
2
SQLBeginner#keys

What is a composite key?

Open
3
SQLIntermediate#keys

What is a candidate key and a super key?

Open