Can you GROUP BY a column that's not in SELECT?
SQLLevel: IntermediateAggregations & GROUP BY
Can you GROUP BY a column that's not in SELECT?
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Yes. GROUP BY doesn't require you to select the grouped column.
-- Groups by department_id for correctness but selects department_name only
SELECT department_name, SUM(salary)
FROM employees e
JOIN departments d ON e.department_id = d.id
GROUP BY d.department_id, department_name;
Source and licence: SQL Interview Questions — Arda Kocadoru · MIT