SQL code snippets with use cases
27 ready-made code building blocks, sorted by topic.
Basics
- Hello World – Check that the database connection works and a statement gets executed.
- Constants via CTE and Type Conversion – Define recurring values such as tax rate or currency in one place instead of scattering…
- Handling NULL Safely – Replace missing values in reports with defaults and avoid division by zero.
Reporting
- Revenue per Customer – Identify the best customers for sales or reporting.
- Pivot with CASE – Show row values as columns, e.g. orders per month and status in a cross-tab.
- Combining Values into One Text – Show all products of an order in one row (e.g. for shipping lists or exports).
- Grouping by Month – Evaluate revenue or sign-ups per month for dashboards.
More snippets
- CASE WHEN – Classify values, e.g. price tiers, customer segments, or status names in a report.
- Recursive CTE as a Loop – Generate number or date series, e.g. for calendar reports without gaps.
- Function and Aggregate Function – Define a calculation such as the gross price centrally and reuse it everywhere.
- Result List and IN List – Select records from a fixed set of values, e.g. certain categories or ids.
- GROUP BY – Mapping Key to Value – Evaluate revenue, counts, or averages per category, month, or customer.
- CREATE TABLE with Constraints – Define a new data model and enforce data quality directly in the database.
- View for Recurring Queries – Define complex join logic once and reuse it in reporting or for BI tools.
- Constraint Errors and ROLLBACK – Protect several related changes so that nothing stays half-saved when an error occurs.
- Import and Export CSV – Load data from Excel/CSV or pass results on as a file.
- Customers without an Order – Find inactive customers for a reactivation email or track down orphaned records.
- Top-N per Group with ROW_NUMBER – The most expensive product per category or the latest order per customer.
- Running Total and Previous Period – Cumulative revenue over time or comparison with the previous month.
- UPSERT (ON CONFLICT) – Synchronize records: insert if new, otherwise update – without a race condition.
- UPDATE Based on Another Table – Copy values from one table to another, e.g. price changes from an import table.
- Finding and Removing Duplicates – Track down and clean up duplicate customers after an import.
- Pagination with Keyset – Load long lists (feeds, admin tables) quickly, page by page.
- Creating and Checking an Index – Speed up a slow query and prove that the index is used.
- Hierarchy with a Recursive CTE – Output category trees, org charts, or bills of materials with level and path.
- Querying JSON Columns – Store and filter flexible extra attributes (configuration, event payloads) in a single…
- Atomic Transfer Booking – Book stock or money between two records without only one side being changed.