Senior
In what sequence is this SQL query executed (query plan)?.
sobes.tech AI
Answer from AI
The sequence of executing an SQL query (logical plan) is usually as follows:
- FROM — selecting tables and performing joins.
- WHERE — filtering rows based on a condition.
- GROUP BY — grouping data.
- HAVING — filtering grouped data.
- SELECT — selecting necessary columns and calculating expressions.
- DISTINCT — removing duplicates.
- ORDER BY — sorting the result.
- LIMIT / OFFSET — limiting the number of returned rows.
This is a logical order, which may differ from the physical plan; the optimizer can change the order of operations to improve performance.
Example:
SELECT department, COUNT(*)
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 5
ORDER BY department;
Here, employees with a salary > 50000 are selected first, then they are grouped by department, groups with more than 5 employees are filtered, and finally, the result is sorted by department.