Reviewing SQL queries

On this page

Judge queries against their purpose

A query can be valid SQL and still answer the wrong question. Start with the requested output, then check the source relationships, row filters, time boundary, and grouping.

  • A query must be judged against a stated purpose: the required output columns, population, period, and level of detail. State these before reviewing the SQL.
  • Extracting and integrating data: Confirm each source's documented key, the matching key in the other source, and the row grain before accepting a join.
  • In standard SQL, an inner JOIN keeps combinations that satisfy its ON condition. A wrong key can remove valid rows, create incorrect matches, or change the row count.
  • A WHERE search condition keeps a row only when the condition is TRUE. Rows that are FALSE or UNKNOWN, including many NULL comparisons, are not returned.
  • For a full period stored as timestamps, use a closed lower bound and an open upper bound. Use the first instant and the first instant after the period.
  • Every selected nonaggregate expression must satisfy the query's grouping rules. A grouped result must have the requested grain, and ORDER BY is needed when a specific output order is required.

January gross sales query

Prepared by the data analyst; the query does not tie to its stated purpose.

SQL linePrepared query
1SELECT c.customer_id,
2c.customer_name,
3SUM(oi.quantity * oi.unit_price) AS gross_sales
4FROM customers c
5JOIN orders o ON o.customer_id = c.customer_id
6JOIN order_items oi ON oi.order_id = c.customer_id
7WHERE o.order_ts >= TIMESTAMP '2025-01-01 00:00:00'
8AND o.order_ts <= TIMESTAMP '2025-01-31 00:00:00'
9GROUP BY c.customer_id, c.customer_name
10ORDER BY gross_sales DESC;
SourceFacts
PurposeShow January 2025 completed gross sales by customer, including all order lines belonging to qualifying orders, with one row per customer.
customerscustomer_id is the unique customer key. Customer 10 is Ada Lee. Customer 20 is Ben Ortiz.
ordersOrder 1001 belongs to customer 10, has order timestamp 2025-01-01 09:00:00, and status Completed.
ordersOrder 1002 belongs to customer 10, has order timestamp 2025-01-31 15:30:00, and status Completed.
ordersOrder 1003 belongs to customer 20, has order timestamp 2025-01-20 12:00:00, and status Cancelled.
ordersOrder 1004 belongs to customer 20, has order timestamp 2025-02-01 08:00:00, and status Completed.
order_itemsEach row belongs to an order through order_items.order_id = orders.order_id.
order_itemsOrder 1001 has quantity 2 at unit price $50.
order_itemsOrder 1002 has quantity 1 at unit price $80.
order_itemsOrder 1003 has quantity 4 at unit price $25.
order_itemsOrder 1004 has quantity 3 at unit price $40.

Wrong joins, dates and status

The wrong join key breaks the relationship between orders and their lines before any WHERE condition can help. The date and status problems then show that a query can have the right tables and still be incomplete.

What is wrongWhere it sitsCorrect figure or treatmentRule and chapterError tag
The order-line join compares an order-line order ID with a customer ID.Line 6: JOIN order_items oi ON oi.order_id = c.customer_idUse JOIN order_items oi ON oi.order_id = o.order_id.Extracting and integrating data: Match each source through the documented key relationship. Reviewing SQL queries: inspect each ON condition against the source facts.cross-document reconciliation
The upper date condition stops at midnight at the start of January 31, so later January 31 timestamps are not included.Line 8: o.order_ts <= TIMESTAMP '2025-01-31 00:00:00'Use AND o.order_ts < TIMESTAMP '2025-02-01 00:00:00'. This includes every timestamp in January and excludes February.Reviewing SQL queries: use the first instant after a timestamp period as the open upper bound.rule selection
The query includes cancelled orders even though the purpose says completed sales.The WHERE clause has no status condition.Add AND o.status = 'Completed'.Reviewing SQL queries: every population condition in the stated purpose must appear in the filtering logic.fact extraction

The corrected join reaches the intended order lines. The half-open date range covers January, and the status condition limits the population to completed orders.

March shipped sales by customer

This review changes the business status and month, so the purpose must be read again. The input-to-output trace also parallels Business process models and diagrams: identify the intended output, trace each input and transformation, and remove any break in that path.

Prepared by the reporting analyst; the query does not tie to its stated purpose.

