Skip to main content

DISTINCT

Editorial

Introduction

DISTINCT removes repeated rows from a result: each different row comes back once.

Here you will:

  • see what DISTINCT keeps, with one column and with several
  • count different values with COUNT(DISTINCT column)
  • compare DISTINCT with GROUP BY, and use it with ORDER BY and NULL
  • see what it costs on the site's own engine

What is DISTINCT?

DISTINCT goes right after SELECT. It compares whole result rows and keeps one row for each different one.

Without DISTINCT

SELECT customer_state
FROM olist_customers_dataset
LIMIT 10;

The site shows AC ten times. The query asks only for customer_state, and the table has an index on that column which holds every customer's state in order, A to Z. SQLite reads the index instead of the table, so the first ten rows it meets are customers in AC (it has 81). With no ORDER BY, which rows come first is SQLite's choice.

With DISTINCT

SELECT DISTINCT customer_state
FROM olist_customers_dataset;

Each of the 27 states comes back once. They come A to Z because SQLite read the same index again, not because DISTINCT sorts: on rows read in another order, it keeps each value where it first meets it, as the figure shows with eight customers.

How DISTINCT removes duplicates. One row comes back for each different value of the selected columns. Left, WITHOUT DISTINCT: the customer_state column of eight customers, one for each of eight cities, in the order they are read: SP, SP, RJ, RJ, MG, RS, SP, BA; 8 rows: 3 are copies, drawn dashed and crossed (rows 2, 4, 7). A funnel narrows from it through a card reading SELECT DISTINCT customer_state, with "duplicates filtered out" below, to the right, WITH DISTINCT: SP, RJ, MG, RS, BA, each checked; 5 rows: each state once, in the order first read. Top right, DISTINCT customer_state, customer_city on the same rows: the three SP rows stay three rows (SP sao paulo; SP campinas; SP santos): every pair differs: 8 rows in, 8 out. and 5 more pairs, one each. Below it: No order is promised. The same eight, read through the state index: BA, MG, RJ, RS, SP, A to Z. A note at the bottom: DISTINCT compares ALL the selected columns: with several, it keeps each different COMBINATION once.

Basic DISTINCT Syntax

Syntax

SELECT DISTINCT column1, column2
FROM table_name;

One Column, in Order

-- List every state once, A to Z
SELECT DISTINCT customer_state
FROM olist_customers_dataset
ORDER BY customer_state;

With ORDER BY the order is part of the query, whatever SQLite reads first.

Every Order Status

-- List every order status once
SELECT DISTINCT order_status
FROM olist_orders_dataset;

8 statuses, A to Z: SQLite read them from the index on order_status. Read in the table's own order they would start with delivered, the status of its first order.

DISTINCT with Multiple Columns

With several columns, DISTINCT keeps each different combination of their values once.

Example: State and City Pairs

SELECT DISTINCT customer_state, customer_city
FROM olist_customers_dataset
ORDER BY customer_state, customer_city
LIMIT 20;

AC has 8 cities before the first pair of AL.

How Many Pairs?

SELECT COUNT(*) AS state_city_pairs
FROM (
    SELECT DISTINCT customer_state, customer_city
    FROM olist_customers_dataset
);

4,310 pairs, though there are only 4,119 different city names: 163 city names stand in two or more states, and each of those states makes its own pair.

Key Point

The whole pair is compared. ('SP', 'sao paulo'), ('SP', 'campinas') and ('SP', 'santos') are three rows, though their state is the same, because their cities differ.

Watch DISTINCT Keep One Row a Value

Pick a table and the columns after SELECT DISTINCT, then read the rows one at a time or all at once. Each row goes to the box of its value. The first row of a value is the one DISTINCT keeps; each later copy lands in the same box and is dropped. Once every row is in, the boxes are the result.

The same customers, products and payments as the GROUP BY and HAVING steppers. Read the rows one at a time: the first row of a value is kept, every later copy is dropped, as SQLite does it.

DISTINCT Applies to the Whole Row

DISTINCT is not a function of the first column. It applies to every column in the SELECT list together.

A Common Misreading

SELECT DISTINCT customer_state, customer_city does not mean "each state once, and its city too". It means each different (state, city) pair once, which is why the pairs above repeat AC.

DISTINCT on Every Column

SELECT
    (SELECT COUNT(*) FROM olist_customers_dataset) AS all_rows,
    (SELECT COUNT(*)
     FROM (SELECT DISTINCT * FROM olist_customers_dataset)) AS distinct_rows;

DISTINCT * kept all 99,441 rows: every row has its own customer_id, so no two rows are the same in every column. On a table like this one it only adds work (see Performance below).

COUNT(DISTINCT column)

COUNT(DISTINCT column) counts the different values of a column, where COUNT(column) counts every value that is not NULL. SQLite's documentation: "In any aggregate function that takes a single argument, that argument can be preceded by the keyword DISTINCT. In such cases, duplicate elements are filtered before being passed into the aggregate function."

Examples

