Sql Queries

作者 anthropicsae1513ea94dc無授權條款27K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

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, or aggregations.

精選僅含說明Data & Analytics
AI 產生的概覽

提供跨主流資料倉儲方言的 SQL 撰寫與最佳化參考,並附常用分析查詢模式。

功能
提供 PostgreSQL、Snowflake、BigQuery、Redshift 與 Databricks SQL 的方言語法參考,涵蓋日期時間、字串、陣列與半結構化資料函式以及效能建議。也提供視窗函式、CTE、同期群留存、漏斗分析與去重的可重用模式,並說明常見查詢錯誤的排查方式。產出的是 SQL 查詢與撰寫指引,而非實際執行查詢。
適用情境
適用於撰寫新的分析型 SQL、最佳化慢查詢、在不同倉儲方言之間轉換查詢,或建構包含 CTE、視窗函式與聚合的複雜查詢。也適合排查方言語法、型別或分組相關錯誤。
執行需求
僅包含說明,不含指令碼或工具。除自身執行環境外,不需安裝套件、憑證或網路存取。

SQL Queries Skill

Write correct, performant, readable SQL across all major data warehouse dialects.

Dialect-Specific Reference

PostgreSQL (including Aurora, RDS, Supabase, Neon)

Date/time:

sql
-- Current date/timeCURRENT_DATE, CURRENT_TIMESTAMP, NOW()
-- Date arithmeticdate_column + INTERVAL '7 days'date_column - INTERVAL '1 month'
-- Truncate to periodDATE_TRUNC('month', created_at)
-- Extract partsEXTRACT(YEAR FROM created_at)EXTRACT(DOW FROM created_at)  -- 0=Sunday
-- FormatTO_CHAR(created_at, 'YYYY-MM-DD')

String functions:

sql
-- Concatenationfirst_name || ' ' || last_nameCONCAT(first_name, ' ', last_name)
-- Pattern matchingcolumn ILIKE '%pattern%'  -- case-insensitivecolumn ~ '^regex_pattern$'  -- regex
-- String manipulationLEFT(str, n), RIGHT(str, n)SPLIT_PART(str, delimiter, position)REGEXP_REPLACE(str, pattern, replacement)

Arrays and JSON:

sql
-- JSON accessdata->>'key'  -- textdata->'nested'->'key'  -- jsondata#>>'{path,to,key}'  -- nested text
-- Array operationsARRAY_AGG(column)ANY(array_column)array_column @> ARRAY['value']

Performance tips:

  • Use EXPLAIN ANALYZE to profile queries
  • Create indexes on frequently filtered/joined columns
  • Use EXISTS over IN for correlated subqueries
  • Partial indexes for common filter conditions
  • Use connection pooling for concurrent access

Snowflake

Date/time:

sql
-- Current date/timeCURRENT_DATE(), CURRENT_TIMESTAMP(), SYSDATE()
-- Date arithmeticDATEADD(day, 7, date_column)DATEDIFF(day, start_date, end_date)
-- Truncate to periodDATE_TRUNC('month', created_at)
-- Extract partsYEAR(created_at), MONTH(created_at), DAY(created_at)DAYOFWEEK(created_at)
-- FormatTO_CHAR(created_at, 'YYYY-MM-DD')

String functions:

sql
-- Case-insensitive by default (depends on collation)column ILIKE '%pattern%'REGEXP_LIKE(column, 'pattern')
-- Parse JSONcolumn:key::string  -- dot notation for VARIANTPARSE_JSON('{"key": "value"}')GET_PATH(variant_col, 'path.to.key')
-- Flatten arrays/objectsSELECT f.value FROM table, LATERAL FLATTEN(input => array_col) f

Semi-structured data:

sql
-- VARIANT type accessdata:customer:name::STRINGdata:items[0]:price::NUMBER
-- Flatten nested structuresSELECT    t.id,    item.value:name::STRING as item_name,    item.value:qty::NUMBER as quantityFROM my_table t,LATERAL FLATTEN(input => t.data:items) item

