SQLancer
📖 Production Query Snippets

Database Query Cookbook

100 copy-pasteable SQL and database query recipes across 10 engines. Production-ready solutions for upserts, window analytics, JSON queries, and performance tuning.

Select Engine:
🐘 PostgreSQL

1. Upsert Record with ON CONFLICT

Insert a new row or update existing row columns when primary key conflicts.

INSERT INTO user_stats (user_id, login_count, last_login)
VALUES (42, 1, NOW())
ON CONFLICT (user_id) DO UPDATE SET
  login_count = user_stats.login_count + 1,
  last_login = EXCLUDED.last_login;
#upsert#conflict#insert
🐘 PostgreSQL

2. Query Nested JSONB Properties

Filter rows based on deeply nested JSON key values using arrow operators.

SELECT id, metadata->>'title' AS title
FROM documents
WHERE metadata @> '{"status": "published", "author": "Alex"}';
#jsonb#json#query
🐘 PostgreSQL

3. Group Values into Delimited List

Aggregate text rows into a single comma-separated list per group.

SELECT department_id,
       STRING_AGG(first_name, ', ' ORDER BY first_name) AS team_members
FROM employees
GROUP BY department_id;
#string_agg#group_by#aggregate
🐘 PostgreSQL

4. Window Functions for Lead/Lag Analysis

Compute previous and next period row values without self-joins.

SELECT sale_date, amount,
       LAG(amount, 1) OVER (ORDER BY sale_date) AS prev_amount,
       amount - LAG(amount, 1) OVER (ORDER BY sale_date) AS diff
FROM daily_sales;
#window#lag#analytics
🐘 PostgreSQL

5. Create Range Partitioned Table

Divide large tables into date range partitions for query pruning.

CREATE TABLE sales_log (
  id BIGSERIAL,
  sale_date DATE NOT NULL,
  amount NUMERIC(10,2)
) PARTITION BY RANGE (sale_date);

CREATE TABLE sales_2026_q1 PARTITION OF sales_log
  FOR VALUES FROM ('2026-01-01') TO ('2026-04-01');
#partition#ddl#scaling
🐘 PostgreSQL

6. Full-Text Search with tsvector

Perform natural language text matching with rank scoring.

SELECT title, ts_rank(to_tsvector('english', body), query) AS rank
FROM articles, to_tsquery('english', 'database & performance') query
WHERE to_tsvector('english', body) @@ query
ORDER BY rank DESC;
#fts#search#text
🐘 PostgreSQL

7. Recursive CTE for Hierarchy Trees

Traverse employee-manager organizational hierarchies recursively.

WITH RECURSIVE org_tree AS (
  SELECT id, name, manager_id, 1 AS level
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, o.level + 1
  FROM employees e JOIN org_tree o ON e.manager_id = o.id
)
SELECT * FROM org_tree ORDER BY level, id;
#cte#recursive#hierarchy
🐘 PostgreSQL

8. Find Running & Blocked Queries

Inspect active database locks and long-running client sessions.

SELECT pid, now() - query_start AS duration, query, state
FROM pg_stat_activity
WHERE state != 'idle' AND now() - query_start > INTERVAL '5 seconds'
ORDER BY duration DESC;
#dba#monitoring#locks
🐘 PostgreSQL

9. Check Size of Tables & Indexes

Retrieve total disk space consumption for database tables.

SELECT relname AS table_name,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
#dba#storage#size
🐘 PostgreSQL

10. Generate Date Ranges with generate_series

Create continuous date series tables for zero-filling missing trend data.

SELECT generate_series(
  '2026-01-01'::date,
  '2026-01-07'::date,
  '1 day'::interval
)::date AS calendar_day;
#generate_series#utility#dates
🐎 MySQL

1. Upsert with ON DUPLICATE KEY UPDATE

Insert new record or update existing values on duplicate primary key.

INSERT INTO user_scores (user_id, score)
VALUES (101, 50)
ON DUPLICATE KEY UPDATE score = score + 50;
#upsert#insert#duplicate
🐎 MySQL

2. Concatenate Group Values with GROUP_CONCAT

Combine group text values into a single comma-separated string.

SELECT department_id,
       GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') AS team
FROM employees
GROUP BY department_id;
#group_concat#string#aggregate
🐎 MySQL

3. Paginate Results with LIMIT & OFFSET

Retrieve paginated query output rows efficiently.

