sql-queries
Skill1 starsChanged 7 months agoMITView on GitHub
Write correct, performant SQL across all major data warehouse dialects (Snowflake, BigQuery, Databricks, PostgreSQL, etc.). Use when writing queries, optimizing slow SQL, translating between dialects, or building complex analytical queries with CTEs, window functions, and aggregations. Trigger phrases: "write a SQL query", "optimize this query", "SQL for", "convert this query to BigQuery", "window function for", "CTE for", "fix this SQL", "why is this query slow", "SQL to calculate", "translate this query to Snowflake"
12 other projects use a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- yuusakuri/agent-skillstheir own version, first seen Nov 1, 2026
- vijaysuperpositionist/skillstheir own version, first seen Nov 1, 2026
- The-Utopia-Studio/skillstheir own version, first seen Oct 13, 2026
- anthropics/knowledge-work-pluginstheir own version, first seen Oct 13, 2026
- edu6565/claude-skillstheir own version, first seen Oct 11, 2026
- stefanomartiradonna/claude-skillstheir own version, first seen Aug 14, 2026
Used with
Projects with it also use brainstorm-experiments-new, brainstorm-experiments-existing and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
skytiger6724Skillbrainstorm-experiments-new
Design lean startup experiments (pretotypes) for a new product. Creates XYZ hypotheses and suggests low-effort validation methods like landing pages, explainer videos, and pre-orders. Use when validating a new product idea, creating pretotypes, or testing market demand.
Also in 8 projects that use this
skytiger6724Skillbrainstorm-experiments-existing
Design experiments to test assumptions for an existing product — prototypes, A/B tests, spikes, and other low-effort validation methods. Use when validating assumptions, testing feature ideas cheaply, or planning product experiments.
Also in 6 projects that use this
45ckSkillpestle-analysis
Also in 6 projects that use this
About-IntelligenceSkillpositioning-ideas
Brainstorm product positioning ideas differentiated from competitors.
Also in 6 projects that use this
About-IntelligenceSkillproduct-name
Brainstorm 5 unique, memorable product names with rationale aligned to brand values and target audience.
Also in 6 projects that use this
launchapp-devSkillinterview-script
Create a structured user interview script with warm-up, core exploration, and wrap-up sections. Use when preparing for user research interviews to ensure consistent, insightful conversations.
Also in 8 projects that use this
- +6 more from skytiger6724
Other versions12 projects use a version of this.
Word for word · 0
None found.
Edited · 1
- miptah21/skills★ 210% same
Wrote their own version · 11
- anthropics/knowledge-work-plugins★ 35ksame name
- The-Utopia-Studio/skills★ 6same name
- Adhamxon/claude-code-skills★ 2same name
- skytiger6724/qwen-skills★ 2same name
- yuusakuri/agent-skills★ 2same name
- miovrag/claude-skills★ 1same name
- edu6565/claude-skills★ 0same name
- jmolz/m0lz.01★ 0same name
- maeng777/claude-skills★ 0same name
- stefanomartiradonna/claude-skills★ 0same name
1 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository164 other files it gives its agents.
- instrument-data-to-allotropeSkill
- literature-reviewSkill
- nextflow-developmentSkill
- scientific-problem-selectionSkill
- scvi-toolsSkill
- single-cell-rna-qcSkill
- discover-brandSkill
- enforce-voiceSkill
- generate-guidelinesSkill
- csat-reportSkill
- customer-escalationSkill
- customer-researchSkill
- draft-responseSkill
- kb-articleSkill
- sentiment-analysisSkill
- ticket-triageSkill
- analyzeSkill
- build-dashboardSkill
- create-vizSkill
- data-context-extractorSkill
- data-modelingSkill
- data-pipelineSkill
- etl-designSkill
- explore-dataSkill
- statistical-analysisSkill
- validate-dataSkill
- write-querySkill
- accessibility-reviewSkill
- component-librarySkill
- design-critiqueSkill
- design-handoffSkill
- design-systemSkill
- frontend-designSkill
- research-synthesisSkill
- user-researchSkill
- ux-copySkill
- wireframingSkill
- Agent DevelopmentSkill
- CLAUDE.md ManagementSkill
- MCP Server BuilderSkill
- Plugin DevelopmentSkill
- Prompt EngineeringSkill
- Skill CreatorSkill
- curriculum-designSkill
- lesson-planningSkill
- quiz-generatorSkill
- study-guideSkill
- tutoringSkill
- api-designSkill
- architectureSkill
- ci-cd-pipelineSkill
- code-reviewSkill
- database-migrationSkill
- debugSkill
- dependency-auditSkill
- deploy-checklistSkill
- documentationSkill
- error-handlingSkill
- git-workflowSkill
- incident-responseSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
12 rules. 0 are common, 5 are distinctive, and 7 are very specific to this project.
0
Common
Most of the 12 edited versions we read keep these.
5
Distinctive
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Write correct, performant SQL across major data warehouse dialects.
- Distinctive: line 19
Before writing SQL, establish:
- Distinctive: line 30
Always use CTEs for readability.
- Distinctive: line 150
Use clustering keys for frequently filtered columns
- Distinctive: line 151
Avoid ORDER BY in CTEs (it is ignored)
- Very specific: line 152
Use RESULT_SCAN(LAST_QUERY_ID()) for iterative exploration
- Very specific: line 156
Use QUALIFY (supported since 2021)
- Very specific: line 157
Prefer SAFE_DIVIDE(a, b) over a / NULLIF(b, 0)
- Very specific: line 221
Handle division by zero: Always wrap denominators with NULLIF(x, 0).
- Very specific: line 223
Test with LIMIT first: Run with LIMIT 100 before executing the full query on large tables.
- Very specific: line 224
Include row counts: Add COUNT(*) as a sanity check when developing.
- Very specific: line 226
Use date literals consistently: Prefer '2024-01-01' over DATE('2024-01-01') unless dialect requires it.
“Common” is measured: kept by at least 6 in 10 of the 12 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Queries Skill
Write correct, performant SQL across major data warehouse dialects. Handle everything from simple selects to complex analytical queries with CTEs, window functions, and advanced aggregations.
Workflow
Step 1: Clarify Requirements
Before writing SQL, establish:
- What question does this answer? Restate the business question.
- What dialect? Snowflake, BigQuery, Databricks SQL, PostgreSQL, MySQL, Redshift.
- What tables are involved? Get table names, schemas, key columns.
- What is the grain? One row per user? Per day? Per transaction?
- What filters apply? Date range, segments, exclusions.
- How large are the tables? This affects optimization strategy.
Step 2: Structure with CTEs
Always use CTEs for readability. Structure queries in logical layers:
WITH
-- Layer 1: Source data with filters
filtered_orders AS (
SELECT
order_id,
customer_id,
order_date,
amount
FROM orders
WHERE order_date >= '2024-01-01'
AND status = 'completed'
AND is_test = FALSE
),
-- Layer 2: Intermediate aggregation
daily_revenue AS (
SELECT
order_date,
COUNT(DISTINCT customer_id) AS customers,
COUNT(order_id) AS orders,
SUM(amount) AS revenue
FROM filtered_orders
GROUP BY order_date
),
-- Layer 3: Final calculation
final AS (
SELECT
order_date,
customers,
orders,
revenue,
revenue / NULLIF(orders, 0) AS avg_order_value,
SUM(revenue) OVER (ORDER BY order_date ROWS UNBOUNDED PRECEDING) AS cumulative_revenue
FROM daily_revenue
)
SELECT * FROM final
ORDER BY order_date;Step 3: Apply Dialect-Specific Syntax
Date Functions
| Operation | Snowflake | BigQuery | PostgreSQL | Databricks |
| Current date | CURRENT_DATE() | CURRENT_DATE() | CURRENT_DATE | CURRENT_DATE() |
| Date diff | DATEDIFF('day', a, b) | DATE_DIFF(b, a, DAY) | b - a | DATEDIFF(b, a) |
| Date trunc | DATE_TRUNC('month', d) | DATE_TRUNC(d, MONTH) | DATE_TRUNC('month', d) | DATE_TRUNC('month', d) |
| Add days | DATEADD('day', n, d) | DATE_ADD(d, INTERVAL n DAY) | d + INTERVAL 'n days' | DATE_ADD(d, n) |
| Extract | EXTRACT(MONTH FROM d) | EXTRACT(MONTH FROM d) | EXTRACT(MONTH FROM d) | EXTRACT(MONTH FROM d) |
String Functions
| Operation | Snowflake | BigQuery | PostgreSQL |
| Concat | col1 || col2 | CONCAT(col1, col2) | col1 || col2 |
| Substring | SUBSTR(s, 1, 5) | SUBSTR(s, 1, 5) | SUBSTRING(s FROM 1 FOR 5) |
| Split | SPLIT_PART(s, ',', 1) | SPLIT(s, ',')[OFFSET(0)] | SPLIT_PART(s, ',', 1) |
| Regex | REGEXP_LIKE(s, 'pat') | REGEXP_CONTAINS(s, 'pat') | s ~ 'pat' |
Array/JSON
| Operation | Snowflake | BigQuery | PostgreSQL |
| Unnest array | LATERAL FLATTEN(arr) | UNNEST(arr) | UNNEST(arr) |
| JSON extract | col:key::STRING | JSON_VALUE(col, '$.key') | col->>'key' |
Step 4: Window Functions
Master these patterns:
-- Running total
SUM(amount) OVER (PARTITION BY customer_id ORDER BY date ROWS UNBOUNDED PRECEDING)
-- Row number for deduplication
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
-- Lag/Lead for period-over-period
LAG(revenue, 1) OVER (ORDER BY month) AS prev_month_revenue
-- Percent of total
amount / SUM(amount) OVER (PARTITION BY category) AS pct_of_category
-- Moving average
AVG(daily_value) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_avg_7d
-- Rank within groups
RANK() OVER (PARTITION BY category ORDER BY revenue DESC) AS revenue_rank
-- Cumulative distinct count (approximate)
-- Snowflake: HLL
-- BigQuery: APPROX_COUNT_DISTINCT (not windowed, use a different approach)Step 5: Optimize for Performance
General optimization rules:
- Filter early. Push WHERE clauses into CTEs as close to the source as possible.
- Avoid SELECT *. Name specific columns to reduce I/O.
- Use approximate functions for large datasets.
APPROX_COUNT_DISTINCTinstead ofCOUNT(DISTINCT)when exact counts are not needed. - Partition pruning. Filter on partition columns (usually date) to avoid full table scans.
- Avoid correlated subqueries. Rewrite as JOINs or window functions.
- Use QUALIFY instead of subqueries for filtering window results:
-- Instead of wrapping in a subquery to filter by rn = 1: SELECT * FROM events QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY ts DESC) = 1 - Minimize joins on large tables. Pre-aggregate before joining when possible.
- Use semi-joins (EXISTS/IN) instead of full joins when you only need to filter.
Snowflake-specific:
- Use clustering keys for frequently filtered columns
- Avoid ORDER BY in CTEs (it is ignored)
- Use
RESULT_SCAN(LAST_QUERY_ID())for iterative exploration
BigQuery-specific:
- Filter on
_PARTITIONDATEor_PARTITIONTIMEfor partitioned tables - Use
QUALIFY(supported since 2021) - Prefer
SAFE_DIVIDE(a, b)overa / NULLIF(b, 0)
Step 6: Common Patterns
Deduplication
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC) AS rn
FROM raw_table
) WHERE rn = 1Pivoting
SELECT
date,
SUM(CASE WHEN channel = 'organic' THEN revenue END) AS organic_revenue,
SUM(CASE WHEN channel = 'paid' THEN revenue END) AS paid_revenue,
SUM(CASE WHEN channel = 'referral' THEN revenue END) AS referral_revenue
FROM orders
GROUP BY dateGap Detection
WITH dates AS (
SELECT date FROM UNNEST(GENERATE_DATE_ARRAY('2024-01-01', CURRENT_DATE())) AS date
)
SELECT d.date
FROM dates d
LEFT JOIN daily_data dd ON d.date = dd.date
WHERE dd.date IS NULLRetention Cohorts
WITH first_purchase AS (
SELECT customer_id, MIN(DATE_TRUNC('month', order_date)) AS cohort_month
FROM orders GROUP BY 1
)
SELECT
fp.cohort_month,
DATEDIFF('month', fp.cohort_month, DATE_TRUNC('month', o.order_date)) AS month_number,
COUNT(DISTINCT o.customer_id) AS retained_customers
FROM orders o
JOIN first_purchase fp ON o.customer_id = fp.customer_id
GROUP BY 1, 2Output Format
-- [Brief description of what this query does]
-- Dialect: [Snowflake/BigQuery/PostgreSQL/etc.]
-- Expected output: [Description of result set]
[SQL query with comments explaining non-obvious logic]Best Practices
- Format consistently. Keywords uppercase, table/column names lowercase, one clause per line.
- Comment the why, not the what.
-- Exclude refunds processed after cutoffnot-- filter by status. - Use meaningful CTE names.
daily_active_usersnottmp1. - Handle division by zero. Always wrap denominators with
NULLIF(x, 0). - Use COALESCE for null handling. Be explicit about how nulls should be treated.
- Test with LIMIT first. Run with
LIMIT 100before executing the full query on large tables. - Include row counts. Add
COUNT(*)as a sanity check when developing. - Avoid implicit type coercion. Cast explicitly:
CAST(id AS STRING). - Use date literals consistently. Prefer
'2024-01-01'overDATE('2024-01-01')unless dialect requires it. - Version your queries. Include a comment header with date and purpose when saving queries.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