SELECT COUNT(DISTINCT customer_state) AS unique_states
FROM olist_customers_dataset;
SELECT COUNT(DISTINCT customer_city) AS unique_cities
FROM olist_customers_dataset;

COUNT and COUNT(DISTINCT) Side by Side

SELECT
    COUNT(*) AS total_customers,
    COUNT(DISTINCT customer_state) AS unique_states,
    COUNT(DISTINCT customer_city) AS unique_cities
FROM olist_customers_dataset;

People, Not Ids

Each order in this dataset has a customer_id of its own; the person behind it is customer_unique_id:

SELECT
    COUNT(*) AS customer_ids,
    COUNT(DISTINCT customer_unique_id) AS people
FROM olist_customers_dataset;

99,441 customer ids belong to 96,096 people.

COUNT(DISTINCT) with GROUP BY

-- Cities per state
SELECT
    customer_state,
    COUNT(*) AS total_customers,
    COUNT(DISTINCT customer_city) AS unique_cities
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY unique_cities DESC, customer_state;

MG has the most cities, 745, though SP has 41,746 customers to its 11,635. The second sort key, the state, fixes the order of states with the same number of cities.

DISTINCT vs GROUP BY

Both can return each value once.

The Same Result

The GROUP BY form of the sorted states above:

SELECT customer_state
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_state;

The same 27 rows as SELECT DISTINCT customer_state ... ORDER BY customer_state.

When to Use Each

Use CaseUse
Each different value or combinationDISTINCT
Counts, sums or other aggregates per valueGROUP BY
Keeping only some groups (HAVING)GROUP BY

Aggregates Need GROUP BY

SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC;

DISTINCT cannot do this. Put COUNT(*) beside it with no GROUP BY, and the whole table becomes one group:

SELECT DISTINCT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset;

The site shows one row: AC beside 99,441, the count of every customer, with the state of one arbitrary row. PostgreSQL refuses it: its error says that customer_state must appear in the GROUP BY clause or be used in an aggregate function.

Which Is Faster?

Measured on the site's engine (SQLite 3.54.1 on the course's file, the median of six timed runs): on the indexed state both read the index, 4.47 ms for DISTINCT and 5.36 ms for GROUP BY. On the city, which has no index, DISTINCT keeps a list of the values it has seen (32.65 ms), while GROUP BY first sorts all 99,441 cities (51.91 ms). For each value once, DISTINCT was the faster here.

DISTINCT with ORDER BY

ORDER BY sorts the rows DISTINCT keeps.

Example

SELECT DISTINCT payment_type
FROM olist_order_payments_dataset
ORDER BY payment_type;

Ordering by a Column You Did Not Select

SELECT DISTINCT customer_state
FROM olist_customers_dataset
ORDER BY customer_city;

SQLite runs it, and the order looks random: GO comes first. Each state stands for many customers and many cities. SQLite kept the first row it read for each state and sorted the states by those rows' cities: the first GO customer in the table is from aparecida de goiania, which comes before every other state's first city. PostgreSQL refuses it: for SELECT DISTINCT, ORDER BY expressions must appear in select list.

The Fix: Select What You Order By

SELECT DISTINCT customer_state, customer_city
FROM olist_customers_dataset
ORDER BY customer_city, customer_state
LIMIT 10;

Now the pairs themselves are sorted by city, and each pair is a different row.

DISTINCT with NULL Values

For DISTINCT, two NULLs are the same value, so NULL comes back once. SQLite's documentation: "For the purposes of detecting duplicate rows, values are compared using the IS DISTINCT FROM operator. Thus two NULL values are considered to be equal."

Example

SELECT DISTINCT product_category_name
FROM olist_products_dataset
ORDER BY product_category_name;

NULL comes first: SQLite sorts it before every other value.

COUNT(DISTINCT) and NULL

SELECT
    COUNT(*) AS total_products,
    COUNT(product_category_name) AS with_category,
    COUNT(DISTINCT product_category_name) AS unique_categories
FROM olist_products_dataset;

610 products have no category, so COUNT(product_category_name) is 32,341. COUNT(DISTINCT ...) leaves NULL out too: 73 categories. Yet DISTINCT returns NULL as a row of its own:

SELECT COUNT(*) AS distinct_rows
FROM (
    SELECT DISTINCT product_category_name
    FROM olist_products_dataset
);

74 rows: the 73 names and NULL. PostgreSQL does the same, and sorts NULL last.

Practice

Each exercise runs on the course's tables: press Run to see its rows.

Exercise 1: Basic DISTINCT

List every order status once:

-- List every order status once

SELECT DISTINCT order_status
FROM olist_orders_dataset
ORDER BY order_status;

8 statuses, from approved to unavailable.

Exercise 2: DISTINCT with Multiple Columns

List the first 20 state and city pairs:

-- Every state and city pair once

SELECT DISTINCT customer_state, customer_city
FROM olist_customers_dataset
ORDER BY customer_state, customer_city
LIMIT 20;

AC's 8 cities, then AL's.

Exercise 3: COUNT(DISTINCT)

Count the orders, products and sellers behind the order items:

