Core SQL querying

SQL SELECT, WHERE, and ORDER BY for Daily Reporting

Use SELECT, WHERE, and ORDER BY together to pull clean report slices from operational tables, with clear filters, stable sorting, and fewer accidental data mistakes.

How this page is maintained

Written for learners, checked against the sources below, and reviewed every year. Last reviewed July 22, 2026.

Short answer

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).

  1. Select order_id, customer_id, and shipped_at from orders.
  2. Filter with WHERE status = 'shipped' AND order_date >= DATE '2026-01-01'.
  3. Sort with ORDER BY shipped_at DESC, order_id DESC so ties are deterministic.
Result: The team gets a repeatable shipped-order list sorted from newest to oldest with stable tie handling.

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

Learn this with a tutor

Tell LearnLive what you already know and what you need to do with select where order by.

Build this course