DISTINCT
Some questions have repeated answers. Ask "which countries do our customers live in?" and India comes back three times:
SQL
SELECT country FROM customers;SELECT DISTINCT
DISTINCT removes duplicate rows from the result:
SQL
SELECT DISTINCT country
FROM customers
ORDER BY country;Ten rows become eight, with each country once. The table itself is unchanged: DISTINCT only affects what the query returns.
DISTINCT on several columns
With more than one column, a row is a duplicate only if every column matches. The two Engineers collapse into one row, but an Engineer and a Lead Engineer stay separate:
SQL
SELECT DISTINCT department, title
FROM employees
ORDER BY department, title;Counting distinct values
Put DISTINCT inside COUNT to count unique values:
SQL
SELECT
COUNT(*) AS orders,
COUNT(DISTINCT customer_id) AS customers_who_ordered,
COUNT(DISTINCT status) AS statuses
FROM orders;Twelve orders came from nine different customers, in four different statuses.
Exploring a column
DISTINCT is a quick way to see what values a column holds before you filter on it:
SQL
SELECT DISTINCT status FROM orders ORDER BY status;Finished this lesson?Mark it complete to earn +20 XP and move your progress on.