This course builds on SQL from zero. If you've done that one, this lesson is a quick warm-up; if you haven't, it covers what the rest of the course uses, so you can start here.
A database keeps data in tables of rows (one thing each, like one order) and columns (one fact each, like its date). SQL is the language for asking it questions, and each question is a query. The examples use a small shop: customers, products, orders and order_items (which products are in each order, and how many), plus a few other tables you'll meet along the way. The practice lists them all under The tables.
A query names the columns to SELECT, the table they come FROM, which rows to keep with WHERE, how to sort with ORDER BY (add DESC for largest first) and how many to keep with LIMIT. Text goes in single quotes, and dates are written year-month-day so they compare in time order.
SELECT name, price
FROM products
WHERE category = 'Garden' AND price < 30
ORDER BY price DESC;
Returns
name | price
------------+------
Duck feeder | 24
Pond net | 12.5
(2 rows)
A missing value is NULL, which means unknown. Nothing equals NULL, so you test for it with IS NULL or IS NOT NULL, and COALESCE(x, 'fallback') swaps it for something else.
Aggregate functions turn many rows into one answer: COUNT(*) counts rows, SUM and AVG add up and average a column, MIN and MAX find the smallest and largest. They skip NULLs. AS names a result column, ROUND(x, 2) rounds, and CASE WHEN … THEN … ELSE … END picks a value for each row.
SELECT COUNT(*) AS orders, MIN(ordered_on) AS first, MAX(ordered_on) AS last
FROM orders;
Returns
orders | first | last
-------+------------+-----------
10 | 2024-09-01 | 2024-10-11
(1 row)
Practice
The names and cities of the customers in Denver, in alphabetical order of name.