Timedora

Plan Reliable Business Queries

A practical lesson on defining query grain, planning business questions, avoiding join-driven duplication, and validating aggregated SQL results.

Start with the question and its

Plan the result before writing the query

Start with the business question, not with a list of tables. For each requested result, decide five things:

  1. : What quantity are you calculating, and what does it mean? For revenue, agree on the definition—for example, quantity multiplied by unit price. Include discounts only if the agreed definition requires them and the query has the relevant discount data.

  2. Output : What does one result row represent? “One row per month and product category” is a different result from “one row per order.”

  3. Time basis: Which date determines the month—order date, shipment date, or another date? Make the choice explicit.

  4. Scope: Which records count? Specify rules such as the date range and whether to include completed orders only.

  5. Source detail: Which tables supply the necessary information, and what does each contribute?

These choices work together. The determines the detail you need; the and dimensions determine which fields to retrieve; and the time basis and scope determine which records to include.

Work through the sales question

Suppose a sales manager asks, “What was revenue by month and product category?” A clear plan is one result row for each month-and-category combination, using the chosen order date and filtering to completed orders. If the agreed scope also sets a date range, make that range explicit in the query.

The example starts with sales line items because each row represents a product line on an order and provides quantities and prices. Orders supply the date and status needed for the time and scope rules. Products supply the category. The source query implements the plan by grouping line items by month and category and summing quantity multiplied by unit price within each group:

SELECT
    DATE_TRUNC('month', o.order_date) AS order_month,
    p.category,
    SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items AS oi
JOIN orders AS o
    ON o.order_id = oi.order_id
JOIN products AS p
    ON p.product_id = oi.product_id
WHERE o.status = 'completed'
GROUP BY
    DATE_TRUNC('month', o.order_date),
    p.category
ORDER BY
    order_month,
    p.category;

Here, GROUP BY gives one result for each month-and-category combination, and SUM adds the line-item amounts in each group. The query filters to completed orders; if the business question specifies a date range, add the agreed date condition as well. The example uses a database-specific date-truncation operation to obtain the month, and the exact syntax can vary between database systems. Before implementing the plan, confirm that the chosen fields and filters match the business definitions. A query can be syntactically valid yet answer the wrong question if its date basis, included statuses, or is left implicit.

Join without multiplying measures

Check the tables before joining

Tables often describe different things at different levels of detail. An orders table may have one row per order, while an order-items table may have several rows per order—one for each product line. Joining orders to items repeats the order's attributes across its matching item rows. That is expected for line-level analysis, but it can distort a that is meant to be counted or summed once per order.

Before joining, establish what one row represents in each table, which keys connect the tables, whether those keys are unique, and how many matches each row can have on either side. Also decide what should happen to unmatched records: the join type affects whether they are retained or excluded. These checks help determine whether the join will preserve the you intend to report.

Why two detail tables can inflate totals

Suppose an order has multiple line items and multiple payments. Joining the raw item rows directly to the raw payment rows can pair every item with every payment for that order. Hypothetical illustration: with two items and three payments, that order can produce six joined rows. An item-level amount would then appear three times, so summing it over the joined rows would overstate the sales total.

A safer approach, when payment totals are needed alongside order-level information, is to aggregate payments to one row per order before joining that result at the order level. More generally, bring tables to compatible grains before combining them. Do not reach reflexively for DISTINCT: it may conceal duplicate-looking rows without undoing an inflated sum.

Investigate unexpected rows or totals

More rows than expected are a reason to investigate, not proof that source data is wrong. Compare row counts before and after each join, test whether the presumed key is unique, and group by the expected output key to find keys with multiple matches. Then determine whether the matches are valid business events, repeated source records, or evidence of an incorrect join condition.

For example, if the result is supposed to contain one row per order but some orders appear several times, check whether line-item or payment detail has entered the query. If a total is unexpectedly high, test whether joining those two detail tables multiplied rows. Correct the join, choose a more suitable starting , or aggregate one side before joining, depending on what the checks reveal.

Read and validate aggregated results

Let the grouping define the row meaning

Grouping columns determine what each output row represents. In the sales example, grouping by month and product category creates one result for each month-and-category combination. The revenue sum is calculated from the line items in each such group. A should fit that level of detail: summing line-item revenue suits this grouping, while a value that belongs once per order needs care if joins have repeated it across item rows.

Make results interpretable with column names that clearly identify measures and dimensions, and make important rules visible in the query. Decide how to handle missing values, canceled or refunded transactions, and unmatched lookup records; these choices can affect both which records appear and what totals mean.

Validate the result

Check a small sample against known records to see whether the calculations and business rules behave as intended. When possible, reconcile totals with a trusted report. If the numbers differ, revisit the definition, filters, grouping , and joins rather than assuming the itself is the only issue. Validation is especially useful for confirming that the rows being combined and the rows being excluded match the intended business question.

  • : The number of rows on one side of a join that can match a row on the other side.

  • : The level of detail represented by a table's rows.