Skip to main content
Datamata Studios
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.

Copy vetted SQL patterns for windows, pivots and constraints without searching forums

Experienced analysts still look up the same window frame clauses and safe dedupe patterns every quarter. A curated snippet library keeps vetted examples one click away instead of scattered bookmarks with outdated syntax. This reference loads in the browser; copying text does not upload your warehouse credentials or table names to Datamata Studios. Pair snippets with local execution in the SQLite Playground when you need to prove results on a CSV sample before change control.

Snippet workflow

  1. Browse by topic: windows, joins, DDL or data quality checks.
  2. Copy the pattern and rename tables to your schema.
  3. Format with the SQL Formatter for review-friendly layout.
  4. Execute against sample data in the SQLite Playground.

Adaptation checklist

Replace placeholder table names and partition columns explicitly. Confirm whether NULLS FIRST matches your warehouse default. Snippets that use ROW_NUMBER for dedupe assume a stable ORDER BY — pick columns that reflect business keys, not arbitrary timestamps unless that is intentional.

SQL cluster companions

Run proofs in the SQLite Playground, lay out final scripts with the SQL Formatter and seed tables from the CSV → SQL Import Helper when you need realistic rows behind the pattern. Prototype string filters in the Regex Tester when snippets extract fields from messy text columns.

Team knowledge base

When a snippet saves an incident, promote it to an internal repo with owner and dialect notes. Link warehouse ER diagrams from tickets so reviewers know which keys are legitimate. Redact customer data from playground exports attached to PRs even though browsing snippets stays local.

Adapting snippets to your dialect

Library examples target common ANSI-style SQL; translate functions when you move to BigQuery, T-SQL or PostgreSQL. Parameter placeholders differ — replace ? with named params as required. Snippets are starting points, not performance-tuned production queries. Add comments in your repo when you alter a pattern so reviewers know which catalogue version you based work on. Bookmark snippets you use weekly and pair them with the formatter so shared examples stay readable in code review.

Review before copy-paste

Snippets illustrate patterns — they are not tuned for your table sizes or indexes. Read each statement for cartesian products, missing filters and dialect-specific functions before you run against shared environments. Pair with the SQL Formatter so diffs in code review stay readable when you adapt a catalogue example.

Related Utilities

Same hub cluster

SQL and tabular data

Format queries, build IN lists, move between CSV and SQL and strip duplicate lines before you load data.

When to use this cluster: Use this cluster when you are shaping extracts, IN lists or deduped rows before you paste into a warehouse client or migration PR.

Open cluster on hub
SQL Snippet Library | Datamata Studios