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

Model a Four-State SLA Outcome

Return Not Measured, Invalid Target, Breached, or Met in that precedence order.

  • CASE expressions
  • NULL handling
  • Sorting

Exercise brief

Understand the request

Service-level governance analyst A two-state pass/fail label would hide missing measurements and invalid targets.

A two-state pass/fail label would hide missing measurements and invalid targets. Return Not Measured, Invalid Target, Breached, or Met in that precedence order.

Return

  • Return event_id, actual_ms, target_ms, and sla_state.
  • Order by event_id.

Constraints

  • Handle NULL measurement inputs before target validation.
  • Treat actual_ms equal to target_ms as Met.

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

SQL predicates involving NULL evaluate to unknown, so handle missing values explicitly.

Hint 2

Invalid targets need their own branch before the breach comparison.

Hint 3

Once exceptions are removed, ELSE can safely mean Met.

Verified SQL answer

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

Reveal solution and explanation
SELECT event_id, actual_ms, target_ms, CASE WHEN actual_ms IS NULL OR target_ms IS NULL THEN 'Not Measured' WHEN target_ms <= 0 THEN 'Invalid Target' WHEN actual_ms > target_ms THEN 'Breached' ELSE 'Met' END AS sla_state FROM pipeline_events ORDER BY event_id;

Why this works

Production data contracts often require more than true and false. CASE makes missing, invalid, breached, and met states explicit instead of collapsing unknown data into a misleading success.

Success check

Every data-quality state remains distinct from a true SLA result.

Expected result

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

event_idactual_mstarget_mssla_state
10190100Met
102100100Met
103199100Breached
104210100Breached
208200200Met
209401200Breached
210200200Met
303NULL300Not Measured
304600300Breached
305301300Breached

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.