Section 1 · Lesson 3
Sorting, DISTINCT and missing values
Sort results with ORDER BY, build top-N lists with LIMIT, remove duplicates with DISTINCT and handle NULL correctly.
Filtering gets you the right rows. This lesson is about presenting them well: in a useful order, without duplicates, and without being tripped up by missing values.
ORDER BY: sorting results
SELECT name, daily_budget
FROM campaigns
ORDER BY daily_budget DESC;
ASC(ascending, the default) puts the smallest number, earliest date or “A” first.DESC(descending) puts the largest first.- You can sort by several columns. The second one only matters when the first one ties:
ORDER BY channel, daily_budget DESCgroups the channels alphabetically and shows the biggest budgets first within each channel.
Ties are more common than you’d think: four campaigns in our data share a 1,400 USD budget.
If the order of tied rows matters (a ranked report, a top-N list), always add a tie-breaker
column such as name or id, otherwise two runs of the same query may disagree.
LIMIT: top-N lists
ORDER BY + LIMIT is how you answer every “top 10” question:
-- The 3 largest orders ever placed
SELECT id, customer_id, amount
FROM orders
ORDER BY amount DESC
LIMIT 3;
LIMIT 10 OFFSET 20 skips the first 20 rows and returns the next 10, which is how apps
page through results. Remember from lesson 1: LIMIT without ORDER BY returns an
arbitrary sample, not the “top” anything.
DISTINCT: unique values
SELECT DISTINCT industry FROM advertisers;
DISTINCT removes duplicate rows from the result. With several columns it keeps each unique
combination: SELECT DISTINCT channel, objective returns each channel/objective pair once.
It’s the quickest way to learn which values a column actually contains before you filter on it.
NULL: the value that isn’t there
NULL means “unknown” or “not applicable”. It is not zero and not an empty string. In our data:
campaigns.end_dateis NULL for always-on campaigns with no planned end.customers.age_groupis NULL when the customer didn’t share it.orders.campaign_idis NULL when an order can’t be credited to any campaign.
Because NULL is unknown, any normal comparison with it is also unknown, so the row is dropped:
WHERE end_date = NULL -- never true, returns nothing
WHERE end_date IS NULL -- correct: always-on campaigns
WHERE end_date IS NOT NULL -- campaigns with a planned end
The same trap hides in “not equal” filters. WHERE age_group <> '25-34' silently skips
customers whose age group is NULL. If you want them, say so:
WHERE age_group <> '25-34' OR age_group IS NULL.
COALESCE: fill in a default
COALESCE returns the first value in its list that isn’t NULL. It’s ideal for readable labels
in reports:
SELECT first_name, last_name, COALESCE(age_group, 'unknown') AS age_group
FROM customers;
The underlying data doesn’t change; only the output does.
Sorting NULLs: SQLite treats NULL as smaller than any value, so NULLs appear first in an ascending sort and last in a descending one. PostgreSQL does the opposite. SQLite also supports
ORDER BY end_date NULLS LASTwhen you want to control it explicitly.
Putting it together
A query’s clauses always appear in this order:
SELECT DISTINCT ... -- columns
FROM ... -- table
WHERE ... -- row filter
ORDER BY ... -- sorting
LIMIT ...; -- how many rows
The video uses an earthquake table rather than our ad data, but every clause it shows works the same way in the sandbox.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Top 5 daily budgets
DoneShow the 5 campaigns with the highest daily_budget. Return name, channel and daily_budget, sorted by daily_budget from highest to lowest. Several campaigns share the same budget, so break ties by name in alphabetical order (A to Z).
Need a hint?
ORDER BYsorts ascending (smallest first) unless you addDESC.- List a second column after a comma to break ties:
ORDER BY daily_budget DESC, name.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT name, channel, daily_budget
FROM campaigns
ORDER BY daily_budget
LIMIT 5;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Which channels have which statuses?
DoneList each distinct combination of channel and status that appears in campaigns, once per combination (2 columns: channel, then status). Sort by channel A to Z, then by status A to Z.
Need a hint?
SELECT DISTINCTremoves duplicate rows from the result.- DISTINCT applies to the whole row, so each channel/status pair appears once.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT channel, status
FROM campaigns
ORDER BY channel, status;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Label always-on campaigns
DoneFor every campaign on the search channel, return name, start_date and the end date. When end_date is NULL (the campaign is always-on), show the text always-on instead. Sort by start_date (earliest first), then by name A to Z.
Need a hint?
COALESCE(a, b)returnsaunless it is NULL, in which case it returnsb.- Write it as
COALESCE(end_date, 'always-on'), with the label in single quotes.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT name, start_date, end_date
FROM campaigns
WHERE channel = 'search'
ORDER BY start_date, name;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)