Sorting, top N and DISTINCT
Order rows, take the top few, handle ties and missing values, and list a column's distinct values.
What runs in CodeSplash
- Frequencies (categorical variables) Verified in Python and R
You will be able to
- Sort rows with ORDER BY, including by several columns
- Take the top N with LIMIT, and say when ties make it arbitrary
- List distinct values and combinations
Read first
Order the rows
ReadWithout ORDER BY, a query's row order isn't guaranteed. Add it whenever order matters.
SELECT species, sex, body_mass
FROM palmer_penguins_sample
ORDER BY body_mass DESC
LIMIT 3;
DESC sorts largest first. ASC, the default, sorts smallest first. Together with LIMIT, this gives you a top N: here, the three heaviest penguins, all Gentoo males, at 6,300, 6,050 and 6,000 grams.
Where do missing values go?
PredictPredict first
Two penguins have no recorded body_mass. In ORDER BY body_mass DESC, where do they go in DuckDB?
Reveal
Last, which is why the query above shows real weights at the top. Don't rely on this when you move SQL elsewhere: PostgreSQL puts NULLs first under DESC. Say NULLS LAST or NULLS FIRST when it matters.
Sort by several columns
In the appEach column has its own direction. Run this, then swap the two sort columns and see how the order changes.
SELECT species, island, body_mass
FROM palmer_penguins_sample
WHERE body_mass IS NOT NULL
ORDER BY species ASC, body_mass DESC
LIMIT 10;
Rows sort by the first column, and the second only breaks ties. Adelie comes first alphabetically, so you'll see the heaviest Adelies.
Ties make top N arbitrary
ExploreMany penguins share a weight. If you take LIMIT 5 and the fifth and sixth rows tie, the query keeps one of them with no stated reason.
Add a tiebreaker, so the same query gives the same rows next time:
SELECT species, island, bill_len, body_mass
FROM palmer_penguins_sample
WHERE body_mass IS NOT NULL
ORDER BY body_mass DESC, bill_len DESC, island
LIMIT 5;
A top-N query you'll rerun should always sort down to a unique row, or use a window function, which comes later in this track.
What values are there?
ExploreDISTINCT removes duplicates from the result. It works on the whole row.
SELECT DISTINCT species
FROM palmer_penguins_sample
ORDER BY species;
SELECT DISTINCT species, island
FROM palmer_penguins_sample
ORDER BY species, island;
SELECT count(DISTINCT island) AS islands
FROM palmer_penguins_sample;
Run them. The second shows which species live on which island: Gentoo only on Biscoe, Chinstrap only on Dream, Adelie on all three.
Write your own top N
In the appNow write one from a task. It opens in a new SQL tab, and Check compares your result with the answer's.
SQL exercise · penguins
Sort and take the top
Find the five heaviest penguins with a known body mass. Show species and body mass, heaviest first.
Hints
- ORDER BY … DESC puts the largest first. Without DESC you get the smallest.
- In a descending sort DuckDB puts missing values last by default, but say what you mean with IS NOT NULL.
Show a solution
SELECT species, body_mass
FROM {{table}}
WHERE body_mass IS NOT NULL
ORDER BY body_mass DESC
LIMIT 5;In the app this opens in a real SQL tab on the sample table and checks your result.
Check your understanding
CheckpointCheck yourself
How many distinct species and island combinations does the table have?
Show the answer
Answer: 5
SELECT DISTINCT species, island returns five rows. Three species on three islands could make nine, and the missing four tell you something about where these penguins live.
Check yourself
Which species is the single lightest penguin? Write a query with ORDER BY body_mass ASC LIMIT 1 and type the species.
Show the answer
Accepted: “Chinstrap”, “chinstrap”
It's a Chinstrap at 2,700 grams. A minimum alone wouldn't tell you whose it was, and that's when sorting beats summarizing.
Check yourself
A query has no ORDER BY. What can you say about its row order?
Show the answer
Answer: b
SQL tables have no inherent order, and DuckDB reads in parallel. If order matters, ask for it.
From sorted rows to a summary
ReflectSorted rows show you extremes; a summary shows you the whole column. When did a single extreme value last change what you thought about a dataset? Next, summarize a categorical column:
Recap
Recap- Use
ORDER BYwhenever order matters, with a tiebreaker for anything you'll rerun. - State
NULLS LASTorNULLS FIRSTif your SQL may move to another database. DISTINCTapplies to the whole row and lists the combinations that exist.