Sub topic 1
Why Duplicate Rows Appear in Query Results
Prerequisites
This chapter assumes you can write a basic SELECT statement with FROM and WHERE, sort results with ORDER BY, and describe a table as rows and columns. Knowing how a JOIN combines two tables helps, because joins are a common source of repeated rows.
How duplicates arise
A query returns one output row for each matching source row. If several rows hold the same value, that value appears several times in the result. The following query returns the country of every customer:
SELECT country
FROM customers;If 40 customers live in Canada, "Canada" appears 40 times. Joins cause the same effect. One order that matches three line items produces three rows, and the order columns repeat in each.
Removing duplicates with SELECT DISTINCT
Place the keyword DISTINCT directly after SELECT. The database then returns each value once:
SELECT DISTINCT country
FROM customers;> Note: DISTINCT treats all NULL values as equal, so the result contains at most one NULL row.
DISTINCT across multiple columns
When you list several columns, DISTINCT applies to the combination of all of them. Each unique pair appears once:
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city;Adding a column usually returns more rows, not fewer, because each new combination counts as distinct.
Counting unique values with COUNT(DISTINCT)
COUNT(DISTINCT country) counts the different non-NULL values in a column instead of the rows:
SELECT COUNT(DISTINCT country) AS country_count
FROM customers;Exercise
Exercise
Write a query that returns how many different cities appear in the customers table.
Show answer
SELECT COUNT(DISTINCT city) AS city_count FROM customers;