Sub topic 4
Removing duplicate rows with DISTINCT
This chapter assumes you can write a basic SELECT ... FROM query, choose columns, and read a table as rows and columns. You should also have a SQL client connected to a database such as PostgreSQL, MySQL, or SQLite.
Why duplicates appear
A table stores one row per record, but a query result is not a table. When you select only some columns, different rows can produce identical output. The employees table may hold 200 rows, yet only a handful of distinct departments.
SELECT department
FROM employees;If 40 employees work in Sales, the word Sales appears 40 times. SQL does not remove these repeats on its own. A result set is a multiset: it can contain the same row more than once.
The DISTINCT keyword removes duplicate rows from the result.
SELECT DISTINCT department
FROM employees;This returns each department value once, even if many employees share it.
What DISTINCT compares
DISTINCT goes right after SELECT. It compares the whole row of selected values, not each column on its own. Two rows are duplicates only when every selected column matches.
SELECT DISTINCT department, job_title
FROM employees;This returns one row for each unique pair of department and job_title. Suppose the table holds these rows:
| department | job_title |
|---|---|
| Sales | Manager |
| Sales | Manager |
| Sales | Analyst |
| Marketing | Manager |
The query returns three rows. Sales / Manager collapses to one row, but Sales / Analyst and Marketing / Manager remain, because each differs from the others in at least one column.
A common mistake: expecting DISTINCT on one column
DISTINCT is not a function applied to the column next to it. This query does not mean "distinct department, plus the first name":
SELECT DISTINCT department, first_name
FROM employees;Because first_name is almost always different, nearly every row survives. The query returns about as many rows as the table has. If you wanted one row per department, you must select only department. If you also need a per-department detail, you need grouping and aggregate functions, which later chapters cover.
Parentheses do not change this behavior:
SELECT DISTINCT(department), first_name
FROM employees;Here (department) is just a parenthesized column. The query still compares both columns. Avoid this form because it suggests a scope that does not exist.
Using DISTINCT with expressions
DISTINCT works on computed values as well as plain columns. It compares the final output of each selected expression.
SELECT DISTINCT salary * 12 AS annual_salary
FROM employees;This lists each different annual salary once. Two employees with a monthly salary of 4000 both produce 48000, so that value appears one time.
DISTINCT and NULL
For DISTINCT, two NULL values count as the same. This differs from WHERE, where NULL = NULL is unknown rather than true. Suppose several employees have no manager_id:
SELECT DISTINCT manager_id
FROM employees;The result contains NULL once, alongside each distinct manager ID. The SQL standard defines this treatment: for duplicate removal, values that are both NULL are not distinct from each other.
Combining DISTINCT with WHERE and ORDER BY
DISTINCT fits into the query as you would expect. WHERE filters rows first. DISTINCT then removes duplicates from what is left. ORDER BY sorts the final result.
SELECT DISTINCT department
FROM employees
WHERE salary >= 50000
ORDER BY department;This returns each department that has at least one employee earning 50,000 or more, in alphabetical order. A department with only lower-paid employees does not appear, because WHERE removed those rows before DISTINCT ran.
ORDER BY has a restriction when DISTINCT is present. In most databases, every column in ORDER BY must also appear in the select list. This query fails in PostgreSQL:
SELECT DISTINCT department
FROM employees
ORDER BY salary;PostgreSQL reports that for SELECT DISTINCT, ORDER BY expressions must appear in the select list. The reason is that each department row stands for many employees, each with a different salary. The database has no single salary to sort that row by. Some databases, including MySQL in certain modes and SQLite, accept such queries, but the order they produce is not well defined. Do not rely on it.
Counting distinct values
You will often want to know how many distinct values exist, not the values themselves. The aggregate function COUNT accepts DISTINCT:
SELECT COUNT(DISTINCT department) AS department_count
FROM employees;This returns a single number. Here DISTINCT is inside the parentheses, so it applies to the one expression being counted. COUNT(DISTINCT ...) ignores NULL values, so rows with a NULL department do not add to the count. Aggregates are covered properly in a later tutorial. For now, remember that DISTINCT can appear in two places with the same idea: remove repeats before the next step.
Performance and design considerations
DISTINCT is not free. To find duplicates, the database must compare rows. It usually does this by sorting the result or by building a hash table, which takes time and memory in proportion to the number of rows. On a large table, SELECT DISTINCT over many columns can be slow. Three habits help:
- Select only the columns you need, so each row is smaller.
- Filter with
WHEREfirst, so fewer rows reach the duplicate check. - Check whether an index on the column can let the database find distinct values cheaply. Many engines can scan an index for a single column.
Do not use DISTINCT to hide a problem. A frequent pattern is a query that returns unexpected duplicates, and a developer adds DISTINCT until the repeats disappear. When the duplicates come from a mistake, such as a join that multiplies rows, DISTINCT masks the bug and costs performance. Ask first why the repeats appear. Joins come later in this tutorial series, but keep the rule in mind.
Dialect notes
SELECT DISTINCT is standard SQL and works in PostgreSQL, MySQL, SQLite, SQL Server, and Oracle. The opposite keyword is ALL, which keeps duplicates. It is the default, so SELECT ALL department FROM employees behaves the same as leaving it out. PostgreSQL also offers DISTINCT ON (column), which keeps the first row for each value of a column. It is a PostgreSQL extension and does not exist in standard SQL or in MySQL.
SELECT DISTINCT ON (department) department, first_name, salary
FROM employees
ORDER BY department, salary DESC;In PostgreSQL, this returns one row per department: the highest-paid employee in each. The ORDER BY decides which row counts as first, so its leading columns must match the DISTINCT ON expression. Do not use this form if your code must run on other databases.
Summary
DISTINCTremoves rows that are identical across all selected columns.- It applies to the whole select list, whatever parentheses you add.
- Two
NULLvalues count as duplicates underDISTINCT. - It runs after
WHEREand beforeORDER BY, andORDER BYcolumns generally must appear in the select list. - It costs sorting or hashing work, and it should not be used to hide unexplained duplicates.
Exercise
A table named orders has the columns customerid, product and quantity. The query SELECT DISTINCT customerid, product FROM orders; returns 120 rows. The query SELECT DISTINCT customer_id FROM orders; returns 45 rows. What do these numbers tell you, and why can the first result never be smaller than the second?
Show answer
The 45 means there are 45 different customers who placed orders. The 120 means there are 120 different customer and product pairs. Each customer appears in at least one pair, and a customer who bought several products appears in several pairs. So the pair count is always at least the customer count. Here the average customer ordered about 2.7 different products.
Exercise
A query SELECT DISTINCT department FROM employees ORDER BY salary; fails in PostgreSQL. Explain why, and rewrite it so that it lists each department with the highest salary in that department, sorted from the highest salary to the lowest. You may use MAX, which returns the largest value in a group.
Show answer
Each output row represents many employees with different salaries, so there is no single salary to sort by, and PostgreSQL requires ORDER BY expressions to appear in the select list. A working rewrite is: SELECT department, MAX(salary) AS topsalary FROM employees GROUP BY department ORDER BY topsalary DESC; This uses grouping instead of DISTINCT, which is the correct tool when you need a per-group value.