SELECT id, title, price
FROM products
WHERE is_active = 1
ORDER BY created_at DESC
LIMIT 10 OFFSET 20;
#pagination#limit#offset
🐎 MySQL

4. Find Duplicate Records

Identify duplicate row entries based on unique column combinations.

SELECT email, COUNT(*)
FROM accounts
GROUP BY email
HAVING COUNT(*) > 1;
#duplicates#having#group_by
🐎 MySQL

5. Format Dates with DATE_FORMAT

Convert raw DATETIME values into readable formatted strings.

SELECT order_id,
       DATE_FORMAT(order_date, '%W, %M %e, %Y') AS formatted_date
FROM orders;
#date#formatting#time
🐎 MySQL

6. Extract Values from JSON Columns

Parse nested JSON object values directly inside MySQL queries.

SELECT id, JSON_UNQUOTE(JSON_EXTRACT(attributes, '$.color')) AS color
FROM inventory
WHERE JSON_EXTRACT(attributes, '$.in_stock') = true;
#json#extract#nosql
🐎 MySQL

7. Rank Rows with DENSE_RANK()

Compute sales ranking for employees across departments.

SELECT employee_id, dept_id, revenue,
       DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY revenue DESC) AS rank_in_dept
FROM sales_rep;
#window#rank#dense_rank
🐎 MySQL

8. Inspect Running Queries with SHOW PROCESSLIST

Monitor active threads and terminate stuck database connections.

-- View active queries
SHOW FULL PROCESSLIST;

-- Kill stuck process (replace 1234 with ID)
-- KILL 1234;
#dba#monitoring#process
🐎 MySQL

9. Reset AUTO_INCREMENT Counter

Re-anchor auto-increment key starting value.

ALTER TABLE orders AUTO_INCREMENT = 10000;
#auto_increment#ddl#table
🐎 MySQL

10. Analyze Query Execution Plan

Evaluate query indexing and row scan costs using EXPLAIN FORMAT=JSON.

EXPLAIN FORMAT=JSON
SELECT * FROM customers c
JOIN orders o ON c.id = o.customer_id
WHERE c.country = 'USA';
#explain#performance#dba
ðŸŠķ SQLite

1. Create In-Memory SQLite Database

Initialize zero-latency temporary in-memory storage.

-- Connect string: :memory:
CREATE TABLE temp_cache (
  key TEXT PRIMARY KEY,
  value TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
#memory#sqlite#init
ðŸŠķ SQLite

2. Enable High-Speed WAL Mode

Switch SQLite journal mode to WAL for concurrent read/write performance.

PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
#wal#pragma#performance
ðŸŠķ SQLite

3. Inspect Table Schema Metadata

Retrieve column definitions and data types using PRAGMA.

PRAGMA table_info('users');
#pragma#schema#metadata
ðŸŠķ SQLite

4. Create Full-Text Search Table (FTS5)

Build high-speed text search index over documents.

CREATE VIRTUAL TABLE docs_fts USING fts5(title, content);

-- Insert & query
INSERT INTO docs_fts(title, content) VALUES ('SQL Guide', 'Learn relational database queries.');
SELECT * FROM docs_fts WHERE docs_fts MATCH 'relational OR database';
#fts5#search#virtual
ðŸŠķ SQLite

5. SQLite Upsert with ON CONFLICT

Handle primary key collisions with update clauses.

INSERT INTO settings (key, val) VALUES ('theme', 'dark')
ON CONFLICT(key) DO UPDATE SET val = excluded.val;
#upsert#conflict#sqlite
ðŸŠķ SQLite

6. Parse JSON with json_extract()

Extract properties from JSON text strings.

SELECT id, json_extract(data, '$.user.name') AS name
FROM events
WHERE json_extract(data, '$.active') = 1;
#json#extract#sqlite
ðŸŠķ SQLite

7. Reclaim Disk Space with VACUUM

Defragment single-file database storage.

VACUUM;
#vacuum#maintenance#size
ðŸŠķ SQLite

8. Attach External Database File

Query tables across separate SQLite database files.

ATTACH DATABASE 'archive.db' AS archive;
SELECT * FROM main.orders JOIN archive.old_orders USING(id);
#attach#multi-db#file
ðŸŠķ SQLite

9. Format Date & Time Modifiers

Manipulate timestamps using built-in datetime helpers.

SELECT datetime('now', 'start of month', '+1 month', '-1 day');
#datetime#dates#helpers
ðŸŠķ SQLite

10. Enable Foreign Key Enforcement

Turn on foreign key constraint checking.

PRAGMA foreign_keys = ON;
#foreign_keys#pragma#integrity
ðŸ”ī Oracle Database

1. Paginate Results with FETCH FIRST N ROWS

Standard ANSI pagination syntax in modern Oracle 12c+.

SELECT employee_id, first_name, salary
FROM employees
ORDER BY salary DESC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
#pagination#oracle#fetch
ðŸ”ī Oracle Database

2. Handle NULLs with NVL / NVL2

Substitute default value when expressions return NULL.

SELECT first_name, NVL(commission_pct, 0) AS commission,
       NVL2(commission_pct, 'Commissioned', 'Salaried') AS pay_type
FROM employees;
#nvl#null#oracle
ðŸ”ī Oracle Database

3. Query Hierarchical Trees with CONNECT BY

Traverse parent-child org chart relationships.

SELECT LEVEL, employee_id, last_name, manager_id
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;
#connect_by#hierarchy#tree
ðŸ”ī Oracle Database

4. Concatenate Rows with LISTAGG

Aggregate group strings with specified delimiter.

SELECT department_id,
       LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY last_name) AS team
