Every SQL query you write as an analyst answers one question: which rows, which columns, in what order. The SELECT statement expresses that question, and it helps to know that the database does not read it in the order you type it.
You write SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT. The database evaluates it roughly as FROM (find the table), WHERE (keep matching rows), GROUP BY (collapse rows into groups), HAVING (filter groups), SELECT (compute the output columns), ORDER BY (sort) and finally LIMIT. This explains several common errors. For example, you usually cannot use a column alias defined in SELECT inside WHERE, because WHERE runs first.
The examples in this course use a small table called orders with these columns: order_id, customer_id, order_date, region, product, quantity, unit_price and status.
SELECT order_id, region, quantity * unit_price AS revenue
FROM orders
ORDER BY revenue DESC
LIMIT 10;
This returns the ten largest orders by revenue. Note three habits worth adopting now:
- Name your columns. Avoid
SELECT *in anything you share. It hides which fields a result depends on and breaks when the table changes. - Alias calculations.
AS revenuemakes the output readable and lets you sort by it. - Limit while exploring. On a large table, add
LIMITwhile you check your logic.
Try this
Write a query that returns order_id, order_date and product for the 20 most recent orders. Then rewrite it so that it also shows revenue, aliased as revenue. If you have no database to hand, SQLite and DB Fiddle both run these examples for free.