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

Compare Each Run with Its Predecessor

Use LAG to read the previous rows_loaded within each pipeline.

  • Window functions
  • Sorting

Exercise brief

Understand the request

Pipeline observability engineer A run timeline needs prior throughput beside the current run without collapsing source rows.

A run timeline needs prior throughput beside the current run without collapsing source rows. Use LAG to read the previous rows_loaded within each pipeline.

Return

  • Return pipeline_name, run_id, started_at, rows_loaded, and previous_rows_loaded.
  • Order chronologically by pipeline with run_id as a tie-breaker.

Constraints

  • Partition by pipeline_name.
  • Order the window by started_at and 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
  • started_atTEXT
  • rows_loadedINTEGER

Hints, when you need them

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

Hint 1

LAG reads a preceding row without a self-join.

Hint 2

Define both the reset boundary and total chronology.

Hint 3

Use LAG(rows_loaded) over pipeline_name ordered by started_at, run_id.

Verified SQL answer

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

Reveal solution and explanation
SELECT pipeline_name, run_id, started_at, rows_loaded, LAG(rows_loaded) OVER (PARTITION BY pipeline_name ORDER BY started_at, run_id) AS previous_rows_loaded FROM pipeline_runs ORDER BY pipeline_name, started_at, run_id;

Why this works

LAG preserves the run grain while exposing an adjacent value. A stable secondary ordering key prevents ambiguous predecessor selection.

Success check

The first run per pipeline has NULL and timestamp ties follow deterministic run_id order.

Expected result

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

pipeline_namerun_idstarted_atrows_loadedprevious_rows_loaded
billing_rollup3012026-06-03 08:00:001500NULL
billing_rollup3022026-06-03 09:00:0015001500
billing_rollup3032026-06-03 10:00:0013001500
billing_rollup3042026-06-03 11:00:0011001300
customer_sync2012026-06-03 09:30:00850NULL
customer_sync2022026-06-03 10:30:00850850
customer_sync2032026-06-03 11:30:00850850
customer_sync2042026-06-03 12:30:00650850
ingest_orders1012026-06-03 09:00:001000NULL
ingest_orders1022026-06-03 10:00:0012001000

Previewing 10 of 12 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.