✏️ Explanatory Question

What is the difference between DISTINCT and GROUP BY?

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

22

What is the difference between DISTINCT and GROUP BY?

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: Simply removes duplicate rows from the result set. It is used purely for uniqueness, not for calculations.
  • GROUP BY: Groups rows so you can run aggregate functions (COUNT, SUM, AVG) on each group. Removing duplicates is just a side effect.
Rule of thumb: If you just want unique values, use DISTINCT. If you want unique values plus aggregated data (like a count per group), use GROUP BY.

Side-by-Side Comparison

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

Both Give the Same Result Here

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;

Where GROUP BY Wins — Aggregation

-- 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)
Interviewer tip: The one-liner they want — "DISTINCT only removes duplicate rows, while GROUP BY groups rows to perform aggregate calculations. Use DISTINCT for uniqueness and GROUP BY when you need per-group summaries."