data-sql-queries
When to use
Use this for production-grade SQL — a new query, a refactor, or a fix for one that is slow, wrong, or expensive — on a warehouse (BigQuery, Snowflake, Redshift, Postgres, DuckDB). Correctness first, then performance.
Not for: translating a plain-English ask from scratch (use data-write-query), judging whether numbers are statistically real (use data-statistical-analysis), or documenting metric definitions (use data-context-extractor).
Method
- Confirm the contract: dialect, source tables, grain, expected output columns, and how the result is used. Ambiguity here yields confidently wrong SQL.
- Get the grain right. Know each table's grain before joining. Decision point: if a join key is non-unique, expect fan-out — verify row counts before and after each join.
- Structure for readability: CTEs, one logical step each. Filter early, aggregate late; explicit column lists over
SELECT *.
- Match the dialect. Date functions,
QUALIFY (BigQuery/Snowflake), array/struct handling, and window syntax differ — do not port blindly.
- Optimize: prune partitions and clustering keys, push filters down, replace correlated subqueries with joins/windows, pre-aggregate before joining. On BigQuery watch bytes scanned; on Snowflake watch spillage and warehouse size.
- Read the plan. Use
EXPLAIN/query profile to confirm the fix. Decision point: if you cannot show before/after cost or runtime, do not claim it is faster.
Example
A SUM(amount) doubled after adding an orders → shipments join because an order has many shipments (fan-out). Fix: pre-aggregate shipments to order grain first.
WITH ship AS ( -- collapse to one row per order
SELECT order_id, COUNT(*) AS n_ship
FROM shipments GROUP BY order_id
)
SELECT o.order_id, o.amount, s.n_ship -- amount no longer multiplied
FROM orders o
LEFT JOIN ship s USING (order_id);
Pitfalls
- Trusting a SUM without checking row counts across joins — fan-out is silent.
SELECT * on wide/columnar tables, scanning and paying for unused columns.
- Correlated subqueries where a window function is cheaper and clearer.
- Asserting a speedup with no plan or timing to back it.
Output format
SQL: <final, dialect labeled, commented per CTE>
Assumptions: <grain, keys, filters, dialect>
Correctness notes: <fan-out checks; nulls, ties, timezone edge cases>
Performance: <what changed + measured/plan-based evidence>
If the grain is unclear, state your assumption explicitly.
1---2name: data-sql-queries3version: 1.0.04description: Write correct, performant SQL across warehouse dialects and diagnose queries that are slow, wrong, or expensive.5author: matrixx00706tags: [sql, warehouse, optimization, bigquery, snowflake, query-tuning]7capabilities: []8metadata:9 source: https://skillmd.com/skills/matrixx0070/data-sql-queries10---1112# data-sql-queries1314## When to use1516Use this for production-grade SQL — a new query, a refactor, or a fix for one that is slow, wrong, or expensive — on a warehouse (BigQuery, Snowflake, Redshift, Postgres, DuckDB). Correctness first, then performance.1718**Not for:** translating a plain-English ask from scratch (use data-write-query), judging whether numbers are statistically real (use data-statistical-analysis), or documenting metric definitions (use data-context-extractor).1920## Method21221. **Confirm the contract:** dialect, source tables, grain, expected output columns, and how the result is used. Ambiguity here yields confidently wrong SQL.232. **Get the grain right.** Know each table's grain before joining. Decision point: if a join key is non-unique, expect fan-out — verify row counts before and after each join.243. **Structure for readability:** CTEs, one logical step each. Filter early, aggregate late; explicit column lists over `SELECT *`.254. **Match the dialect.** Date functions, `QUALIFY` (BigQuery/Snowflake), array/struct handling, and window syntax differ — do not port blindly.265. **Optimize:** prune partitions and clustering keys, push filters down, replace correlated subqueries with joins/windows, pre-aggregate before joining. On BigQuery watch bytes scanned; on Snowflake watch spillage and warehouse size.276. **Read the plan.** Use `EXPLAIN`/query profile to confirm the fix. Decision point: if you cannot show before/after cost or runtime, do not claim it is faster.2829## Example3031A `SUM(amount)` doubled after adding an `orders → shipments` join because an order has many shipments (fan-out). Fix: pre-aggregate shipments to order grain first.3233```sql34WITH ship AS ( -- collapse to one row per order35 SELECT order_id, COUNT(*) AS n_ship36 FROM shipments GROUP BY order_id37)38SELECT o.order_id, o.amount, s.n_ship -- amount no longer multiplied39FROM orders o40LEFT JOIN ship s USING (order_id);41```4243## Pitfalls4445- Trusting a SUM without checking row counts across joins — fan-out is silent.46- `SELECT *` on wide/columnar tables, scanning and paying for unused columns.47- Correlated subqueries where a window function is cheaper and clearer.48- Asserting a speedup with no plan or timing to back it.4950## Output format5152```53SQL: <final, dialect labeled, commented per CTE>54Assumptions: <grain, keys, filters, dialect>55Correctness notes: <fan-out checks; nulls, ties, timezone edge cases>56Performance: <what changed + measured/plan-based evidence>57```5859If the grain is unclear, state your assumption explicitly.