Ranking & NTH Value SQL Topic exerciseMediumVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Select Exactly Two Runs Per Pipeline

Use deterministic ROW_NUMBER per pipeline and keep row_num at most 2.

  • Window functions
  • Subqueries
  • Filtering
  • Sorting

Exercise brief

Understand the request

Benchmarking coordinator A fixed-size benchmark sample requires exactly two runs from each pipeline even when the cutoff value is tied.

A fixed-size benchmark sample requires exactly two runs from each pipeline even when the cutoff value is tied. Use deterministic ROW_NUMBER per pipeline and keep row_num at most 2.

Return

  • Return pipeline_name, run_id, and rows_loaded.
  • Order by pipeline_name and row_num.

Constraints

  • Partition by pipeline_name.
  • Break throughput ties by run_id.

Data you will use

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

pipeline_runs

  • pipeline_nameTEXT
  • run_idINTEGER
  • rows_loadedINTEGER

Hints, when you need them

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

Hint 1

Exact-N and tie-inclusive top-N are different contracts.

Hint 2

ROW_NUMBER plus a stable tie-breaker produces a fixed count.

Hint 3

Filter row_num <= 2 in an outer query.

Verified SQL answer

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

Reveal solution and explanation
WITH ranked AS (SELECT run_id, pipeline_name, rows_loaded, ROW_NUMBER() OVER (PARTITION BY pipeline_name ORDER BY rows_loaded DESC, run_id) AS row_num FROM pipeline_runs) SELECT pipeline_name, run_id, rows_loaded FROM ranked WHERE row_num <= 2 ORDER BY pipeline_name, row_num;

Why this works

ROW_NUMBER intentionally resolves peers to produce an exact quota. The run_id tie-breaker makes that choice repeatable.

Success check

Exactly six rows are returned, including only two of the three customer_sync peers.

Expected result

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

pipeline_namerun_idrows_loaded
billing_rollup3011500
billing_rollup3021500
customer_sync201850
customer_sync202850
ingest_orders1021200
ingest_orders1031200

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.