SQL linePrepared query
PurposeShow March 2025 shipped sales by customer, with total value and one row per customer.
1SELECT c.customer_id,
2c.customer_name,
3SUM(oi.quantity * oi.unit_price) AS total_value
4FROM customers c
5JOIN orders o ON o.customer_id = c.customer_id
6JOIN order_items oi ON oi.order_id = o.order_id
7WHERE o.order_ts >= TIMESTAMP '2025-03-01 00:00:00'
8AND o.order_ts < TIMESTAMP '2025-04-01 00:00:00'
9GROUP BY c.customer_id
10ORDER BY total_value DESC;
Source notecustomer_id is the customer key. The status values include Shipped and Cancelled. Strict standard SQL grouping is required.

Practice

The March query must return only orders whose status is Shipped. Which change supplies that condition without changing the grouping or display order?

Which key condition connects each order line to the order that contains it?

One fact changes: the period field is DATE order_day rather than TIMESTAMP order_ts, and the displayed filter is order_day >= DATE '2025-03-01' and order_day < DATE '2025-04-01'. Does the date filter need a change to include every March date?

Output, keys, grain and boundaries

  1. Start with the output promise; every table, join, filter, selected field, and group must support it.
  2. Check key fields and row grain before trusting an aggregate.
  3. Test the population and both period boundaries, especially when timestamps are involved.

Unlock the full lesson and continue reading

Signup to continue reading this lesson and unlimited access questions, flashcards, AI notes, and more

Scan to download app

Scan to download
UNLOCK FREE ACCESS

Practice Questions: Reviewing SQL queries

  1. 1. A CPA on an internal controls team is reviewing the February 3, 20X5 migration of January sales data from a legacy billing system to a new cloud ERP. The migration is not yet approved for financial-reporting use. Management requires the target data to include all invoices posted during January, including January invoices corrected through the February 3 cutoff. Use the exhibits to identify extraction and transformation defects, calculate corrected totals, and determine the appropriate migration conclusion.

    • 2. A CPA in internal audit is reviewing the first production run of a sales data mart used for the July 15, 20X5 management revenue report. The CPA must determine whether the data model, source selection, transformations, and reconciliation controls conform to the approved requirements. Use Exhibits 1 through 4 to complete the review.

      • 3. A CPA on the internal controls team is reviewing the January 20X5 revenue data pipeline used for management reporting. The dashboard must report all posted January sales invoices and credit memos at net document amount and assign customer segment based on the segment effective on each document's accounting date. The CPA must determine the effect of the current extraction and transformation design and recommend a controlled remediation.

        • 4. A newly licensed CPA is validating the December 20X5 consolidated-revenue data pipeline for a U.S. parent. The pipeline combines U.S. dollar transactions with euro-denominated transactions from a European subsidiary. Management uses the target table for its monthly financial reporting analytics. The CPA must determine whether the pipeline followed the approved transformation specification, calculate the corrected target amount, and document the related processing and change-management issues.

          • 5. A CPA in internal audit is reviewing the first monthly production run of a new revenue data pipeline. The pipeline extracts posted invoice and credit-memo lines from a legacy billing system and loads a revenue fact table used for financial reporting. The CPA must determine whether the extraction, transformation, integration, change-management, and data-lineage controls operated as designed.

            • 6. A newly licensed CPA is reviewing the February 1, 20X5 migration of open accounts receivable from a legacy ERP system to a new ERP system. The legacy ERP is the system of record through January 31, 20X5. The conversion team must identify eligible documents, validate customer mappings, obtain approval for exceptions, ensure segregation of duties between preparation and loading, and reconcile the target system to approved source control totals.

              • 7. A CPA on an internal controls team is reviewing the first year-end load from a procurement system into an inventory-cost mart. Management intends to use the mart for financial reporting. The CPA must determine whether the extraction and transformation preserved a complete and accurate population and document the required remediation.

                • 8. A CPA on an internal controls team is reviewing the first production migration of posted purchase-order-line data from a procurement system to an inventory cost analytics warehouse. The dashboard has not yet been released to management. The CPA must evaluate whether the load complied with the approved mapping, quantify any error, and determine the appropriate remediation and documentation.

                  • 9. A CPA in internal audit is reviewing a new first-quarter sales data mart before management uses it for financial analysis and monitoring controls. The CPA must determine whether the extraction scope, transformations, customer classifications, and reconciliation procedures comply with the approved requirements, and whether an unauthorized credit-memo override was improperly included in the load. All amounts in the exhibits are in U.S. dollars.

                    Flashcards: Reviewing SQL queries

                    1. 1. Define a query in the context of reporting.

                      Show answer

                      A query is a user-initiated ad hoc report.

                    Everything you need for CPA prep

                    Get full Oncourse access with lessons, practice questions, flashcards and AI study tools.

                    GET STARTED FOR FREE
                    75% OFFLimited time offer
                    GET 75% OFF