FROM employees
GROUP BY department_id;
#listagg#string#aggregate
ðŸ”ī Oracle Database

5. Generate Identity Sequence Values

Create sequence generator and fetch NEXTVAL.

CREATE SEQUENCE order_seq START WITH 1000 INCREMENT BY 1;

-- Usage in INSERT:
INSERT INTO orders (id, total) VALUES (order_seq.NEXTVAL, 150.00);
#sequence#nextval#identity
ðŸ”ī Oracle Database

6. Flashback Query Past Data State

Inspect deleted table rows at historical timestamp.

SELECT * FROM employees AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '15' MINUTE)
WHERE department_id = 20;
#flashback#history#recovery
ðŸ”ī Oracle Database

7. Upsert with MERGE INTO

Synchronize data using ANSI standard MERGE statement.

MERGE INTO target_table t
USING source_table s ON (t.id = s.id)
WHEN MATCHED THEN
  UPDATE SET t.val = s.val
WHEN NOT MATCHED THEN
  INSERT (id, val) VALUES (s.id, s.val);
#merge#upsert#oracle
ðŸ”ī Oracle Database

8. Transform Rows with PIVOT

Pivot department totals into cross-tab output columns.

SELECT * FROM (
  SELECT department_id, salary FROM employees
)
PIVOT (
  SUM(salary) FOR department_id IN (10 AS D10, 20 AS D20, 30 AS D30)
);
#pivot#analytics#cross-tab
ðŸ”ī Oracle Database

9. View Current Session Memory

Check current connected session SGA and PGA consumption.

