Filtering and sorting: WHERE and ORDER BY
Usually you do not want every row, only the rows that meet some condition: sales in one region, or above a certain amount. The WHERE clause does this filtering, and it is one of the most-used pieces of SQL.
Filtering with WHERE
WHERE goes after FROM and states a condition. Only rows where the condition is true are returned:
SELECT region, amount\nFROM sales\nWHERE region = "US";In plain English: "give me the region and amount, from sales, but only the rows where the region is US." The database checks each row and keeps only the matching ones. (Note: real SQL usually uses single quotes for text like 'US'; we show double quotes here only for clarity.)
You can compare numbers too, using operators like = (equals), > (greater than), and >= (greater than or equal):
SELECT *\nFROM sales\nWHERE amount > 100;This keeps only sales bigger than 100. You can combine conditions with AND and OR:
SELECT *\nFROM sales\nWHERE region = "US" AND amount > 100;Now a row must satisfy both conditions: it must be a US sale and bigger than 100. AND narrows the results; OR widens them (a row matching either condition is kept).
Sorting with ORDER BY
To sort the results, add ORDER BY at the end, naming the column to sort by. Add DESC for descending (largest first):
SELECT region, amount\nFROM sales\nWHERE amount > 100\nORDER BY amount DESC;This returns US-or-any sales above 100, with the biggest amounts at the top. Without DESC, sorting is ascending (smallest first) by default.
SELECT region, amount FROM sales WHERE amount > 100 ORDER BY amount DESC; reads as: "choose region and amount, from the sales table, keep only rows over 100, and sort them from largest to smallest." Once you can read a query like a sentence, you can write one.Why filtering at the database matters
You could pull every row into Excel and filter by hand, but on millions of rows that is slow and error-prone. Letting the database filter with WHERE is faster, repeatable, and returns only what you need, which is the whole point of SQL.
- WHERE filters rows to those meeting a condition.
- Use = , > , >= and combine with AND (narrows) / OR (widens).
- ORDER BY sorts results; add DESC for largest first.
- Clause order is fixed: SELECT, FROM, WHERE, ORDER BY.