โ† SQL Primer

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
  • <, >, <=, >= ordering
  • AND, OR, NOT combine conditions
  • IS NULL / IS NOT NULL โ€” null checks (never use = NULL)
  • IN ('a', 'b', 'c') โ€” membership in a list
  • BETWEEN x AND y โ€” inclusive range
  • LIKE 'pre%' โ€” pattern match (% = any chars)
NULL means "unknown", not "zero" or "empty". NULL = NULL is not true โ€” always use IS NULL to 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".