SELECT name, value FROM v$mystat m JOIN v$statname n USING (statistic#)
WHERE n.name LIKE '%memory%';
#dba#memory#stats
ðŸ”ī Oracle Database

10. Create Materialized View

Build pre-computed query snapshot view with auto-refresh.

CREATE MATERIALIZED VIEW dept_summary
BUILD IMMEDIATE REFRESH COMPLETE ON DEMAND
AS SELECT department_id, COUNT(*) cnt, SUM(salary) total FROM employees GROUP BY department_id;
#materialized_view#performance#ddl
ðŸ’ŧ Microsoft SQL Server

1. Select Top N Records with TOP

Restrict result set size using TOP clause.

SELECT TOP (10) order_id, customer_id, total_amount
FROM dbo.Orders
ORDER BY order_date DESC;
#top#limit#tsql
ðŸ’ŧ Microsoft SQL Server

2. Correlated Subquery with CROSS APPLY

Join top correlated record per parent row.

SELECT c.CustomerID, c.CompanyName, o.OrderID, o.OrderDate
FROM dbo.Customers c
CROSS APPLY (
  SELECT TOP (1) OrderID, OrderDate
  FROM dbo.Orders
  WHERE CustomerID = c.CustomerID
  ORDER BY OrderDate DESC
) o;
#cross_apply#apply#tsql
ðŸ’ŧ Microsoft SQL Server

3. Safe Type Conversion with TRY_CAST

Convert text strings to numbers safely without throwing runtime errors.

SELECT RawValue,
       TRY_CAST(RawValue AS INT) AS CleanInteger
FROM dbo.StagingData
WHERE TRY_CAST(RawValue AS INT) IS NOT NULL;
#try_cast#conversion#error_handling
ðŸ’ŧ Microsoft SQL Server

4. Aggregate Text with STRING_AGG

Combine group text values into delimited string.

SELECT DepartmentID,
       STRING_AGG(FirstName, ', ') WITHIN GROUP (ORDER BY FirstName) AS EmployeeList
FROM dbo.Employees
GROUP BY DepartmentID;
#string_agg#tsql#aggregate
ðŸ’ŧ Microsoft SQL Server

5. Create & Drop Local Temp Table (#table)

Store temporary intermediate results.

CREATE TABLE #MonthlyStats (
  MonthID INT,
  TotalRev DECIMAL(18,2)
);

INSERT INTO #MonthlyStats VALUES (1, 50000.00);
SELECT * FROM #MonthlyStats;
DROP TABLE #MonthlyStats;
#temp_table#session#tsql
ðŸ’ŧ Microsoft SQL Server

6. Synchronize Data with MERGE

Execute UPSERT logic matching source and target tables.

MERGE INTO dbo.TargetUsers AS t
USING dbo.SourceUsers AS s ON (t.UserID = s.UserID)
WHEN MATCHED THEN
  UPDATE SET t.Email = s.Email
WHEN NOT MATCHED THEN
  INSERT (UserID, Email) VALUES (s.UserID, s.Email);
#merge#upsert#tsql
ðŸ’ŧ Microsoft SQL Server

7. Check Index Fragmentation Levels

Retrieve DMV fragmentation statistics to optimize slow indexes.

SELECT object_name(object_id) AS TableName, index_id, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED')
WHERE avg_fragmentation_in_percent > 10
ORDER BY avg_fragmentation_in_percent DESC;
#dba#index#fragmentation
ðŸ’ŧ Microsoft SQL Server

8. Dynamic Reporting with PIVOT

Rotate unique row values into column headers.

SELECT Year, [1] AS Jan, [2] AS Feb
FROM (
  SELECT YEAR(OrderDate) AS Year, MONTH(OrderDate) AS Month, Total
  FROM dbo.Orders
) AS Src
PIVOT (
  SUM(Total) FOR Month IN ([1], [2])
) AS pvt;
#pivot#analytics#reporting
ðŸ’ŧ Microsoft SQL Server

9. Compare Next Order with LEAD()

Fetch subsequent record value within customer partition.

SELECT CustomerID, OrderDate, TotalAmount,
       LEAD(OrderDate, 1) OVER (PARTITION BY CustomerID ORDER BY OrderDate) AS NextOrderDate
FROM dbo.Orders;
#window#lead#analytics
ðŸ’ŧ Microsoft SQL Server

10. Allow Explicit Identity Insert

Override automatic identity constraint for data migration.

SET IDENTITY_INSERT dbo.Customers ON;
INSERT INTO dbo.Customers (CustomerID, CompanyName) VALUES (999, 'Migrated Co');
SET IDENTITY_INSERT dbo.Customers OFF;
#identity#insert#tsql
🍃 MongoDB

1. Multi-Stage Aggregation Pipeline ($match & $group)

Filter, group, and calculate totals over document collections.

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
      _id: "$customerId",
      totalSpent: { $sum: "$amount" },
      orderCount: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } }
]);
#aggregation#pipeline#group
🍃 MongoDB

2. Left Outer Join Collections ($lookup)

Join related documents from secondary collection.

db.orders.aggregate([
  { $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userInfo"
  }},
  { $unwind: "$userInfo" }
]);
#lookup#join#unwind
🍃 MongoDB

3. Update Document with Upsert Option

Modify matching document or insert new object if missing.

db.users.updateOne(
  { email: "alex@example.com" },
  { 
    $set: { name: "Alex", lastActive: new Date() },
    $inc: { loginCount: 1 }
  },
  { upsert: true }
);
#update#upsert#crud
🍃 MongoDB

4. Text Search Index & Query

Create text index and run natural language searches.

db.articles.createIndex({ title: "text", content: "text" });

