Choosing Columns and SQL DISTINCT
Name the columns you need, and add DISTINCT when you want each value once.
The
SELECT
line controls which columns appear in your result. The shortcut
*
means "show every column", which is useful for exploring a table.
Once you know what you need, name the columns directly. That keeps results focused and makes your query easier for another person to understand.
Naming columns can leave repeats behind. Ask for customers' states and you
get one row per customer, so PA appears six times.
DISTINCT, written straight after
SELECT, keeps each distinct row once.
It compares whole rows, not one column. With two columns selected, a state appears once for every different city it has, because each state and city pair is its own row.
select distinct column_one, column_two
from table_name Schema · Garden Shop Table · customers 9 columns · 20 rows
One row per customer. Some customers have no phone on file.
List every place the shop has customers: each state and city pair once, sorted by state, then city.
Run your query to inspect the result.
Expected answer
- Columns: state, city.
- Rows: 15 state and city pairs, sorted by state, then city.
- 20 customers live in 15 places, so five repeated rows disappear.
Related
Clause order and the shape of a SELECT query.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Sort before you limit, or top-N is arbitrary.
Write a first SELECT and read the returned rows.
Sort rows and keep the focused top results.