✏️ Explanatory Question
Level: Intermediate — A subtle question, since both can remove duplicates but serve different goals.
Both DISTINCT and GROUP BY can eliminate duplicate values, but their intent is different:
DISTINCT. If you want unique values plus aggregated data (like a count per group), use GROUP BY.
| Feature | DISTINCT | GROUP BY |
|---|---|---|
| Main purpose | Remove duplicate rows | Group rows for aggregation |
| Aggregate functions | Not used | Commonly used |
| Allows HAVING? | No | Yes |
| Output | Unique rows | One row per group |
| Sorting side effect | None guaranteed | May group/order internally |
For a simple unique-value list, these two queries return identical output — but DISTINCT is clearer for that intent:
-- Using DISTINCT
SELECT DISTINCT dept_id FROM employees;
-- Using GROUP BY (same result)
SELECT dept_id FROM employees GROUP BY dept_id;
-- DISTINCT can only list unique departments
SELECT DISTINCT dept_id FROM employees;
-- GROUP BY can also COUNT employees per department
SELECT dept_id, COUNT(*) AS total_employees
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 3; -- and filter groups (DISTINCT can't do this)