Performance tips:

  • Use clustering keys on large tables (not traditional indexes)
  • Filter on clustering key columns for partition pruning
  • Set appropriate warehouse size for query complexity
  • Use RESULT_SCAN(LAST_QUERY_ID()) to avoid re-running expensive queries
  • Use transient tables for staging/temp data

BigQuery (Google Cloud)

Date/time:

sql
-- Current date/timeCURRENT_DATE(), CURRENT_TIMESTAMP()
-- Date arithmeticDATE_ADD(date_column, INTERVAL 7 DAY)DATE_SUB(date_column, INTERVAL 1 MONTH)DATE_DIFF(end_date, start_date, DAY)TIMESTAMP_DIFF(end_ts, start_ts, HOUR)
-- Truncate to periodDATE_TRUNC(created_at, MONTH)TIMESTAMP_TRUNC(created_at, HOUR)
-- Extract partsEXTRACT(YEAR FROM created_at)EXTRACT(DAYOFWEEK FROM created_at)  -- 1=Sunday
-- FormatFORMAT_DATE('%Y-%m-%d', date_column)FORMAT_TIMESTAMP('%Y-%m-%d %H:%M:%S', ts_column)

String functions:

sql
-- No ILIKE, use LOWER()LOWER(column) LIKE '%pattern%'REGEXP_CONTAINS(column, r'pattern')REGEXP_EXTRACT(column, r'pattern')
-- String manipulationSPLIT(str, delimiter)  -- returns ARRAYARRAY_TO_STRING(array, delimiter)

Arrays and structs:

sql
-- Array operationsARRAY_AGG(column)UNNEST(array_column)ARRAY_LENGTH(array_column)value IN UNNEST(array_column)
-- Struct accessstruct_column.field_name

Performance tips:

  • Always filter on partition columns (usually date) to reduce bytes scanned
  • Use clustering for frequently filtered columns within partitions
  • Use APPROX_COUNT_DISTINCT() for large-scale cardinality estimates
  • Avoid SELECT * -- billing is per-byte scanned
  • Use DECLARE and SET for parameterized scripts
  • Preview query cost with dry run before executing large queries

Redshift (Amazon)

Date/time:

sql
-- Current date/timeCURRENT_DATE, GETDATE(), SYSDATE
-- Date arithmeticDATEADD(day, 7, date_column)DATEDIFF(day, start_date, end_date)
-- Truncate to periodDATE_TRUNC('month', created_at)
-- Extract partsEXTRACT(YEAR FROM created_at)DATE_PART('dow', created_at)

String functions:

sql
-- Case-insensitivecolumn ILIKE '%pattern%'REGEXP_INSTR(column, 'pattern') > 0
-- String manipulationSPLIT_PART(str, delimiter, position)LISTAGG(column, ', ') WITHIN GROUP (ORDER BY column)

Performance tips:

  • Design distribution keys for collocated joins (DISTKEY)
  • Use sort keys for frequently filtered columns (SORTKEY)
  • Use EXPLAIN to check query plan
  • Avoid cross-node data movement (watch for DS_BCAST and DS_DIST)
  • ANALYZE and VACUUM regularly
  • Use late-binding views for schema flexibility

Databricks SQL

Date/time:

sql
-- Current date/timeCURRENT_DATE(), CURRENT_TIMESTAMP()
-- Date arithmeticDATE_ADD(date_column, 7)DATEDIFF(end_date, start_date)ADD_MONTHS(date_column, 1)
-- Truncate to periodDATE_TRUNC('MONTH', created_at)TRUNC(date_column, 'MM')
-- Extract partsYEAR(created_at), MONTH(created_at)DAYOFWEEK(created_at)

Delta Lake features:

sql
-- Time travelSELECT * FROM my_table TIMESTAMP AS OF '2024-01-15'SELECT * FROM my_table VERSION AS OF 42
-- Describe historyDESCRIBE HISTORY my_table
-- Merge (upsert)MERGE INTO target USING sourceON target.id = source.idWHEN MATCHED THEN UPDATE SET *WHEN NOT MATCHED THEN INSERT *

