The snippet library.
Small, practical examples. Search by task or narrow things down below.
Count rows satisfying separate conditions
SQL Server: SUM over CASE expressions calculates several conditional counts in one scan.
SQL Server✓ Tested
Count the rows in a table
SQL Server: COUNT(*) includes every row, including rows with NULL columns.
SQL Server✓ Tested
Create a table and insert its first row
SQL Server: Define column types and a primary key, then insert one row using an explicit column list.
SQL Server✓ Tested
Create an index for an equality filter
SQL Server: A nonunique index can support lookups on a frequently filtered column.
SQL Server✓ Tested
Create an index matching filter and ordering columns
SQL Server: Place the equality-filter column before the ordering column in this composite index.
SQL Server✓ Tested
Delete one row from a practice table
SQL Server: Restrict DELETE with a primary-key condition and verify the remaining row count.
SQL Server✓ Tested
Delete rows selected by a related table
SQL Server: A correlated EXISTS limits the delete to explicitly listed records.
SQL Server✓ Tested
Display a fallback for missing data
SQL Server: Return a supplied label when a column contains NULL.
SQL Server✓ Tested
Distinguish row count from non-null value count
SQL Server: COUNT(*) includes every row while COUNT(column) skips NULL values.
SQL Server✓ Tested
Divide an ordered result into numbered buckets
SQL Server: NTILE distributes rows across buckets; include a unique tie-breaker for deterministic assignment.
SQL Server✓ Tested
Enforce a bounded numeric range
SQL Server: A named CHECK constraint keeps numeric values inside an inclusive interval.
SQL Server✓ Tested
Enforce a relationship between two columns
SQL Server: A row-level CHECK can require a start value to be no greater than an end value.
SQL Server✓ Tested