SQL Basics: SELECT, WHERE, ORDER BY

Reading tables with SELECT, filtering rows, sorting, limiting and handling NULLs correctly.

Beginner · about 5 hours · difficulty 1/5

SQL is the language you will use most as an analyst. Nearly all company data lives in relational databases or warehouses, and SQL is how you ask them questions.

The shape of a query

SELECT customer_id, order_date, amount
FROM orders
WHERE status = 'completed'
  AND order_date >= '2024-01-01'
ORDER BY amount DESC
LIMIT 20;
  • SELECT picks columns; use aliases (amount AS revenue) and expressions (amount * 0.9).
  • WHERE filters rows with =, <>, >, BETWEEN, IN (...), LIKE 'abc%'.
  • ORDER BY sorts; LIMIT (or TOP, FETCH FIRST) caps rows.
  • DISTINCT removes duplicate rows from the result.
  • CASE WHEN creates derived categories inside a query.

NULL is special

NULL means unknown. WHERE discount = NULL never matches; use IS NULL / IS NOT NULL. Comparisons with NULL return unknown, so WHERE status <> 'cancelled' silently drops rows where status is NULL. COALESCE(col, 0) substitutes defaults.

Order of evaluation

SQL runs roughly FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. That explains why you usually cannot use a SELECT alias in WHERE.

Pitfall: SELECT * on huge warehouse tables, which is slow and, in pay-per-byte warehouses, expensive. Move on when you can write filtered, sorted queries with CASE and NULL handling without looking anything up.

Key concepts

  • SELECT, aliases, expressions
  • WHERE with IN, BETWEEN, LIKE
  • ORDER BY and LIMIT
  • DISTINCT
  • CASE WHEN
  • NULL, IS NULL, COALESCE
  • Logical query evaluation order

Mini project

Load the Chinook sample database into SQLite or PostgreSQL and answer 10 questions such as 'the 20 longest tracks in the Rock genre' and 'invoices over 10 dollars from Canada'.

Check yourself

Why does WHERE status <> 'cancelled' exclude rows where status is NULL?

Free resources