db.articles.find(
  { $text: { $search: "database query optimization" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });
#text#search#index
🍃 MongoDB

5. Geospatial Near Location Search ($near)

Find documents near geographical coordinates.

db.places.createIndex({ location: "2dsphere" });

db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
      $maxDistance: 5000
    }
  }
});
#geo#2dsphere#spatial
🍃 MongoDB

6. Push Element to Array Field ($push)

Add unique element to document array field.

db.users.updateOne(
  { _id: ObjectId("60d5ec49f1a2c80015f8e123") },
  { $addToSet: { tags: "premium" } }
);
#array#push#update
🍃 MongoDB

7. Build Compound Index Background

Create multi-field index without locking write operations.

db.logs.createIndex(
  { status: 1, timestamp: -1 },
  { background: true }
);
#index#compound#performance
🍃 MongoDB

8. Auto-Expire Documents with TTL Index

Set automatic document deletion after expiration interval.

db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
);
#ttl#index#expire
🍃 MongoDB

9. Enforce Document JSON Schema

Add strict structural validation rules to collection.

db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "price"],
      properties: {
        name: { bsonType: "string" },
        price: { bsonType: "double", minimum: 0 }
      }
    }
  }
});
#schema#validation#ddl
🍃 MongoDB

10. Inspect Aggregation Plan Execution

Inspect query execution statistics using explain().

db.orders.explain("executionStats").find({ status: "pending" });
#explain#performance#stats
ðŸ”ī Redis

1. Cache Value with Expiration (SET EX)

Store key-value pair in cache with 60-second TTL expiration.

SET user:42:session "eyJhbGciOiJIUzI1..." EX 60;
#cache#ttl#string
ðŸ”ī Redis

2. Store User Profile Object in Hash (HSET)

Manage structured fields inside a single Redis Hash key.

HSET user:1001 name "Alex" email "alex@dev.com" logins 5;
HGETALL user:1001;
#hash#object#hset
ðŸ”ī Redis

3. API Rate Limiter with INCR & EXPIRE

Limit client request count to 100 per minute.

MULTI;
INCR rate:client:192.168.1.1:minute;
EXPIRE rate:client:192.168.1.1:minute 60;
EXEC;
#rate_limit#incr#transaction
ðŸ”ī Redis

4. Real-Time Leaderboard with Sorted Set (ZADD)

Rank gaming players dynamically by score.

ZADD leaderboard 1500 "PlayerA" 2300 "PlayerB" 1800 "PlayerC";
-- Get top 3 players:
ZREVRANGE leaderboard 0 2 WITHSCORES;
#zset#leaderboard#ranking
ðŸ”ī Redis

5. Publish Message to Channel (PUBLISH)

Broadcast real-time message to connected channel subscribers.

-- In Publisher:
PUBLISH updates:news "New article published!";

-- In Subscriber:
-- SUBSCRIBE updates:news;
#pubsub#channel#messaging
ðŸ”ī Redis

6. Producer-Consumer Task Queue (LPUSH & RPOP)

Implement high-speed background job processing queue.

LPUSH queue:jobs '{"task": "send_email", "id": 99}';
-- In worker process:
BRPOP queue:jobs 5;
#queue#list#brpop
ðŸ”ī Redis

7. Spatial Distance Lookup (GEOADD & GEODIST)

Store geospatial coordinates and compute distance.

GEOADD locations -73.9857 40.7484 "EmpireState" -73.9654 40.7829 "CentralPark";
GEODIST locations EmpireState CentralPark km;
#geo#spatial#geodist
ðŸ”ī Redis

8. Unique Cardinality Count (PFADD)

Count millions of unique daily visitors consuming minimal memory (~12KB).

PFADD uv:2026-01-01 "user_ip_1" "user_ip_2" "user_ip_1";
PFCOUNT uv:2026-01-01;
#hyperloglog#pfcount#cardinality
ðŸ”ī Redis

9. Atomic Inventory Decr with Lua Script

Execute safe stock decrement without concurrency race conditions.

EVAL "if redis.call('get', KEYS[1]) > ARGV[1] then return redis.call('decrby', KEYS[1], ARGV[1]) else return 0 end" 1 stock:item:5 1;
#lua#script#atomic
ðŸ”ī Redis

10. Inspect Memory Consumption

Monitor peak RAM usage and key eviction stats.

INFO memory;
#dba#memory#info
❄ïļ Snowflake

1. Filter Window Results with QUALIFY

Filter window function outputs directly without CTE subqueries.

