Blogs and Articles / Mastering SQL for data analysis
SQL analysis: make the total worth trusting
Work through a small sales query to understand aggregation, running totals, missing days and the checks that AI-generated SQL still needs.

Imagine receiving a sales report with three daily totals and a tidy running balance. Before using it, ask what one row represents, which orders qualify and what happened on the missing date. Those questions are the starting point for useful SQL analysis.
This worked example follows five fictional orders through a daily summary and a window calculation. The numbers are deliberately small enough to check by hand. Use the same habit when reviewing a much larger query, whether you wrote it yourself or asked an AI assistant to draft it.
First, define what one row means
For this example, each input row is one completed order, with an order identifier, a business date and an amount in a single currency. We want one output row per observed business date. Write those assumptions beside a real query, adding the reporting timezone, refund treatment and cut-off rules. If a colleague interprets sales differently, settle that disagreement before comparing totals. A calculation cannot choose the business definition for you.
GROUP BY combines rows that share the specified values. Here, grouping by order_day gives us the daily rows we need. This changes the level of detail in the result, so keep the order-level data available for investigation. A surprising daily total should lead back to identifiable orders, rather than to another summary whose inputs nobody can inspect.[1]
A join can change the amount you are adding
An inner join returns a row for each matching pair. Imagine joining an order worth 100 to its three line items, then summing the order amount. The joined result contains that 100 three times, producing 300. This is a consequence of the relationship, even when the SQL runs without an error. Our advice is to aggregate line items to the required level before joining, or sum the appropriate line amounts. Compare row counts and totals on both sides of every new join.[1]
Build the daily rows, then look across them
The query below includes its own fictional input, so you can run it without creating tables. Dates are fixed-width ISO text for this small exercise; production date and timestamp handling needs its own rules. The daily step calculates the total and order count. The outer SELECT then adds a running total and a change from the preceding observed day. PostgreSQL's tutorial explains this useful distinction: an ordinary aggregate combines rows, while a window function keeps the rows and calculates across them.[2]
A self-contained daily sales example
sqlWITH orders(order_id, order_day, amount) AS (
VALUES
(1, '2026-09-01', 100),
(2, '2026-09-01', 50),
(3, '2026-09-02', 80),
(4, '2026-09-02', 120),
(5, '2026-09-04', 75)
),
daily AS (
SELECT order_day,
COUNT(*) AS order_count,
SUM(amount) AS day_total
FROM orders
GROUP BY order_day
)
SELECT order_day, order_count, day_total,
SUM(day_total) OVER (
ORDER BY order_day
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_total,
day_total - LAG(day_total) OVER (
ORDER BY order_day
) AS change
FROM daily
ORDER BY order_day;Read the result as carefully as the query
The first two orders total 150. The next two total 200, so the running amount becomes 350 and the change is 50. The final order takes the running amount to 425. Notice that summing the running_total column would count earlier sales repeatedly. To answer the period-total question, use the sum of day_total or the final running value for this ordered example. The result table is also a compact expected answer you can save with the query.[3]
The explicit ROWS frame tells SUM to include the first daily row through the current one. That makes the intended accumulation visible during review. Each date is unique after grouping, so the window order is unambiguous. If you apply a similar calculation directly to individual orders, add a suitable tie-breaker when dates repeat. Also keep the final ORDER BY: the order used inside a window does not itself specify the displayed result order.[3][2]
| Date | Orders | Daily total | Running total | Change |
|---|---|---|---|---|
| 2026-09-01 | 2 | 150 | 150 | NULL |
| 2026-09-02 | 2 | 200 | 350 | 50 |
| 2026-09-04 | 1 | 75 | 425 | -125 |
Missing information needs a decision
LAG reads a preceding row, so the 4 September change compares with 2 September. It does not promise a comparison with yesterday. If daily continuity matters, introduce a calendar and decide how to represent dates without orders. Only assign zero when you know the feed is complete and the business had no qualifying activity. A missing delivery of data deserves investigation, not an automatic zero in a chart.[3]
Missing amounts need similar care. COUNT(*) counts rows, whereas COUNT(amount) counts non-null amounts. SUM ignores null inputs and returns null when there are no inputs. As a practical check, compare the two counts before accepting a monetary total. Replacing missing amounts with zero may conceal an upstream problem; document that choice if zero is genuinely the intended business meaning.[4]
What AI assistance changes in 2026
Google Cloud updated its Data Engineering Agent announcement on 22 April 2026 to mark general availability. The product generates pipeline code from natural-language requests. Google's documentation says users must review and run or schedule those pipelines, since the agent cannot execute them. This is a specific product development, but it illustrates a useful working boundary: assistance can produce a draft while a person still checks the transformation and its result.[5][6]
For an assistant drafting our example, provide the input columns, one-order-per-row assumption, qualifying statuses and expected output. Ask it to explain how it handles repeated dates and absent days. Then run the small example and compare every cell. Keep a deliberately awkward case, such as a missing amount or a duplicated join key, alongside the normal case. Our recommendation is to make these examples the acceptance criteria for generated SQL, rather than treating a plausible explanation as proof.
Sources and further reading
Sources were checked on the review date above. Product availability and documentation can change.
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.