✏️ Explanatory Question
Level: Basic to Intermediate — Tests whether you understand sorting vs aggregating results.
Both clauses organize query results, but they serve completely different purposes:
ASC) or descending (DESC) order. It does not combine rows.COUNT(), SUM(), AVG().| Feature | ORDER BY | GROUP BY |
|---|---|---|
| Purpose | Sorts rows | Groups rows |
| Row count | Unchanged | Reduced (one per group) |
| Aggregate functions | Not required | Commonly used |
| Execution order | Runs last (before LIMIT) | Runs before ORDER BY |
| Directions | ASC / DESC | N/A |
-- ORDER BY: just sort all rows by salary (highest first)
SELECT name, salary
FROM employees
ORDER BY salary DESC;
-- GROUP BY: one summary row per department
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id;
-- Both together: group first, then sort the groups
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id -- collapse into one row per dept
ORDER BY avg_salary DESC; -- then sort those group results