SQL Server

SQL for Data Engineering: Subqueries and CASE

Classify transactions with CASE and check product reference data with subqueries.

By Javier GuerreroPublished 12 min readIntermediate

Learning objectives

  • Classify transactions with CASE and check product reference data with subqueries.
  • Explain the input grain and output grain of this lesson’s query.
  • Identify a repeatability, quality, or performance decision in the example.
  • Verify the result against the supplied fictional fixture.

Prerequisites and setup

Prerequisites: SQL Server Foundations, including SELECT, WHERE, joins, aggregates, and NULL. Estimated time: 20–30 minutes. Run examples/sql-for-data-engineering/00_setup.sql in a disposable SQL Server 2019 or later database before running this lesson script.

Why this pattern matters

CASE turns ordered conditions into an explicit classification. Put the most specific rule first and include ELSE so new values do not disappear into an accidental NULL. EXISTS and NOT EXISTS answer whether a matching reference row is present without multiplying transaction rows. A scalar subquery can return one value, such as a product category, but must not return multiple rows. Correlated subqueries refer to the current outer row; they are clear for existence checks but should be measured on large inputs. Treat missing values separately from invalid values and preserve a reason for rejection.

A data pipeline is a sequence of contracts. The source defines what a delivered row means; the staging step records how strings become typed values; validation states which rules a row passed; curated tables define their business grain; and reports state how measures are aggregated. Keeping these boundaries visible makes failures diagnosable. If a dashboard total changes, an engineer can compare each boundary and determine whether the source changed, parsing changed, a rule changed, or a consumer joined at the wrong grain.

Repeatability is part of correctness. A rerun should not create a second business event, silently skip a correction, or advance a checkpoint before target changes commit. Use a stable business key for identity, a source version or delivery sequence for ordering, and a documented policy for late data. Keep rejected rows with their source identifiers and reasons. A replayable batch is easier to investigate than a one-off manual correction because its inputs and decisions remain available.

  1. Conditions
  2. Reference check
  3. Classification
Why this pattern matters. Classify transactions with CASE and check product reference data with subqueries.

Read the query

The shared fixture starts with the same 20 fictional rows as the Python Foundations sales CSV. Text columns intentionally include blanks, invalid numbers, zero and negative quantities, a malformed decimal, and one missing business key. Three additional deliveries cover an exact redelivery, a correction, and a late-arriving transaction. The scripts preserve this source evidence; they do not change the CSV used by Python exercises. This lesson focuses on the shared source records and uses the same table and column names in all three languages. The query is a complete SQL Server example, not pseudocode. Read the filter, selected columns, and final order together: a filter defines which rows qualify, the projection defines what a reader can inspect, and ORDER BY defines the displayed sequence.

The script is stored at examples/sql-for-data-engineering/03_case_subqueries.sql. Use the SQL viewer’s copy button to copy the exact source into SQL Server Management Studio or another SQL Server client. Run the setup script first. The viewer is read-only and does not execute queries or connect to a database. Outputs below come from the validated SQL Server run for this fixture.

SQL query: Repeatable sales transformationSQL Server T-SQL
/* Run 00_setup.sql first. CASE classifies rows; EXISTS and a scalar subquery check product reference data. */
SELECT d.transaction_id,d.product,
       CASE WHEN d.transaction_id IS NULL THEN 'Missing business key'
            WHEN TRY_CONVERT(date,d.order_date_text,23) IS NULL THEN 'Invalid date'
            WHEN TRY_CONVERT(int,d.quantity_text) IS NULL THEN 'Invalid quantity format'
            WHEN TRY_CONVERT(int,d.quantity_text) <= 0 THEN 'Quantity outside allowed range'
            WHEN TRY_CONVERT(decimal(10,2),d.unit_price_text) IS NULL THEN 'Invalid price format'
            WHEN TRY_CONVERT(decimal(10,2),d.unit_price_text) < 0 THEN 'Negative price'
            WHEN NULLIF(LTRIM(RTRIM(d.product)),'') IS NULL THEN 'Missing product'
            ELSE 'Candidate for curation' END AS validation_status,
       CASE WHEN EXISTS (SELECT 1 FROM sqleng.Product AS p WHERE p.product=d.product)
            THEN 'Known product' ELSE 'Unknown product' END AS product_status,
       CASE WHEN NOT EXISTS (SELECT 1 FROM sqleng.Product AS p WHERE p.product=d.product)
            THEN 'Reference row required' ELSE 'Reference row found' END AS reference_action,
       (SELECT p.product_category FROM sqleng.Product AS p WHERE p.product=d.product) AS product_category
FROM sqleng.TransactionDelivery AS d WHERE d.source_row_id <= 20
ORDER BY d.source_row_id;
SQL Server T-SQL17 linesRead-only query display. It is not connected to a database.

Make types and null behavior explicit. Use TRY_CONVERT when source text may be malformed, then distinguish conversion failure from a legitimate zero. A decimal type should match the precision of the business measure. Dates should use an explicit input format. NULL does not equal an empty string and cannot be tested with =. A derived value should have a named rule and a documented fallback. These details matter at boundaries because a value that parses differently on two machines can change both validation and totals. Readable SQL helps reviewers follow the transformation, but readability alone does not guarantee performance. CTEs are query-scoped names and are not promises that SQL Server materializes an intermediate result. Inspect actual plans and row counts when work is repeated or large. Add an index only for a demonstrated access pattern and after considering write cost. Prefer a small, auditable example first; production tuning should follow measurements rather than assumptions based on syntax.

Practice

Run the setup script once, then run the lesson query. Inspect the output grain before changing the SQL. Complete the exercise by changing only a copy of the fixture, rerunning the query, and explaining how the result changed. Add a CASE branch for a product that is absent from the reference table. Use NOT EXISTS to identify that exception and return a distinct action label. Verify that the query still returns exactly 20 source rows.

Expected result

20 source rows: 12 candidates, 8 invalid; 19 rows match the product reference.

Common mistakes

  • Treating a display order as guaranteed without ORDER BY.
  • Using a surrogate row ID as if it were the business key.
  • Replacing an invalid value without retaining its source and reason.
  • Assuming a readable query is automatically fast.
  • Rerunning a write without checking its idempotency.

Knowledge check

  1. When should EXISTS be used?
  2. What must a scalar subquery return?
  3. How should NULL be tested?

EXISTS checks for a matching row without multiplying output. A scalar subquery returns at most one value. Test NULL with IS NULL or IS NOT NULL.

Operational notes

Before scheduling a load, define ownership for failed batches, retries, retention, permissions, monitoring, and recovery. Record a run identifier, the input boundary, start and end times, and counts for received, accepted, rejected, inserted, and updated rows. Reconcile measures as well as row counts. A successful SQL statement does not prove the entire pipeline succeeded if a later publication step failed. Keep credentials outside scripts and apply least privilege. Test a restore or replay procedure before relying on it during an incident.

These scripts are instructional examples, not production deployment templates. They use fictional data and an isolated sqleng schema. The setup script drops only tables in that teaching schema; never point it at a production database. SQL Server-specific syntax is labelled in the viewer. Other engines may differ in conversion functions, locking, transaction behavior, and upsert syntax.

Continue

Next lesson: SQL for Data Engineering: Window Functions

Tags

  • SQL Server
  • T-SQL
  • Data Pipelines