Performance tips:

  • Use Delta Lake's OPTIMIZE and ZORDER for query performance
  • Leverage Photon engine for compute-intensive queries
  • Use CACHE TABLE for frequently accessed datasets
  • Partition by low-cardinality date columns

Common SQL Patterns

Window Functions

sql
-- RankingROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)RANK() OVER (PARTITION BY category ORDER BY revenue DESC)DENSE_RANK() OVER (ORDER BY score DESC)
-- Running totals / moving averagesSUM(revenue) OVER (ORDER BY date_col ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as running_totalAVG(revenue) OVER (ORDER BY date_col ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_avg_7d
-- Lag / LeadLAG(value, 1) OVER (PARTITION BY entity ORDER BY date_col) as prev_valueLEAD(value, 1) OVER (PARTITION BY entity ORDER BY date_col) as next_value
-- First / Last valueFIRST_VALUE(status) OVER (PARTITION BY user_id ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)LAST_VALUE(status) OVER (PARTITION BY user_id ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
-- Percent of totalrevenue / SUM(revenue) OVER () as pct_of_totalrevenue / SUM(revenue) OVER (PARTITION BY category) as pct_of_category

CTEs for Readability

sql
WITH-- Step 1: Define the base populationbase_users AS (    SELECT user_id, created_at, plan_type    FROM users    WHERE created_at >= DATE '2024-01-01'      AND status = 'active'),
-- Step 2: Calculate user-level metricsuser_metrics AS (    SELECT        u.user_id,        u.plan_type,        COUNT(DISTINCT e.session_id) as session_count,        SUM(e.revenue) as total_revenue    FROM base_users u    LEFT JOIN events e ON u.user_id = e.user_id    GROUP BY u.user_id, u.plan_type),
-- Step 3: Aggregate to summary levelsummary AS (    SELECT        plan_type,        COUNT(*) as user_count,        AVG(session_count) as avg_sessions,        SUM(total_revenue) as total_revenue    FROM user_metrics    GROUP BY plan_type)
SELECT * FROM summary ORDER BY total_revenue DESC;

Cohort Retention

sql
WITH cohorts AS (    SELECT        user_id,        DATE_TRUNC('month', first_activity_date) as cohort_month    FROM users),activity AS (    SELECT        user_id,        DATE_TRUNC('month', activity_date) as activity_month    FROM user_activity)SELECT    c.cohort_month,    COUNT(DISTINCT c.user_id) as cohort_size,    COUNT(DISTINCT CASE        WHEN a.activity_month = c.cohort_month THEN a.user_id    END) as month_0,    COUNT(DISTINCT CASE        WHEN a.activity_month = c.cohort_month + INTERVAL '1 month' THEN a.user_id    END) as month_1,    COUNT(DISTINCT CASE        WHEN a.activity_month = c.cohort_month + INTERVAL '3 months' THEN a.user_id    END) as month_3FROM cohorts cLEFT JOIN activity a ON c.user_id = a.user_idGROUP BY c.cohort_monthORDER BY c.cohort_month;

Funnel Analysis

sql
WITH funnel AS (    SELECT        user_id,        MAX(CASE WHEN event = 'page_view' THEN 1 ELSE 0 END) as step_1_view,        MAX(CASE WHEN event = 'signup_start' THEN 1 ELSE 0 END) as step_2_start,        MAX(CASE WHEN event = 'signup_complete' THEN 1 ELSE 0 END) as step_3_complete,        MAX(CASE WHEN event = 'first_purchase' THEN 1 ELSE 0 END) as step_4_purchase    FROM events    WHERE event_date >= CURRENT_DATE - INTERVAL '30 days'    GROUP BY user_id)SELECT    COUNT(*) as total_users,    SUM(step_1_view) as viewed,    SUM(step_2_start) as started_signup,    SUM(step_3_complete) as completed_signup,    SUM(step_4_purchase) as purchased,    ROUND(100.0 * SUM(step_2_start) / NULLIF(SUM(step_1_view), 0), 1) as view_to_start_pct,    ROUND(100.0 * SUM(step_3_complete) / NULLIF(SUM(step_2_start), 0), 1) as start_to_complete_pct,    ROUND(100.0 * SUM(step_4_purchase) / NULLIF(SUM(step_3_complete), 0), 1) as complete_to_purchase_pctFROM funnel;

Deduplication

sql
-- Keep the most recent record per keyWITH ranked AS (    SELECT        *,        ROW_NUMBER() OVER (            PARTITION BY entity_id            ORDER BY updated_at DESC        ) as rn    FROM source_table)SELECT * FROM ranked WHERE rn = 1;

Error Handling and Debugging

When a query fails:

  1. Syntax errors: Check for dialect-specific syntax (e.g., ILIKE not available in BigQuery, SAFE_DIVIDE only in BigQuery)
  2. Column not found: Verify column names against schema -- check for typos, case sensitivity (PostgreSQL is case-sensitive for quoted identifiers)
  3. Type mismatches: Cast explicitly when comparing different types (CAST(col AS DATE), col::DATE)
  4. Division by zero: Use NULLIF(denominator, 0) or dialect-specific safe division
  5. Ambiguous columns: Always qualify column names with table alias in JOINs
  6. Group by errors: All non-aggregated columns must be in GROUP BY (except in BigQuery which allows grouping by alias)

來源與署名

來源:anthropics/knowledge-work-plugins位於data/skills/sql-queries提交ae1513e

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 anthropics/knowledge-work-plugins 的技能

Ticket Deflector

anthropics

精選

Reads a forwarded customer email or ticket, pulls order and refund status from a payments connector (PayPal, Square, or Stripe) or Shopify, account history from the CRM, and open tickets from a support desk (Zoho Desk), drafts a tone-matched reply in the owner's writing voice, and can issue a refund through the payments connector with explicit owner approval. With Shopify connected it also runs a proactive order-triage mode that surfaces orders needing attention — unfulfilled past the promised window, payment problems, pending refunds, stuck shipments — and drafts the next action for each before the customer has to ask. Use when the user says "draft a response," "answer this customer," "where's my order," "I want a refund," "check my orders," or "anything about to blow up."

待分類27K今天更新

Tax Season Organizer

anthropics

精選

Prepares tax-season materials for the owner's accountant, not tax advice. US federal tax; a non-US business gets its closed-books packet instead. Two modes: (1) quarterly estimated tax from YTD net income in the ledger (MYOB, NetSuite, QuickBooks, Xero, or Zoho Books); (2) year-end 1099 prep, scanning the ledger, PayPal, and Stripe for contractors paid over USD 600 into a 1099-NEC list with missing W-9 flags. Any tax request routes first to /tax-prep, which confirms the books are closed and reconciled before running this skill. Use this skill directly only when the owner says the period's books are already closed: "books are closed, now do the 1099s," "run the quarterly estimate off the closed numbers," or "just the contractor W-9 list."

待分類27K今天更新

Tax Prep

anthropics

精選

根據已結帳的帳目準備稅務資料:季度預估繳稅明細,或年終 1099-NEC 清單與會計師資料包。

Business & Finance27K今天更新

Smb Onboard

anthropics

精選

引導小型企業主完成首次設定:連接工具、執行一次展現價值的配方、記錄業務背景並設定每週檢查節奏。

Productivity & Workflow27K今天更新

Smb Router

anthropics

精選

將小型企業主的需求轉接到合適的外掛技能或指令,並說明可用功能。

Productivity & Workflow27K今天更新

Month End Prep

anthropics

精選

Reconciles the accounting ledger (MYOB, NetSuite, QuickBooks, Xero, or Zoho Books) against PayPal, Shopify, Square, and Stripe settlements, flags transactions that need attention, suspicious duplicates, and missing receipts, then writes a plain-English P&L narrative and exports a close packet (xlsx + one-page PDF). This is the first link of the /close-month command; a request to close the month or the books routes there, and the command runs this skill before refreshing the forecast and distributing the packet. Use this skill directly only when the owner wants the reconciliation alone, with no forecast refresh and no distribution: "just reconcile, no packet," "what's missing from the books," "flag the duplicates and missing receipts," or "write the P&L narrative for this month."

待分類27K今天更新