-- Orders, products and sellers behind the order items

SELECT
    COUNT(*) AS total_order_items,
    COUNT(DISTINCT order_id) AS unique_orders,
    COUNT(DISTINCT product_id) AS unique_products,
    COUNT(DISTINCT seller_id) AS unique_sellers
FROM olist_order_items_dataset;

112,650 items come from 98,666 orders, 32,951 products and 3,095 sellers.

Exercise 4: DISTINCT with GROUP BY

Find the ten states with the most different cities:

-- Cities per state, the ten with most

SELECT
    customer_state,
    COUNT(DISTINCT customer_city) AS unique_cities,
    COUNT(*) AS total_customers
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY unique_cities DESC, customer_state
LIMIT 10;

MG first with 745 cities, RJ tenth.

Exercise 5: Find Unique Payment Types per Order

Find the orders paid with more than one payment type:

-- Orders paid with more than one payment type

SELECT
    order_id,
    COUNT(DISTINCT payment_type) AS payment_types_used,
    SUM(payment_value) AS total_paid
FROM olist_order_payments_dataset
GROUP BY order_id
HAVING COUNT(DISTINCT payment_type) > 1
ORDER BY payment_types_used DESC, total_paid DESC
LIMIT 10;

2,246 orders used two types; none used more. The largest paid 3297.4.

Common Use Cases

1. List the Options

-- Which payment types are there?
SELECT DISTINCT payment_type
FROM olist_order_payments_dataset;

5 types. This column has no index, so they come in the order the table first holds each one.

2. Find Who Took Part

-- Which sellers have sold something?
SELECT DISTINCT seller_id
FROM olist_order_items_dataset;

3,095 sellers have sold something; the site shows the first 30.

3. Explore the Data

-- Which product categories have a name?
SELECT DISTINCT product_category_name
FROM olist_products_dataset
WHERE product_category_name IS NOT NULL
ORDER BY product_category_name;

4. Check the Data

Is any customer_id used twice?

-- Is any customer_id used twice?
SELECT customer_id, COUNT(*) AS copies
FROM olist_customers_dataset
GROUP BY customer_id
HAVING COUNT(*) > 1;

No rows: each customer_id is used once.

5. Build a Lookup List

-- One sample city for each state
SELECT
    customer_state AS state_code,
    MIN(customer_city) AS sample_city
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_state;

GROUP BY already returns one row a state, so DISTINCT adds nothing here. Written with it, the query returns the same 27 rows:

SELECT DISTINCT
    customer_state AS state_code,
    MIN(customer_city) AS sample_city
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_state;

Performance Considerations

How SQLite Runs DISTINCT

SQLite's plans for these statements show two ways:

  1. An index on the column. The index holds the values in order, so equal values stand together, and SQLite can tell a new value "by comparing the current row to the previous row". Its documentation: "SQLite will also attempt to use indexes to help satisfy GROUP BY clauses and the DISTINCT keyword."
  2. No index. SQLite keeps a temporary list of the values it has seen, in a b-tree, and skips any row whose value is already in it (the plan says USE TEMP B-TREE FOR DISTINCT). A new value is passed on as soon as it is met. Its documentation: "If a SELECT query contains an ORDER BY, GROUP BY or DISTINCT clause, SQLite may need to use a temporary b-tree structure to sort the output rows."

The times below were measured on the site's engine (SQLite 3.54.1 on the course's file, the median of six timed runs, without printing the rows).

1. Filter with WHERE First

SELECT DISTINCT customer_city
FROM olist_customers_dataset
WHERE customer_state = 'SP';

The cities of SP alone, found through the state index: 18.87 ms, against 32.65 ms for the cities of every state.

2. Select Only the Columns You Need

SELECT DISTINCT * on the customers took 391.91 ms, against 4.47 ms for SELECT DISTINCT customer_state: every column of every row went into the list.

3. An Index Helps

The state has an index and the city has none: 4.47 ms against 32.65 ms, for 27 and 4,119 values.

4. Use LIMIT When Exploring

SELECT DISTINCT customer_city
FROM olist_customers_dataset
LIMIT 10;

Because each new value is passed on as soon as it is met, LIMIT stops the work early: the first ten cities took 0.03 ms, all 4,119 of them 32.65 ms.

Summary

Key Takeaways

  • DISTINCT removes repeated rows from the result
  • With several columns, it keeps each different combination once
  • COUNT(DISTINCT column) counts the different values, leaving NULL out
  • DISTINCT treats two NULLs as one value
  • DISTINCT promises no order: add ORDER BY when the order matters
  • For aggregates per value, use GROUP BY

Quick Reference

-- Each value of one column once
SELECT DISTINCT column
FROM table_name;

-- Each combination once
SELECT DISTINCT col1, col2
FROM table_name;

-- Count the different values
SELECT COUNT(DISTINCT column)
FROM table_name;

-- Different values per group
SELECT group_col, COUNT(DISTINCT value_col)
FROM table_name
GROUP BY group_col;

What's Next?

TOP keeps only the first rows of a result.