Sub topic 10
Removing Duplicate Rows with DISTINCT
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and sort with ORDER BY. It covers what DISTINCT compares, how it treats NULL, how it interacts with sorting and row limiting, and when it is the wrong tool.
What DISTINCT does
A query returns one row for every source row that passes the WHERE filter, even when several output rows are identical. DISTINCT tells Oracle to keep only one copy of each identical output row.
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id;Without DISTINCT, this query returns one row per employee. With it, you get one row per department value that appears in the table.
ALL is the opposite keyword and is the default. SELECT ALL department_id ... behaves the same as SELECT department_id .... Oracle also accepts UNIQUE as a synonym for DISTINCT. UNIQUE is an Oracle extension and is not part of standard SQL, so prefer DISTINCT in code that may move to another database.
Setting up a small test table
The HR sample schema works, but a tiny table makes the duplicates easy to see. Run this script to create one.
CREATE TABLE page_visits (
visitor VARCHAR2(20),
page VARCHAR2(20),
country VARCHAR2(20)
);
INSERT INTO page_visits VALUES ('ana', 'home', 'PT');
INSERT INTO page_visits VALUES ('ana', 'home', 'PT');
INSERT INTO page_visits VALUES ('ana', 'pricing', 'PT');
INSERT INTO page_visits VALUES ('ben', 'home', NULL);
INSERT INTO page_visits VALUES ('cy', 'home', NULL);
INSERT INTO page_visits VALUES ('cy', 'docs', 'US');
COMMIT;The table has six rows. The first two are exact duplicates.
DISTINCT applies to the whole row
DISTINCT is not a function of one column. It applies to the entire select list, and two rows are duplicates only when every selected value matches.
SELECT DISTINCT visitor FROM page_visits;This returns three rows: ana, ben and cy.
SELECT DISTINCT visitor, page FROM page_visits;This returns five rows. The pair ana / home appears twice in the table and once in the result. Adding a column can only keep the row count the same or increase it, because each added column gives rows more ways to differ.
Parentheses do not change this. The query below looks like it applies DISTINCT to visitor only, but it behaves exactly like SELECT DISTINCT visitor, page.
SELECT DISTINCT(visitor), page FROM page_visits;You also cannot apply DISTINCT to just one column in the middle of a list. This fails with ORA-00936: missing expression:
SELECT visitor, DISTINCT page FROM page_visits;DISTINCT must come directly after SELECT, and it covers everything that follows.
How DISTINCT treats NULL
Elsewhere in SQL, NULL = NULL is not true, because comparing an unknown value to another unknown value gives an unknown result. DISTINCT is an exception. It treats two NULL values as the same value, so they collapse into one row.
SELECT DISTINCT country FROM page_visits;The result has three rows: PT, US and one row containing NULL. The table holds two NULL countries, but only one survives.
The same rule applies to multiple columns. (ben, NULL) and (cy, NULL) differ because of the visitor, but two rows of ('x', NULL) would collapse into one.
SELECT DISTINCT visitor, country FROM page_visits;This returns four rows: (ana, PT), (ben, NULL), (cy, NULL) and (cy, US).
Remember that Oracle treats an empty string as NULL in VARCHAR2 columns, so empty strings and NULL values also collapse together.
Comparison is also case-sensitive by default. 'PT' and 'pt' are different values, and DISTINCT keeps both unless you normalize them in the query, for example with UPPER(country).
DISTINCT with expressions
You can use DISTINCT on any expression in the select list. Oracle evaluates the expression for each row and removes duplicates among the results.
SELECT DISTINCT UPPER(country) AS country_code
FROM page_visits
WHERE country IS NOT NULL;You can also test it against DUAL. This query returns one row even though the select list contains three rows' worth of identical values:
SELECT DISTINCT 1 AS one FROM dual;COUNT(DISTINCT ...)
DISTINCT has a second use inside aggregate functions. COUNT(DISTINCT expr) counts the different non-null values of the expression.
SELECT COUNT(*) AS all_rows,
COUNT(country) AS non_null_countries,
COUNT(DISTINCT country) AS distinct_countries
FROM page_visits;For the test table the three values are 6, 4 and 2. COUNT(*) counts every row. COUNT(country) skips the two NULL rows. COUNT(DISTINCT country) skips NULL and also counts PT once.
This differs from SELECT DISTINCT country, which returns a row for NULL. If you count the rows of that query, you get 3, not 2.
Interaction with ORDER BY
Oracle removes duplicates before it sorts. Because of that, ORDER BY in a DISTINCT query can only use expressions that appear in the select list. Sorting by a column that is not selected makes no sense, since each output row may stand for many source rows with different values of that column.
SELECT DISTINCT department_id
FROM employees
ORDER BY salary;This fails with ORA-01791: not a SELECTED expression. To sort the distinct values, order by something you selected:
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id DESC;In ascending order, Oracle places NULL last. In descending order, it places NULL first. Add NULLS FIRST or NULLS LAST if you want to control this.
Interaction with FETCH FIRST
FETCH FIRST is applied after DISTINCT and after ORDER BY. It therefore limits the number of distinct rows, not source rows.
SELECT DISTINCT job_id
FROM employees
ORDER BY job_id
FETCH FIRST 3 ROWS ONLY;This returns the first three job IDs in sorted order, each listed once. The next diagram shows where DISTINCT sits in the logical order.
Because DISTINCT runs after the select list is computed, it compares the computed output values. That is why aliases and expressions work, and why unselected columns cannot take part.
What DISTINCT costs
To find duplicates, Oracle must either sort the rows or build a hash table of the rows it has seen. In an execution plan you will see the operation HASH UNIQUE or SORT UNIQUE. On a large table with many columns in the select list, this needs memory and may spill to temporary disk space. Choose the fewest columns that answer your question, because every extra column makes comparison more expensive and the result less likely to shrink.
Restrictions
DISTINCT cannot compare large object columns. If the select list contains a CLOB or BLOB, Oracle raises an error such as ORA-00932: inconsistent datatypes. Select a different column, or apply a function that returns a comparable value.
When not to use DISTINCT
The most common misuse is hiding duplicates caused by a join. Suppose you want the departments that have at least one employee:
SELECT DISTINCT d.department_name
FROM departments d
JOIN employees e ON e.department_id = d.department_id;The query returns the right answer, but it first builds one row per employee and then throws most of them away. A semi-join says what you mean and avoids creating the extra rows:
SELECT d.department_name
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
);If you add DISTINCT only because a query returns unexpected duplicates, find out why first. A missing join condition or a one-to-many relationship is often the cause, and DISTINCT will mask a bug in the logic.
The table below compares the tools that remove or collapse duplicates.
| Tool | Use it when | Note |
|---|---|---|
| `DISTINCT` | You need the unique combinations of the selected columns | Applies to the whole select list |
| `COUNT(DISTINCT x)` | You need the number of different non-null values | Skips `NULL` |
| `GROUP BY` | You also need aggregates per group, such as counts or sums | Gives the same rows as `DISTINCT` when no aggregates are used |
| `EXISTS` | You test whether related rows exist | Avoids join duplicates |
Finally, DISTINCT is not needed when the selected columns already include a primary key or a unique column, because no two rows can be identical. In that case it only adds sorting or hashing work.
Common errors
ORA-01791: not a SELECTED expression: theORDER BYitem is not in theDISTINCTselect list.ORA-00936: missing expression:DISTINCTwas placed after the first select item instead of directly afterSELECT.ORA-00932: inconsistent datatypes: the select list includes a LOB column.- Unexpected extra rows: values differ only by case or trailing spaces, so
DISTINCTtreats them as different. - A count that is one lower than expected:
COUNT(DISTINCT col)skipsNULL.
Exercise
Using the page_visits table, write a query that returns the distinct (visitor, country) pairs, sorted by visitor and then country with NULL countries listed first. How many rows does it return, and why does the visitor cy appear twice?
Show answer
SELECT DISTINCT visitor, country FROM page_visits ORDER BY visitor, country NULLS FIRST; It returns 4 rows: (ana, PT), (ben, NULL), (cy, NULL) and (cy, US). DISTINCT compares the whole row, so the two cy rows differ because their country values differ (NULL and US). The two identical (ana, PT) source rows collapse into one.
Exercise
What do COUNT(*), COUNT(country) and COUNT(DISTINCT country) return for page_visits, and why does SELECT DISTINCT country return 3 rows while COUNT(DISTINCT country) returns 2?
Show answer
They return 6, 4 and 2. COUNT(*) counts all rows, COUNT(country) skips the two NULL rows, and COUNT(DISTINCT country) counts PT and US once each. SELECT DISTINCT country returns a row for NULL as well, because DISTINCT treats NULLs as equal and keeps one of them, so it returns PT, US and NULL.
Exercise
Why does SELECT DISTINCT department_id FROM employees ORDER BY salary fail, and how would you fix it if you want the departments in order?
Show answer
DISTINCT removes duplicates before sorting, so each output row can stand for many employees with different salaries, and salary is not a selected expression. Oracle raises ORA-01791. Order by a selected expression instead, for example ORDER BY department_id.