The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate each group’s integer percentage of the total
SQL Server: Multiply before division and protect against a zero denominator.
SQL Server✓ Tested
Calculate each group’s numeric spread
SQL Server: Subtract MIN from MAX to report the difference between extremes.
SQL Server✓ Tested
Catch a T-SQL error
Handle an expected conversion error in TRY/CATCH.
TRY CATCH✓ Tested
Combine results while retaining duplicates
SQL Server: UNION ALL does not spend work removing equal rows.
SQL Server✓ Tested
Combine text values with a separator
SQL Server: Use the concatenation operator supported by the selected SQL dialect.
SQL Server✓ Tested
Commit multiple related changes together
SQL Server: The first transaction prepares the fixtures. The second commits both updates as one unit.
SQL Server✓ Tested
Compare a row with its own group average
SQL Server: A correlated aggregate computes a different comparison value for each group.
SQL Server✓ Tested
Compute an integer weighted average
SQL Server: Multiply before summing and guard a zero total weight with NULLIF.
SQL Server✓ Tested
Convert text without raising a conversion error
Return NULL when a numeric conversion fails.
TRY_CONVERT✓ Tested
Copy selected rows into another table
SQL Server: INSERT SELECT performs a set-based copy with an explicit destination column list.
SQL Server✓ Tested
Count day boundaries between dates
Compare date values with DATEDIFF.
DATEDIFF✓ Tested
Count distinct values within a result
SQL Server: COUNT DISTINCT counts distinct non-null values.
SQL Server✓ Tested