SELECT employee_id, department, salary,
       ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees
QUALIFY rank = 1;
#qualify#window#snowflake
❄ïļ Snowflake

2. Zero-Copy Clone Production Database

Create instant zero-storage metadata database snapshot.

CREATE DATABASE prod_dev_sandbox CLONE production_db;
#clone#database#utility
❄ïļ Snowflake

3. Time Travel Query Data State

Query table data as it existed prior to an accidental drop or update.

SELECT * FROM orders AT(OFFSET => -60*5); -- 5 mins ago
-- Or by Query ID:
-- SELECT * FROM orders BEFORE(STATEMENT => '8e5d0b9a-0001-0000-0000-000000000000');
#time_travel#recovery#history
❄ïļ Snowflake

4. Parse JSON VARIANT Fields

Extract values directly from JSON variant columns.

SELECT raw_payload:user.id::INT AS user_id,
       raw_payload:user.email::STRING AS email
FROM events_stage
WHERE raw_payload:event_type = 'signup';
#variant#json#semi-structured
❄ïļ Snowflake

5. Load Stage Parquet Files with COPY INTO

Bulk load external S3 cloud files into table.

COPY INTO target_table
FROM @my_s3_stage/data/
FILE_FORMAT = (TYPE = 'PARQUET')
ON_ERROR = 'CONTINUE';
#copy_into#stage#ingestion
❄ïļ Snowflake

6. Pivot Rows to Columns

Transform query row values into dynamic reporting columns.

