WHERE, ORDER BY, LIMIT, narrowing the noise
A SELECT without WHERE is like walking into a library and asking for "all the books." Technically correct, practically useless. WHERE is how you filter. ORDER BY is how you sort. LIMIT is how you stop the database from drowning you in rows.
These three clauses show up in every real query you will ever write. Let us learn them properly.
WHERE: the filter
WHERE follows FROM. Read it as a sentence: "from this table, where this condition is true."
SELECT name, city FROM customers
WHERE city = 'Mumbai';The operators you actually use:
=equals. Strings need single quotes, numbers do not.!=or<>not equals. Both work, pick one and stay consistent.<,>,<=,>=the usual suspects, for numbers and dates.BETWEEN a AND binclusive range.BETWEEN 100 AND 500includes both endpoints.IN (...)one of these values. Cleaner than chaining ORs.LIKE '%chai%'pattern match.%is "anything,"_is "exactly one character."IS NULL/IS NOT NULLNULL is special.= NULLdoes not work, ever.
NULL is not a value. It is the absence of a value.
WHERE column = NULLalways returns nothing. UseIS NULL. I have debugged this exact bug for senior engineers more times than I care to admit.
Combining conditions
Chain with AND and OR. Wrap with parentheses when you mix them, because precedence will bite you.
SELECT * FROM orders
WHERE city = 'Bengaluru'
AND (status = 'delivered' OR status = 'out_for_delivery');Without the parentheses, the OR would slip past the AND and you would get every "out_for_delivery" order in the country.
ORDER BY: sort it
By default, databases give you rows in whatever order they feel like. If you want a specific order, you have to ask.
SELECT name, total FROM orders
ORDER BY total DESC;ASCascending (default, smallest first).DESCdescending, biggest first. The one you actually want most of the time.- Multi-column:
ORDER BY city ASC, total DESCsorts by city, then within each city sorts by total descending.
LIMIT and OFFSET: pagination
You do not want all 4 million orders. You want the first 20.
SELECT name, total FROM orders
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;LIMIT 20give me 20 rows.OFFSET 40skip the first 40. So this is page 3 if your page size is 20.
Always pair LIMIT with ORDER BY. Without sorting, "the first 20" is meaningless. The database could return any 20.
Try it on the right
Three assignments waiting. They build on each other, do them in order. Next up: JOINs, where SQL gets actually interesting.
Free tools you can use while you learn
Watching quietly. Tap me if you want a tip.
Try this (0 of 3 done)
- 1
Show the 3 orders with the highest total, descending.
hint
ORDER BY total DESC, then LIMIT 3.
show answer
SELECT * FROM orders ORDER BY total DESC LIMIT 3; - 2
Find all orders where the total is between 300 and 500 (inclusive).
hint
WHERE total BETWEEN 300 AND 500
show answer
SELECT * FROM orders WHERE total BETWEEN 300 AND 500; - 3
Show all cancelled orders.
show answer
SELECT * FROM orders WHERE status = 'cancelled';