SELECT chooses columns, WHERE filters rows, and ORDER BY controls output order. Write them in that order, test the filter first, then sort by business fields so reports stay predictable.
- List only the columns you need so result sets stay readable and efficient.
- Use explicit date and status filters instead of relying on default table order.
- Always add a tiebreaker column to ORDER BY when rows can share the same value.
Start narrow, then expand
In the Northstar Outfitters analytics database, analysts often begin with orders and order_items. A narrow SELECT with clear aliases makes the first pass easy to verify before joining more tables.
WHERE clauses should encode the business rule directly. If you need shipped orders from last month, express both conditions in SQL so others can inspect the rule instead of guessing from a chart.
Sort for human review and exports
ORDER BY is not optional when people compare rows manually or export to CSV. Without it, row order can change after index changes, vacuum operations, or plan differences.
If two rows can share the same timestamp, add a second sort column such as order_id. This keeps pagination and audit checks stable across reruns.
- Use ASC or DESC explicitly for each sort column.
- Prefer ISO date literals like 2026-01-01 for clarity.
- Treat NULL ordering intentionally when reviewing incomplete records.
List shipped winter orders by recency
Northstar Outfitters stores orders in orders(order_id, customer_id, order_date, status, shipped_at, total_amount).
- Select order_id, customer_id, and shipped_at from orders.
- Filter with WHERE status = 'shipped' AND order_date >= DATE '2026-01-01'.
- Sort with ORDER BY shipped_at DESC, order_id DESC so ties are deterministic.
Common mistakes
- Using SELECT * in production reports and exposing unused fields.
- Filtering with text dates that compare lexicographically instead of as dates.
- Assuming table insertion order is reliable output ordering.
- Sorting by a display label instead of a business key or timestamp.
Try one
Why should ORDER BY shipped_at DESC, order_id DESC be preferred over ORDER BY shipped_at DESC alone?
The second column breaks ties, so rows with the same shipped_at value return in a stable order across reruns.
Sources
- PostgreSQL 18 Docs: SELECTOfficial syntax and processing order for SELECT, WHERE, and ORDER BY.