SQL SELECT, filtering, ordering and NULL
Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.
What you will be able to do
#- Write SELECT queries with WHERE, ORDER BY and LIMIT.
- Reason about three-valued logic and NULL comparisons.
- Use parameterized queries to avoid injection.
Overview
#SELECT reads rows. The clauses run in a fixed logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
Filtering and ordering
SELECT id, title, created_at
FROM articles
WHERE status = 'published'
AND created_at >= now() - interval '30 days'
ORDER BY created_at DESC
LIMIT 20;
NULL and three-valued logic
NULL means unknown. NULL = NULL is not true; it is unknown. Use IS NULL and IS NOT NULL. A WHERE clause keeps only rows where the predicate is true, so unknown rows are filtered out.
SELECT id FROM articles WHERE published_at IS NULL; -- drafts
SELECT id FROM articles WHERE published_at IS NOT NULL; -- published
Parameterized queries
Never build SQL by string concatenation. Pass values as parameters so the driver escapes them.
await client.query('SELECT id FROM articles WHERE status = $1 LIMIT $2', ['published', 20]);
Common pitfalls
WHERE name = NULLinstead ofWHERE name IS NULL.- Using
NOT INwith a subquery that returns a NULL, which makes the whole predicate unknown. - Concatenating user input into SQL, which enables injection.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Given a row where email is NULL, how many rows does this return?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.sqlSELECT id FROM users WHERE email <> 'a@example.com';Exercise 2Implement
Write a query for the 10 most recent published articles with a non-null title.
starter.sql-- table articles(id, title, status, published_at)Reveal the reference answer
reference.sqlSELECT id, title FROM articles WHERE status = 'published' AND title IS NOT NULL ORDER BY published_at DESC LIMIT 10;Authored expected output: Up to 10 rows ordered by published_at descending.
Filter with WHERE, exclude NULL titles explicitly, order before limiting so the limit is deterministic.
Common misconceptions
#- NULL equals NULL: in SQL, comparisons with NULL are unknown, not true.
- LIMIT without ORDER BY is deterministic: without an order, the database may return any rows.
Follow-up practice
#- backend-databases-sql-joins
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.