SELECT and WHERE
~320 words ยท 2 min read
Asking questions of your data
Every SQL query is a question. SELECT chooses which columns to answer with; WHERE chooses which rows to include. Master these two clauses and you can answer most business questions.
Selecting columns
SELECT name, email, signup_date
FROM users;
Use * to select everything, but prefer naming columns explicitly โ it makes the query faster and self-documenting, and it won't silently break if new columns are added later.
Filtering with WHERE
The WHERE clause keeps only the rows that match a condition:
SELECT name, email
FROM users
WHERE status = 'active'
AND signup_date >= '2024-01-01';
Comparison and logical operators
=equal,<>not equal<,>,<=,>=orderingAND,OR,NOTcombine conditionsIS NULL/IS NOT NULLโ null checks (never use= NULL)IN ('a', 'b', 'c')โ membership in a listBETWEEN x AND yโ inclusive rangeLIKE 'pre%'โ pattern match (%= any chars)
NULLmeans "unknown", not "zero" or "empty".NULL = NULLis not true โ always useIS NULLto test for it.
Sorting and limiting
SELECT name, score
FROM players
ORDER BY score DESC, name ASC
LIMIT 10;
ORDER BY sorts the final result; LIMIT caps how many rows come back. Together they answer "show me the top 10".