DISTINCT vs GROUP BY
Both can remove duplicate results, but their main purposes are different.
| Feature | DISTINCT |
GROUP BY |
|---|---|---|
| Main purpose | Removes duplicate rows | Groups rows for calculations |
| Aggregate functions | Not its main purpose | Commonly used with aggregates |
| Result | Unique combinations of selected columns | One result per group |
| Syntax | Simpler for removing duplicates | Used for summarization |
| Common functions | — | COUNT, SUM, AVG, MIN, MAX |
DISTINCT example
Remove duplicate departments:
SELECT DISTINCT Department
FROM Employees;
Result:
IT
HR
Finance
For multiple columns, it returns unique combinations:
SELECT DISTINCT Department, JobTitle
FROM Employees;
GROUP BY example
Group employees by department and calculate the employee count:
SELECT Department, COUNT(*) AS EmployeeCount
FROM Employees
GROUP BY Department;
Example result:
| Department | EmployeeCount |
|---|---|
| IT | 5 |
| HR | 3 |
| Finance | 4 |
When both return the same result
These queries can produce the same output:
SELECT DISTINCT Department
FROM Employees;
SELECT Department
FROM Employees
GROUP BY Department;
However, use DISTINCT when you only need unique values.
Use GROUP BY when you need aggregate calculations:
SELECT Department,
COUNT(*) AS EmployeeCount,
AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;
Important rule
When using GROUP BY, every selected column must either:
-
Be included in
GROUP BY, or -
Be used inside an aggregate function.
SELECT Department, COUNT(*)
FROM Employees
GROUP BY Department;
Interview answer
DISTINCTremoves duplicate rows from the result, whileGROUP BYgroups rows—usually to perform aggregate calculations such asCOUNT,SUM, andAVG.