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.

25 min 3 practice tasks
SQL SELECT Tutorial - Part 2 by Socratica on YouTube

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 DESC groups 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_date is NULL for always-on campaigns with no planned end.
  • customers.age_group is NULL when the customer didn’t share it.
  • orders.campaign_id is 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 LAST when 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.

1

Top 5 daily budgets

Show 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?
  1. ORDER BY sorts ascending (smallest first) unless you add DESC.
  2. List a second column after a comma to break ties: ORDER BY daily_budget DESC, name.
SQL · SQLite
SELECT name, channel, daily_budget
FROM campaigns
ORDER BY daily_budget
LIMIT 5;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Which channels have which statuses?

List 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?
  1. SELECT DISTINCT removes duplicate rows from the result.
  2. DISTINCT applies to the whole row, so each channel/status pair appears once.
SQL · SQLite
SELECT channel, status
FROM campaigns
ORDER BY channel, status;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue