Back to Utilities
CODE SNIPPETS

Snippet Library

Grab trusted code snippets for common tasks. Copy, tweak and run in the SQLite Playground.

Create table with constraints
Primary key, unique email and created_at default
sql
1CREATE TABLE users (
2 id INTEGER PRIMARY KEY,
3 email TEXT UNIQUE NOT NULL,
4 name TEXT,
5 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
6);
schemasqlite
Upsert by primary key (SQLite 3.35+)
Insert or update existing row with ON CONFLICT
sql
1INSERT INTO users (id, email, name)
2VALUES (1, 'ada@example.com', 'Ada')
3ON CONFLICT(id) DO UPDATE SET
4 email = excluded.email,
5 name = excluded.name;
dmlupsert
Window function rank
Rank users by score per cohort
sql
1SELECT
2 user_id,
3 cohort,
4 score,
5 RANK() OVER (PARTITION BY cohort ORDER BY score DESC) AS cohort_rank
6FROM leaderboard;
analyticswindow
Pivot via conditional aggregation
Turn rows into columns with aggregates
sql
1SELECT
2 user_id,
3 SUM(CASE WHEN event = 'signup' THEN 1 ELSE 0 END) AS signups,
4 SUM(CASE WHEN event = 'purchase' THEN 1 ELSE 0 END) AS purchases
5FROM events
6GROUP BY user_id;
pivotanalytics
Recursive CTE for hierarchy
Walk a parent/child tree
sql
1WITH RECURSIVE tree AS (
2 SELECT id, parent_id, name, 0 AS depth
3 FROM categories
4 WHERE parent_id IS NULL
5 UNION ALL
6 SELECT c.id, c.parent_id, c.name, depth + 1
7 FROM categories c
8 JOIN tree t ON c.parent_id = t.id
9)
10SELECT * FROM tree;
ctehierarchy
Top-N per group
Grab the best 3 scores per cohort
sql
1SELECT * FROM (
2 SELECT
3 user_id,
4 cohort,
5 score,
6 ROW_NUMBER() OVER (PARTITION BY cohort ORDER BY score DESC) AS rnk
7 FROM leaderboard
8) ranked
9WHERE rnk <= 3;
windowtopn
Detect duplicates
Emails that appear more than once
sql
1SELECT email, COUNT(*) AS occurrences
2FROM users
3GROUP BY email
4HAVING COUNT(*) > 1;
data-qualitydedupe
JSON extraction (SQLite)
Pull values out of JSON columns
sql
1SELECT
2 json_extract(payload, '$.user.id') AS user_id,
3 json_extract(payload, '$.event') AS event
4FROM audit_log;
jsonsqlite
Running total (cumulative sum)
Cumulative revenue by date using window function
sql
1SELECT
2 event_date,
3 revenue,
4 SUM(revenue) OVER (ORDER BY event_date ROWS UNBOUNDED PRECEDING) AS running_total
5FROM daily_revenue;
windowanalytics
7-day moving average
Smooth metrics with a window avg
sql
1SELECT
2 event_date,
3 metric_value,
4 AVG(metric_value) OVER (
5 ORDER BY event_date
6 ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
7 ) AS moving_avg_7d
8FROM daily_metrics;
windowanalyticstime-series
Lag/Lead for period-over-period
Compare this week vs last week
sql
1SELECT
2 week_start,
3 revenue,
4 LAG(revenue, 1) OVER (ORDER BY week_start) AS prev_week_revenue,
5 ROUND(
6 100.0 * (revenue - LAG(revenue, 1) OVER (ORDER BY week_start))
7 / NULLIF(LAG(revenue, 1) OVER (ORDER BY week_start), 0), 2
8 ) AS pct_change
9FROM weekly_revenue;
windowanalyticslag
Date range filter (last N days)
Filter rows to the last 30 days
sql
1SELECT *
2FROM events
3WHERE created_at >= DATE('now', '-30 days')
4 AND created_at < DATE('now');
filterdatetime-series
Cohort retention analysis
Count users active in their signup month vs later months
sql
1WITH cohorts AS (
2 SELECT
3 user_id,
4 DATE_TRUNC('month', first_seen) AS cohort_month
5 FROM users
6),
7activity AS (
8 SELECT
9 user_id,
10 DATE_TRUNC('month', event_date) AS activity_month
11 FROM user_events
12)
13SELECT
14 c.cohort_month,
15 a.activity_month,
16 COUNT(DISTINCT c.user_id) AS retained_users,
17 DATEDIFF('month', c.cohort_month, a.activity_month) AS months_since_signup
18FROM cohorts c
19JOIN activity a ON c.user_id = a.user_id
20GROUP BY 1, 2
21ORDER BY 1, 4;
cohortretentionanalytics
Percentile buckets (ntile)
Split rows into quartiles or deciles
sql
1SELECT
2 user_id,
3 revenue,
4 NTILE(4) OVER (ORDER BY revenue DESC) AS revenue_quartile,
5 NTILE(10) OVER (ORDER BY revenue DESC) AS revenue_decile
6FROM customer_revenue;
windowanalyticspercentile
Find rows with NULL in any column
Data quality: detect NULLs across multiple columns
sql
1SELECT *
2FROM orders
3WHERE customer_id IS NULL
4 OR amount IS NULL
5 OR status IS NULL
6 OR created_at IS NULL;
data-qualitynull
How to use
  • Copy a snippet and tweak identifiers to match your schema.
  • Paste into the SQLite Playground to validate quickly.
  • Combine snippets to build repeatable migrations for your stack.

User Guide

Overview

The SQL Snippet Library is a curated collection of battle-tested SQL patterns for common database tasks. Each snippet is copy-ready, tagged for discoverability and optimized for SQLite (most patterns work in PostgreSQL/MySQL too).

Instead of googling "SQL upsert syntax" for the 10th time, grab the snippet and adapt it to your schema in seconds.

When to Use This Tool

Use the snippet library when:

  • You need a quick reference for common SQL patterns
  • Learning advanced SQL techniques like window functions and CTEs
  • Building prototypes and need reliable starting code
  • Avoiding syntax errors by using proven patterns
  • Teaching SQL to colleagues or students with concrete examples
  • Looking for performance-optimized alternatives to naive queries

How to Use

1. Browse by Tag

Snippets are tagged: schema, dml, analytics, data-quality, json. Filter by clicking tags to find relevant patterns quickly.

2. Copy to Clipboard

Click the "Copy" button on any snippet. The code is ready to paste into the SQLite Playground, your IDE (VS Code, DataGrip) or production scripts.

3. Adapt to Your Schema

Replace placeholder names with your actual table and column names:

sql
1-- Original snippet:
2SELECT user_id, COUNT(*) FROM events GROUP BY user_id;
3
4-- Your version:
5SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id;

4. Test in Playground

Paste the snippet into the SQLite Playground to test it immediately with sample data.

Snippet Categories

  • schema: Table creation, constraints, primary keys, unique constraints
  • dml: Inserts, updates, deletes, upserts (INSERT ... ON CONFLICT)
  • analytics: Aggregations, window functions, pivots, Top-N per group
  • data-quality: Duplicate detection, NULL handling, data validation
  • json: JSON extraction and querying (SQLite 3.38+)
  • cte: Common Table Expressions, recursive queries for hierarchies

Popular Snippets

Upsert by Primary Key

Insert a row or update it if the primary key already exists:

sql
1INSERT INTO users (id, email, name)
2VALUES (1, 'ada@example.com', 'Ada')
3ON CONFLICT(id) DO UPDATE SET
4 email = excluded.email,
5 name = excluded.name;

Window Function - Ranking

Rank users by score within each cohort:

sql
1SELECT
2 user_id,
3 cohort,
4 score,
5 RANK() OVER (PARTITION BY cohort ORDER BY score DESC) AS cohort_rank
6FROM leaderboard;

Top-N per Group

Get the best 3 scores per cohort:

sql
1SELECT * FROM (
2 SELECT
3 user_id,
4 cohort,
5 score,
6 ROW_NUMBER() OVER (PARTITION BY cohort ORDER BY score DESC) AS rnk
7 FROM leaderboard
8) ranked
9WHERE rnk <= 3;

Detect Duplicates

Find emails that appear multiple times:

sql
1SELECT email, COUNT(*) AS occurrences
2FROM users
3GROUP BY email
4HAVING COUNT(*) > 1;

Tips and Best Practices

  • Test First: Always test snippets in a development environment before running in production.
  • Add Indexes: For snippets with WHERE clauses or window functions, create indexes on relevant columns for better performance.
  • Check Dialect: Some patterns are SQLite-specific (e.g., ON CONFLICT). For MySQL, use ON DUPLICATE KEY UPDATE instead.
  • Use EXPLAIN: Run EXPLAIN QUERY PLAN before your query to check if indexes are being used efficiently.
  • Avoid SELECT *: Specify columns explicitly to reduce I/O and improve query performance.

Related Utilities