Self-contained, runnable demonstrations of SQL Server behaviour — one folder per topic. Each folder has its own README with prerequisites, run order, and what to expect in the output.
Every topic also has a short explainer on my blog: what the problem looks like, why it happens, what fixes it, and a query to check your own server. Browse them all at SQL Server Demos on marlonribunal.com.
Built with AI assistance. The scripts, READMEs and explainers were written with the help of AI. Every result in them comes from actually running the demos on SQL Server, not from the AI. See how this was made.
You probably arrived with a problem, not a feature name. Find it below; each link is a topic that reproduces that problem on purpose and measures the fixes.
"It's fast sometimes and slow other times"
- the plan was compiled for somebody else's parameter → parameter sniffing
- only for the newest data → the ascending-key problem
- "slow in the app, fast in SSMS" → SET options and the plan cache
- a filtered index that's used in SSMS but not from the application, or error 1934 on writes → filtered indexes
- a search screen with optional filters → catch-all queries
- the same, on SQL Server 2025: what optional parameter plan optimization fixes, and where it stops → optional parameter plans
- it was fine yesterday and nothing was deployed → Query Store: plan regressions
- one query from an app you can't change takes the server down: stop it from running (SQL Server 2025) → ABORT_QUERY_EXECUTION
- on SQL Server 2022, the plan changes by itself: PSP variants, CE feedback hints, memory grant feedback → SQL Server 2022 query processing
"This query reads far more than it should"
- a function or expression on the column → non-SARGable predicates
- the parameter's type doesn't match the column → implicit conversions
- thousands of key lookups, or a scan where you expected a seek → the tipping point
- a scalar function in the query → scalar UDF inlining
- a date-partitioned table and the query reads every partition → partition elimination
- a heap that keeps getting slower to scan → forwarded records
- a columnstore table that isn't as fast or small as it should be → the delta store
- a join to a table the query takes no columns from, or a filter a
CHECKconstraint rules out, still reads the table → untrusted constraints - a columnstore range query that reads every rowgroup:
ORDER, MAXDOP, and loads after the build (SQL Server 2022, 2025) → ordered columnstore - filtering on a property inside JSON, or a JSON index that isn't used (SQL Server 2025) → the json data type
REGEXP_LIKEthat scans, misestimates, or quietly misses rows (SQL Server 2025) → regular expressions- a nearest-neighbour search over embeddings that reads every row, or a vector index that misses rows (SQL Server 2025) → vector search
- finding misspelt names:
EDIT_DISTANCE, Jaro-Winkler,SOUNDEX(SQL Server 2025) → fuzzy string matching ||returned NULL,'total=' || 1 + 2failed, or a product came out as 3628800.0000000084 (SQL Server 2025) → new T-SQL syntax traps
"The estimates in the plan are nowhere near the actual rows"
- rows newer than the statistics → ascending key
- two related columns in one
WHERE→ correlated predicates - skewed data, rare values, values that don't exist → statistics sampling
- a
#temptable vs a table variable → tempdb - a multi-statement function estimated at 1 or 100 rows, a table variable estimated at 1 → MSTVFs and table variables
"Half the transaction was saved" / "the job succeeded but the work is missing"
XACT_ABORT,TRY/CATCH, doomed transactions, errorsCATCHcan't see,RAISERRORvsTHROW, a trigger written for one row → error handling
"The totals are off by a cent" / "the report is missing a day" / "the dates are swapped"
- integer division, float, decimal and money rounding, strings cut short, datetime ranges, date formats, trailing spaces, identity overflow → data type traps
"The server is slow and I don't know where to start" / "what are we waiting on?"
- elapsed = CPU + waits, per-session and live waits,
WRITELOG,PAGEIOLATCH,LCK_M_*,SOS_SCHEDULER_YIELD, and the instance-wide numbers' noise → wait stats triage - thousands of single-use plans in the plan cache, high compilations → plan cache bloat
"Queries wait for memory" (RESOURCE_SEMAPHORE)
- grants far bigger than the data → memory grants sized by declared width
"CXPACKET is my top wait" / "small queries eat all the CPU"
- a parallel query no faster than serial, skew, the cost threshold, why a plan stays serial → parallelism
"Everything is blocked" / "we get deadlocks"
- find the session holding everyone up → blocking chains
Msg 1205, "chosen as the deadlock victim" → deadlock patterns- a big update locks the whole table → lock escalation
- on SQL Server 2025: fewer locks, no escalation, updates that stop waiting on rows they only read → optimized locking
- readers wait for writers, or
NOLOCKeverywhere → RCSI and snapshot isolation
"Duplicate rows" / "primary key violations under load" / "the counter is wrong"
- two sessions insert the same new row, or overwrite each other's update → upsert race conditions
"Page 500 of the results takes forever" / "users see the same row on two pages"
OFFSET ... FETCHon deep pages, rows repeated or lost between pages, ties in the sort, the total count → pagination: OFFSET vs keyset
"The database is too big" / "should we turn on compression?"
- ROW vs PAGE vs columnstore, the CPU it costs, data that won't compress, heaps, big documents → data compression
"Should I rebuild / add this index?"
- the maintenance job says the index is fragmented → index fragmentation
- the missing-index DMVs suggest something → missing-index suggestions
"The rollback is taking forever" / "recovery after a restart takes hours"
- instant rollback, a log that truncates under long transactions, and the version store it costs → Accelerated Database Recovery
"A tenant can see (or write) another tenant's rows" / "the admin report comes back empty"
- writes past the filter, a spoofable
SESSION_CONTEXT, leaks through unique keys and identities, the predicate that scans → row-level security
"Someone deleted the wrong rows" / "will our backups actually restore?"
- point-in-time restore to a copy, the tail-log backup,
COPY_ONLYand broken differentials, checksums → backup and restore - backups too big or too slow, and ZSTD compression on SQL Server 2025 → ZSTD backup compression
"The transaction log is full" / "the log file won't stop growing"
- no log backups, an open transaction, a shrink that won't shrink, thousands of VLFs → why is my transaction log full?
"The load is slow and the log is huge"
- bulk inserts that should be minimally logged → minimal logging
- tempdb contention, or when to use a
#temptable → tempdb - one query fills tempdb for everyone: cap it per workload group (SQL Server 2025) → tempdb space governance
Min. version is the oldest version on which every scenario runs. Where
only some scenarios need a newer version, the column says which. On an older
instance the scripts still run without error, and each scenario they can't
run is reported as SKIPPED rather than failing.
What has actually been tested. Every topic was developed on SQL Server 2022 CU25, and CI runs every topic on 2019, 2022 and 2025 on each push. A minimum of 2016 or 2017 comes from when the feature was introduced, according to Microsoft's documentation. Nothing here has been run on 2016 or 2017.
Azure SQL Database and Azure SQL Managed Instance are not tested. Many demos would need changes there. Most create and drop their own database, and several take backups to local disk. Azure SQL Database allows neither.
If you're here to see what a specific release changed:
- SQL Server 2019: scalar UDF inlining, table variable deferred compilation, Accelerated Database Recovery, row-mode memory grant feedback
- SQL Server 2022: parameter-sensitive plans, CE feedback, DOP feedback, memory grant feedback that persists, Query Store hints, ordered clustered columnstore indexes
- SQL Server 2025: optimized locking,
optional parameter plan optimization,
the json data type and JSON indexes,
regular expressions,
vector search,
fuzzy string matching,
ZSTD backup compression,
the ABORT_QUERY_EXECUTION hint,
new T-SQL syntax:
||,PRODUCTand more, tempdb space governance, ordered nonclustered columnstore, and ordered online builds
The fastest way to a scratch instance is the docker-compose.yml in this
repo. It runs SQL Server 2019, 2022 and 2025 Developer edition side by side.
cp .env.example .env # then choose your own MSSQL_SA_PASSWORD
docker compose up -d sql2022 # or sql2019, sql2025
tools/run-topic.sh tempdb # one topic, end to end
tools/run-all.sh # every topic
tools/run-topic.sh runs a topic exactly as its README says: setup, the demo,
the demo again (every demo must be re-runnable without re-running setup),
then cleanup. It reports PASS, WARN or FAIL:
- FAIL: a script raised an error, or the demo's final "anything that did not behave as predicted" result set has a row in it.
- WARN: the only rows there are documented environment caveats, such as
INCONCLUSIVE,INTERMITTENTorSKIPPED.
Every topic carries its own predictions and checks them, so a PASS means the
behaviour the README describes really happened on that instance. It isn't
just "the script ran". It defaults to the sqldemo-2022 container. Pass
another container name as a second argument, or set SQL_CONTAINER.
- The
sapassword comes fromMSSQL_SA_PASSWORD, or failing that from the container's own environment. - A passing run deletes its output. Set
KEEP_OUTPUT=1to keep it. A WARN or FAIL always keeps it, and prints where it is. - Exit status:
0passed (with or without warnings),1failed,2skipped (.ci-skip),3could not run (no container, no password, instance not ready).
tools/run-all.sh [container] runs every topic in alphabetical order and
ends with a one-line tally: passed, passed with warnings, skipped, failed. It
exits non-zero only if a topic failed.
Prefer SSMS or Azure Data Studio? Connect to localhost on the container's
host port, then open each script and run it whole (F5). Every README says
what to expect.
| Service | Container | Host port |
|---|---|---|
sql2019 |
sqldemo-2019 |
14319 |
sql2022 |
sqldemo-2022 |
14322 |
sql2025 |
sqldemo-2025 |
14325 |
Nothing in the containers is persisted. docker compose down throws the
instance away, which is what these demos assume.
- Apple Silicon (M-series Macs). The SQL Server images are x64 only. In Docker Desktop, turn on Use Rosetta for x86_64/amd64 emulation on Apple Silicon (Settings → General). The demos run under emulation, but more slowly, so timings and some CPU-based numbers will differ from the READMEs. None of the demos has been tested under emulation.
- Windows. The
tools/scripts are bash. Run them from WSL 2, with Docker Desktop's WSL integration on, or from Git Bash. Or skip the scripts and run each.sqlfile from SSMS. - Memory. Give each container about 2 GB. Running all three side by side takes about 6 GB of Docker's memory allowance.
- Your own instance. Not using Docker? Run the scripts in order from SSMS,
Azure Data Studio or
sqlcmd -I(QUOTED_IDENTIFIER ON, which several demos need).tools/run-topic.shonly drives containers.
.github/workflows/demos.yml runs every topic
through tools/run-topic.sh on SQL Server 2019, 2022 and 2025, on every push
to main, on pull requests, and on demand. Every topic runs on every version,
including versions older than it needs, so CI also checks that a version-gated
topic reports SKIPPED cleanly instead of failing. A topic that needs
something the CI containers don't have has a .ci-skip file saying so.
Today that's only parameter sniffing, which needs
WideWorldImporters.
Every topic follows the same shape, so once you've run one you know how to run the rest.
Numbered scripts, run in order.
01-setup.sql builds objects and loads data. Runs no demo of its own.
02-demo.sql the demonstration. Run the whole file — never step through it.
03-cleanup.sql restores anything setup changed, then drops everything.
Setup and demo are always separate, so it's never ambiguous which script to run when, and so you can re-run a demo without rebuilding its data.
Demos run unattended. A demo script captures its own evidence — into a results table, an Extended Events session, or both — and prints a summary at the end. You should not have to sit there reading execution plans between executions to see the point.
Everything lives in a Demo schema so cleanup can drop it wholesale without
touching the sample database. A topic that needs no sample database may create
its own database instead and drop it in cleanup — that is preferred where it
works, since it puts the demo's blast radius at zero.
Setup records what it changes. If a script alters a compatibility level, a scoped configuration, a database setting such as Query Store, or a server setting, it saves the original value first and cleanup puts it back. Each topic README states plainly what its setup mutates — including when the answer is "nothing", which is worth stating explicitly rather than leaving to inference.
Prefer a scenario that needs no setting change at all. Where two scenarios teach the same lesson, the one that does not touch engine configuration wins, even if it takes more setup data to build.
Setup changes settings, never data it did not create. Turning Query Store on for a demo is fair; clearing the query history that was already in it is not. Where a demo could take a destructive shortcut, it takes the longer route and says why in comments.
Object-scoped cache operations only — sp_recompile, or
DBCC FREEPROCCACHE with a single plan handle (plan cache
bloat removes its own plans that way), never a bare
DBCC FREEPROCCACHE. Nothing here flushes an entire instance's plan cache.
Nothing runs against production. Several topics change database-level
settings by design, and tempdb space governance
changes Resource Governor for the whole instance while it runs, then puts
it back; plan cache bloat does the same with optimize for ad hoc workloads. Use a scratch instance.
- Create
<topic-name>/— kebab-case, named for the behaviour being demonstrated, not the fix. - Add
01-setup.sql,02-demo.sql,03-cleanup.sqlfollowing the conventions above. Split further only if a topic genuinely needs it (02a,02b). - Write
<topic-name>/README.mdcovering: prerequisites, run order with rough timings, what each scenario shows, what setup changes on the database, and how to read the output. - End
02-demo.sqlwith a result set headed=== N. ANYTHING THAT DID NOT BEHAVE AS PREDICTED ===that lists every check whose verdict was wrong. That is whattools/run-topic.shand CI read. - If a scenario needs a newer version than the oldest CI runs, check the
version first and report it as
SKIPPEDthere. Don't let it error. - Run
tools/run-topic.sh <topic-name>until it reports PASS, on every version the topic claims to support. - Add a row to the Topics table above, an entry under Start from the symptom, and, if it shows a version-specific feature, a link under By version.
- Note any client-specific requirements (SSMS settings, sqlcmd fallbacks) in the topic README — not everyone runs SSMS.
Topics use Microsoft's published sample databases rather than synthetic data where possible. Individual READMEs link to the download and give the restore command.
| Database | Source |
|---|---|
| WideWorldImporters | sql-server-samples releases |
Backups are gitignored — download them yourself rather than expecting them here.
Where a sample database won't reproduce the behaviour on its own (WideWorldImporters is generated with near-uniform distributions, so it can't show data skew), the setup script manufactures the conditions deliberately and says so in comments. A demo that admits what it constructed is worth more than one claiming to have found it in the wild.
Open an issue. A demo that doesn't behave as its README says is exactly what's worth reporting. Please include:
- the output of
SELECT @@VERSION; - the topic, and the
PASS/WARN/FAILline fromtools/run-topic.shif you used it - the rows of the demo's final "ANYTHING THAT DID NOT BEHAVE AS PREDICTED"
result set. With
run-topic.sh, a WARN or FAIL keeps the full output in the folder it prints. - anything unusual about the instance: core count, memory, non-default settings, Docker on Apple Silicon
I built this repository with the help of AI: an AI coding assistant (Claude) helped write the scripts, the READMEs and the explainer pages, under my direction.
What keeps it honest is that nothing here is taken on the AI's word:
- every demo runs against a real SQL Server instance and ends by listing anything that did not behave as its README predicts
- continuous integration re-runs every topic on SQL Server 2019, 2022 and 2025 on every push
- every number in a README or explainer was copied from a real run, and each README names the build it was measured on
If you find something that's wrong anyway, please open an issue.
These scripts are provided as-is, for demonstration and educational purposes only. They have been tested in a limited, controlled environment — the specific SQL Server versions and configurations named in each topic README, and nowhere else. They are not production-ready, and they have not been validated against any other version, edition, configuration, or workload.
Run them only on a scratch instance you can afford to lose. Read every script before you run it. You are solely responsible for reviewing, testing, and deciding whether to run anything here.
To the fullest extent permitted by law, the author provides this repository WITHOUT WARRANTY OF ANY KIND, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author be liable for any claim, damages, data loss, service interruption, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with these scripts or their use.
MIT. The as-is and no-liability terms in the licence apply in addition to the disclaimer above.