

- Description
- Test tubes
- Source
- B.Lachner · original page
- Licence
- CC0 Public domain
Examples: procedural versus set-based
Six cases, side by side, with their pitfalls and their equivalence check.
In brief
- Six cases: running total, update, deduplication, aggregated text, calendar, islands.
- Same structure: problem statement, data, two versions, pitfalls, verification.
- Lookup table: "when a loop does X, think of Y".
Six common cases where row-by-row processing is tempting, each presented with the same structure: problem statement, data set, procedural version and set-based version side by side, expected result, pitfalls, variants and equivalence check.
Each example is self-contained: create the tables in a test database, run the procedural version, then the set-based version, and compare. The last block of each page verifies that both versions return the same result. To quantify the differences, see Measuring seriously.
The six examples#
A lookup table#
When a loop does X, look for the set-based equivalent of X:
| If the loop does… | Think of… | Example |
|---|---|---|
| A running total or a current state | Window function (SUM() OVER, LAG) | Running total |
| A per-row lookup in another table | Join (UPDATE … FROM … JOIN) | Update by reference |
| An existence or duplicate test | EXISTS, ROW_NUMBER | Deduplication |
| A concatenation per group | STRING_AGG (or FOR XML PATH) | String aggregation |
| A row generation | Numbers table, GENERATE_SERIES | Calendar |
| Sequence tracking ("the previous row") | Difference with ROW_NUMBER, or LAG + running sum | Islands |
Going further#
These six examples are patterns. For entire workloads that accumulate several errors, see the disaster cases, and the approach that avoids them.
How to read these pages#
- The procedural code is written correctly: we compare valid versions, not a straw-man counterexample.
- No performance figures are put forward: the gaps depend on the environment. The script on the Measuring seriously page lets you measure them on your own system.
- The pitfalls are so many reasons to verify equivalence between the old and the new processing.