SELECT * FROM sales_summary
PIVOT (SUM(amount) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'))
ORDER BY year;
#pivot#analytics#transform
❄ïļ Snowflake

7. Resize & Suspend Virtual Warehouse

Dynamically alter warehouse compute capacity.

ALTER WAREHOUSE analytics_wh SET WAREHOUSE_SIZE = 'MEDIUM' AUTO_SUSPEND = 300;
#warehouse#dba#compute
❄ïļ Snowflake

8. Undrop Accidental Deleted Table

Restore dropped table instantly with zero data loss.

UNDROP TABLE orders;
#undrop#recovery#safety
❄ïļ Snowflake

9. Unpack JSON Arrays with FLATTEN

Deconstruct JSON arrays into individual output rows.

SELECT id, f.value::STRING AS tag
FROM articles,
LATERAL FLATTEN(input => metadata:tags) f;
#flatten#array#variant
❄ïļ Snowflake

10. Query Cached Result Set

Reuse query result cache without warehouse compute costs.

SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
#cache#result_scan#performance
🍒 ClickHouse

1. Create MergeTree Table with Partitioning

Design high-performance analytical event table.

CREATE TABLE user_events (
  event_date Date,
  user_id UInt64,
  event_type String,
  duration UInt32
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_date)
ORDER BY (event_type, user_id, event_date);
#mergetree#ddl#olap
🍒 ClickHouse

2. Deduplicate Records with ReplacingMergeTree

Keep latest version of records sharing primary key.

CREATE TABLE user_profiles (
  user_id UInt64,
  email String,
  updated_at DateTime
) ENGINE = ReplacingMergeTree(updated_at)
ORDER BY user_id;
#replacingmergetree#dedup#engine
🍒 ClickHouse

3. Continuous Aggregate Materialized View

Pre-aggregate incoming stream metrics automatically.

CREATE MATERIALIZED VIEW daily_sales_mv
ENGINE = SummingMergeTree()
ORDER BY (date, category)
AS SELECT event_date AS date, category, SUM(amount) AS total
FROM raw_orders GROUP BY date, category;
#materialized_view#realtime#aggregate
🍒 ClickHouse

4. Unpack Arrays with arrayJoin()

Expand array elements into separate table rows.

SELECT user_id, arrayJoin(tags) AS tag
FROM user_tags;
#arrayjoin#array#transform
🍒 ClickHouse

5. Compute Percentiles with quantileExact()

Calculate 95th and 99th percentile query latency metrics.

SELECT service_name,
       quantileExact(0.95)(duration_ms) AS p95,
       quantileExact(0.99)(duration_ms) AS p99
FROM app_logs GROUP BY service_name;
#quantile#percentile#analytics
🍒 ClickHouse

6. Extract Domain from URL Strings

Parse web domain from raw request URL string.

SELECT domainWithoutWWW(url) AS domain, COUNT(*)
FROM web_clicks GROUP BY domain ORDER BY COUNT(*) DESC;
#url#string#helpers
🍒 ClickHouse

7. Query System Tables for Part Sizes

Retrieve table storage metrics from system catalog.

SELECT table, formatReadableSize(sum(bytes)) AS size, sum(rows) AS total_rows
FROM system.parts WHERE active = 1 GROUP BY table ORDER BY sum(bytes) DESC;
#system#storage#dba
🍒 ClickHouse

8. Fetch Top Record Attributes with argMax

Retrieve column value associated with maximum timestamp.

SELECT user_id, argMax(status, timestamp) AS latest_status
FROM user_status_logs GROUP BY user_id;
#argmax#aggregate#latest
🍒 ClickHouse

9. External Dictionary Lookup

Join fast in-memory dictionary data without SQL JOINs.

SELECT user_id, dictGetString('country_dict', 'country_name', toUInt64(country_id)) AS country
FROM clicks;
#dictionary#lookup#speed
🍒 ClickHouse

10. Force Background Partition Merge

Manually trigger partition merge and deduplication.

OPTIMIZE TABLE user_profiles FINAL;
#optimize#merge#maintenance
ðŸĶ† DuckDB

1. Query Parquet File Directly with SQL

Execute SQL queries directly over local or remote Parquet files.

SELECT country, COUNT(*), AVG(amount)
FROM read_parquet('data/sales_2026.parquet')
WHERE status = 'completed'
GROUP BY country;
#parquet#read_parquet#file
ðŸĶ† DuckDB

2. Export Query Results to Parquet File

Write compressed Parquet file directly from SQL query.

COPY (
  SELECT * FROM orders WHERE order_date >= '2026-01-01'
) TO 'orders_2026.parquet' (FORMAT PARQUET, COMPRESSION SNAPPY);
#copy#export#parquet
ðŸĶ† DuckDB

3. Query Wildcard CSV Files (Globbing)

Query multiple CSV files matching a path wildcard pattern.

SELECT * FROM read_csv_auto('logs/2026-*.csv')
WHERE response_code = 500;
#csv#glob#read_csv
ðŸĶ† DuckDB

4. Query Python Pandas DataFrame Zero-Copy

Query in-memory Python DataFrames natively inside DuckDB.

-- In Python:
-- import duckdb, pandas as pd
-- df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
-- result = duckdb.query('SELECT AVG(b) FROM df').df()
#python#pandas#zero_copy
ðŸĶ† DuckDB

5. Filter Window Functions with QUALIFY

Filter window outputs directly without CTE wrappers.

SELECT customer_id, order_date, amount,
       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rn
FROM read_parquet('orders.parquet')
QUALIFY rn = 1;
#qualify#window#duckdb
ðŸĶ† DuckDB

6. Query Remote S3 Parquet Data Lake

Attach S3 credentials and query remote cloud files.

INSTALL httpfs; LOAD httpfs;
SET s3_region='us-east-1';

SELECT * FROM 's3://my-bucket/events/*.parquet'
LIMIT 100;
#s3#httpfs#cloud
ðŸĶ† DuckDB

7. Inspect Column Summary Statistics (SUMMARIZE)

Generate statistical summary (nulls, min, max, avg) for all table columns.

SUMMARIZE SELECT * FROM read_parquet('dataset.parquet');
#summarize#eda#stats
ðŸĶ† DuckDB

8. Dynamic PIVOT Query

Pivot quarterly row totals into analytical columns.

PIVOT (SELECT year, quarter, sales FROM quarterly_sales)
ON quarter IN ('Q1', 'Q2', 'Q3', 'Q4')
USING SUM(sales);
#pivot#analytics#transform
ðŸĶ† DuckDB

9. Manage S3 Credentials with CREATE SECRET

Securely store cloud authentication tokens in DuckDB.

CREATE SECRET s3_dev (
  TYPE S3,
  KEY_ID 'AKIAIOSFODNN7EXAMPLE',
  SECRET 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
  REGION 'us-east-1'
);
#secret#security#s3
ðŸĶ† DuckDB

10. Profile Query Execution Plan & Timings

Enable query profiling to inspect execution stage durations.

PRAGMA enable_profiling = 'json';
PRAGMA profiling_output = 'profile.json';

SELECT COUNT(*) FROM read_parquet('large_file.parquet');
#profiling#performance#benchmark