DISTINCT, LIMIT, aliases & ordering: the small everyday tools
Four little tools you'll use in almost every query: remove duplicates, cap the rows, rename columns, and sort by more than one thing.
These four aren't big concepts. They're the small conveniences you'll use in nearly every query. Worth a quick tour so they don't surprise you.
🎯 Explain Like I'm Hired These are your everyday polish tools:
DISTINCTremoves duplicate rows,LIMITcaps how many rows come back, an alias renames a column or table so the output reads nicely, andORDER BYcan sort by several columns at once. Example: "give me the 5 countries we have customers in" isSELECT DISTINCT country ... LIMIT 5, using distinct to avoid repeating the same country, and limit to stop at five.
DISTINCT: remove duplicate rows
SELECT DISTINCT country FROM customers; -- each country listed once
DISTINCT collapses repeated rows into one. Useful for "what are all the possible values here?"
LIMIT: cap the number of rows
SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10; -- 10 most recent
LIMIT 10 returns at most 10 rows. Almost always paired with ORDER BY, otherwise "the first 10" is
whatever the database happens to return. OFFSET 10 skips the first 10 (used for paging through
results).
Aliases: rename for readability
SELECT SUM(amount) AS total_revenue -- the column header reads "total_revenue"
FROM orders o -- "o" is a short nickname for orders
WHERE o.status = 'delivered';
AS total_revenue gives a computed column a readable name. A table alias (orders o) is a short
nickname so you can write o.status instead of orders.status, essential once you're joining
several tables.
Ordering by more than one column
SELECT * FROM orders ORDER BY country, placed_at DESC;
This sorts by country first, then within each country sorts newest-first. The database applies the sort columns left to right.
Next: Data types & casting →