// sql fundamentals

SELECT, WHERE, ORDER BY: the three words in almost every query

Every SQL query you'll write starts with picking columns, filtering rows, and sorting the result. Get comfortable with these three and you can read most queries.

Published 12 Jul 20265 min read55 reads

Almost every SQL query does three things: it picks which columns you want to see (SELECT), keeps only the rows you care about (WHERE), and puts them in an order (ORDER BY). If you understand these three, you can read the majority of queries you'll ever see.

🎯 Explain Like I'm Hired Think of a giant spreadsheet of every order your company has ever taken. SELECT is choosing which columns to show (just the customer and the amount, say). WHERE is filtering the rows down to the ones you want (only delivered orders). ORDER BY is sorting what's left (newest first). That's it: pick columns, filter rows, sort. Example: asked in an interview to "show the 10 most recent delivered orders," you'd SELECT the columns, WHERE status = 'delivered', ORDER BY the date newest-first, and LIMIT 10.

Here's all three together:

SELECT customer_id, amount        -- pick these columns
FROM orders
WHERE status = 'delivered'        -- keep only these rows
ORDER BY placed_at DESC;          -- sort newest first

SELECT picks columns

SELECT customer_id, amount means "show me only those two columns." Writing SELECT * means "show me every column." That's handy while exploring, but in real queries it's better to name the columns you actually need, so the result is smaller and clearer.

WHERE keeps the rows you want

WHERE checks a condition on each row and keeps the ones where it's true. WHERE status = 'delivered' keeps delivered orders and drops the rest. You can combine conditions with AND and OR:

WHERE status = 'delivered' AND amount > 500

One thing that trips up beginners: a blank/unknown value (called NULL) doesn't behave like a normal value in WHERE. WHERE status != 'cancelled' will quietly drop rows where status is blank, because "is a blank not equal to cancelled?" answers "unknown," not "yes." (There's a whole article on this: NULL handling.)

ORDER BY sorts the result

ORDER BY placed_at DESC sorts newest-first (DESC = descending). Leave off DESC (or write ASC) and it sorts oldest-first. You can sort by more than one column, e.g. ORDER BY country, placed_at DESC groups by country, then newest-first inside each country.

The interview tip

Sorting a huge table is one of the more expensive things a database does. If you only need the top few rows, add LIMIT (ORDER BY placed_at DESC LIMIT 10) so the database can stop early instead of sorting everything.


Next: GROUP BY & HAVING →