CASE Statements & Conditional Logic SQL Topic exerciseMediumVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Emit Reusable Data Quality Flags

Create failed, SLA-breach, and unowned 1/0 flags for every event.

  • CASE expressions
  • NULL handling
  • Sorting

Exercise brief

Understand the request

Data quality engineer Downstream metrics need numeric flags that can later be summed without reinterpreting business rules.

Downstream metrics need numeric flags that can later be summed without reinterpreting business rules. Create failed, SLA-breach, and unowned 1/0 flags for every event.

Return

  • Return event_id, failed_flag, sla_breach_flag, and unowned_flag.
  • Order by event_id.

Constraints

  • Use a separate CASE expression for each flag.
  • Only count SLA breaches when target_ms is positive.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

pipeline_events

  • event_idINTEGER
  • pipeline_nameTEXT
  • status_codeTEXT
  • severityTEXT
  • actual_msINTEGER
  • target_msINTEGER
  • retry_countINTEGER
  • processed_rowsINTEGER
  • failed_rowsINTEGER
  • owner_teamTEXT
  • is_customer_facingINTEGER
  • source_systemTEXT
  • maintenance_modeINTEGER

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

Each independent attribute gets its own CASE WHEN condition THEN 1 ELSE 0 END.

Hint 2

Include target_ms > 0 in the breach flag.

Hint 3

Keep ELSE 0 so NULL predicates do not propagate NULL flags.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT event_id, CASE WHEN status_code = 'FAIL' THEN 1 ELSE 0 END AS failed_flag, CASE WHEN actual_ms > target_ms AND target_ms > 0 THEN 1 ELSE 0 END AS sla_breach_flag, CASE WHEN owner_team IS NULL THEN 1 ELSE 0 END AS unowned_flag FROM pipeline_events ORDER BY event_id;

Why this works

Numeric flags are portable and composable. Explicit ELSE 0 turns false and unknown predicates into a stable metric input while preserving each rule as an independently testable expression.

Success check

All three flags are always 0 or 1 and invalid or missing targets do not count as breaches.

Expected result

Use this output to verify values, aliases, ordering, and row count.

event_idfailed_flagsla_breach_flagunowned_flag
101000
102000
103010
104110
208001
209111
210000
303000
304010
305110

Previewing 10 of 14 expected rows. Run the query in the editor to inspect the full result.

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.