Filter and sort results
Use WHERE to select matching rows and ORDER BY to control their order.
- Combine comparisons, boolean conditions and sorting in a query.
WHERE filters rows before they appear in the result. ORDER BY arranges the remaining rows; ASC is ascending and DESC is descending. Use parentheses when they make combined conditions easier to understand.
1SELECT name, city
2FROM customers
3WHERE city = 'Boston'
4ORDER BY name ASC;
5
6SELECT order_id, total
7FROM orders
8WHERE total >= 100 AND total < 500
9ORDER BY total DESC;Use = for equality in SQL. Text values use single quotes. NULL means a value is missing or unknown, so compare it with IS NULL rather than = NULL.
Key takeaways
Combine comparisons, boolean conditions and sorting in a query.
Use table and column names that make the query easy to read.
Check which rows a query affects before relying on its result.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write SQL queries
Write queries against small sample databases and run them locally in your browser. Each test starts from a fresh SQLite database.
Find products in a price range
Return the product name and price for products costing at least 10 and less than 50. Show the most expensive matching product first.
- Products from 10 to under 50
Sample tables and rows
Each test rebuilds an in-memory database for the selected dialect before running your query.
CREATE TABLE products (name TEXT, price REAL); INSERT INTO products VALUES ('Notebook', 12.5), ('Desk', 125), ('Pen', 2), ('Lamp', 35);Using SQLite 3 (sql.js), an embedded database. Queries run locally in a worker against a fresh in-memory database for each test.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…