Lesson 2

SELECT, WHERE, and ORDER BY

Read the core shape of everyday SQL queries.

Most everyday SQL starts with a simple shape:

SELECT id, email, created_at
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 50;

Read it in layers:

  • SELECT says which columns appear in the result.
  • FROM says the starting table.
  • WHERE removes rows that do not match conditions.
  • ORDER BY controls result order.
  • LIMIT caps how many rows come back.

This order is easy to read, but databases do not necessarily execute it line by line. The database optimizer can choose indexes and reorder internal work. For debugging, your first job is still to understand the logical meaning.

Be careful with filters

Small filter changes can change behavior dramatically:

WHERE status = 'paid'
  AND created_at >= '2026-01-01'

This means both conditions must be true. If you use OR, rows can match either side:

WHERE status = 'paid'
   OR status = 'refunded'

When a query is wrong, isolate filters one at a time. Ask: which condition removes the row I expected to see?

Ordering is not guaranteed without ORDER BY

Tables do not have a stable natural order that application code should depend on. If an endpoint says "latest users", the query should express that with ORDER BY created_at DESC. Without it, results can appear stable in development and change later after indexes, upgrades, or data growth.

Key takeaway

For simple queries, debug from FROM to WHERE to ORDER BY. Confirm the source rows first, then add filters, then add sorting and limits.

Use the SQL Formatter to split a one-line query into readable clauses before you inspect filters.

When you want to practice, use the related DevCove tool — optional, not part of this lesson.

Open related tool

Back to course overview