[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7351SSG907M9KBVBFP6K7NF":3,"skill-same:01M7351SSG907M9KBVBFP6K7NF":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7351SSG907M9KBVBFP6K7NF","productize-sql-queries",null,"Write correct, performant SQL across major data warehouse dialects including Snowflake, BigQuery, Databricks, PostgreSQL, and Redshift. Use when writing queries, optimizing slow SQL, translating dialects, or building analytical queries with CTEs, windows, and aggregations.","itseffi\u002Fproductize","itseffi","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F15998472?v=4","01M734C5RJ7CKRTPB3FX84VZV7","Effi","01M734C5S6B7FW62ZNWYBZ9GG7",3,"MIT","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-sql-queries\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: productize-sql-queries\ndescription: >-\n  Write correct, performant SQL across major data warehouse dialects including Snowflake,\n  BigQuery, Databricks, PostgreSQL, and Redshift. Use when writing queries, optimizing slow\n  SQL, translating dialects, or building analytical queries with CTEs, windows, and\n  aggregations.\n---\n\u003C!-- AUTO-GENERATED from SKILL.md.tmpl - do not edit directly -->\n\u003C!-- Regenerate: npm run skills:generate -->\n\n# SQL Queries\n\n## Productize Preamble\n\nBefore producing the artifact, implementation step, or code change, classify the work:\n\n- **User\u002Fpersona**: founder, product leader, AI PM, AI builder, stakeholder, or mixed\u002Funknown.\n- **Product stage**: idea, validation, PMF search, growth, scale, pivot, or unknown.\n- **Artifact mode**: strategy memo, PRD, research plan, positioning, experiment, deck, roadmap, execution brief, diagnostic, or decision record.\n- **Artifact format**: Markdown for short, repo-native, diff-sensitive artifacts; self-contained HTML for long, visual, shareable, interactive, or explicitly requested artifacts.\n- **Evidence standard**: what is known, assumed, missing, and risky.\n- **Decision mode**: recommend, ask for a blocking input, or proceed with explicit assumptions.\n\nOperating rules:\n\n1. Do not produce generic product strategy filler. Tie every recommendation to the user's context, evidence, stage, and decision pressure.\n2. Separate facts from assumptions. Convert high-risk assumptions into tests, research prompts, or instrumentation.\n3. Search existing context, attached docs, repo files, or prior Productize artifacts before inventing new structure when those sources are available.\n4. Ask only for inputs that materially change the output. If the next step is obvious, proceed and state assumptions.\n5. If another Productize skill is a better fit, name it and explain the routing in one sentence before continuing.\n6. Enforce the output contract for this skill. Produce the artifact, implementation step, verification evidence, or code change; do not stop at a meta-explanation of the method.\n7. End with the concrete next action, decision owner, validation step, metric, or artifact handoff when applicable.\n8. Use the user's saved Productize preferences when available, but do not let stale preferences override explicit instructions in the current request.\n9. If you must ask a blocking question, use this compact format: `AskUserQuestion: \u003Cone question> Why it matters: \u003Cdecision it changes>`.\n10. Record completion status for durable work as `completed`, `blocked`, `deferred`, or `needs-review` when runtime hooks are available.\n\nArtifact format policy:\n\n- Default to Markdown for short notes, repo-native documentation, changelog fragments, or artifacts where clean source diffs matter.\n- Use a self-contained HTML file when the user asks for HTML, the artifact is likely to exceed about 100 lines, the reader needs diagrams\u002Ftables\u002Fcomparisons\u002Fscreenshots, the artifact is meant to be shared, or interaction\u002Fexport controls would help the user stay in the loop.\n- Route by product job first, then choose the format. Do not create a generic HTML workflow when a Productize playbook, gate, or routed skill owns the work.\n- HTML artifacts must be local-first and portable: one file, embedded CSS\u002FJS, no remote dependencies unless explicitly requested, readable without a dev server, responsive, accessible, and easy to skim.\n- Prefer semantic sections, tables, SVG diagrams, annotated code blocks, status chips, collapsible detail, and copy\u002Fexport buttons when they improve review speed. Avoid decorative complexity that hides the decision.\n- For implementation work with ambiguities, use `$implementation-notes` when the user asks for a running notes file, especially `implementation-notes.html` or `implementation-notes.md`.\n\nRuntime hooks, if available:\n\n- Use `productize-workflow start \"\u003Cuser request>\"` at the beginning of durable product work; it restores context, routes the request, records the session, and returns the required artifact contract.\n- Use `productize-workflow complete --id \u003Cid> --status completed|blocked|deferred|needs-review --artifact-type \u003Ctype> --summary \u003Csummary>` before ending durable product work; it records the artifact, saves context, and logs completion status.\n- Use `productize-update-check --strict` at the start of maintenance, setup, release, or generated-output work.\n- Use `productize-config` to read or write user\u002Fteam preferences such as persona, artifact mode, evidence threshold, or update-check policy.\n- Use `productize-session-log` to record important workflow decisions.\n- Use `productize-artifact-log` when a durable artifact is produced.\n- Use `productize-context-restore` before restarting long-running product work from scratch.\n- Use `productize-context-save` after producing a durable strategy, research, spec, or stakeholder artifact.\n- Use `productize-registry-search` or `productize-skill-router` when routing is ambiguous.\n- Use `productize-completion-status` to log whether the workflow completed, blocked, deferred, or needs review.\n\nTelemetry standard:\n\n- Keep telemetry local by default in `.productize\u002F` or `PRODUCTIZE_STATE_DIR`.\n- Log artifact type, routing decision, evidence gaps, and completion status; do not log secrets or private customer data unless the user explicitly asks for it.\n\nCurrent skill metadata:\n\n- **Skill**: `sql-queries`\n- **Lifecycle**: Measure\n- **Category**: Analytics\n- **Primary artifact**: SQL Queries analytics diagnosis with metric readout, caveats, decision, and next instrumented step\n\nHelper skill for writing correct, performant, readable SQL across major warehouse dialects.\n\n## Invocation\n\nThis is primarily a support skill for `analyze`, `explore-data`, `metrics-review`, `create-viz`, `build-dashboard`, and `data-context-extractor`. Use it explicitly when dialect-specific SQL guidance is needed.\n\n## Core Rules\n\n- Identify the SQL dialect before writing syntax-sensitive queries.\n- Prefer readable CTEs for multi-step analysis.\n- Qualify columns with table aliases in joins.\n- Protect division with `NULLIF(denominator, 0)` or dialect-safe functions.\n- Avoid `SELECT *` in analytical warehouse queries unless profiling a small table.\n- Filter partition\u002Fdate columns early on large tables.\n- State assumptions about grain, filters, timezone, and deduplication.\n- Include validation queries for non-trivial analysis.\n\n## Dialect Reference\n\n### PostgreSQL, Aurora, RDS, Supabase, Neon\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE, CURRENT_TIMESTAMP, NOW()\ndate_column + INTERVAL '7 days'\ndate_column - INTERVAL '1 month'\nDATE_TRUNC('month', created_at)\nEXTRACT(YEAR FROM created_at)\nEXTRACT(DOW FROM created_at) -- 0=Sunday\nTO_CHAR(created_at, 'YYYY-MM-DD')\n```\n\nStrings, arrays, JSON:\n\n```sql\nfirst_name || ' ' || last_name\nCONCAT(first_name, ' ', last_name)\ncolumn ILIKE '%pattern%'\ncolumn ~ '^regex_pattern$'\nSPLIT_PART(str, delimiter, position)\ndata->>'key'\ndata->'nested'->'key'\ndata#>>'{path,to,key}'\nARRAY_AGG(column)\narray_column @> ARRAY['value']\n```\n\nPerformance:\n- Use `EXPLAIN ANALYZE`.\n- Index frequently filtered or joined columns.\n- Consider partial indexes for common filters.\n- Use `EXISTS` over correlated `IN` when appropriate.\n\n### Snowflake\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP(), SYSDATE()\nDATEADD(day, 7, date_column)\nDATEDIFF(day, start_date, end_date)\nDATE_TRUNC('month', created_at)\nYEAR(created_at), MONTH(created_at), DAY(created_at)\nDAYOFWEEK(created_at)\nTO_CHAR(created_at, 'YYYY-MM-DD')\n```\n\nSemi-structured data:\n\n```sql\ncolumn ILIKE '%pattern%'\nREGEXP_LIKE(column, 'pattern')\ndata:customer:name::STRING\ndata:items[0]:price::NUMBER\n\nSELECT\n  t.id,\n  item.value:name::STRING AS item_name,\n  item.value:qty::NUMBER AS quantity\nFROM my_table t,\nLATERAL FLATTEN(input => t.data:items) item;\n```\n\nPerformance:\n- Use clustering keys on large tables.\n- Filter on clustering columns for pruning.\n- Use appropriate warehouse size.\n- Use `RESULT_SCAN(LAST_QUERY_ID())` to avoid rerunning expensive queries.\n- Use transient tables for staging.\n\n### BigQuery\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP()\nDATE_ADD(date_column, INTERVAL 7 DAY)\nDATE_SUB(date_column, INTERVAL 1 MONTH)\nDATE_DIFF(end_date, start_date, DAY)\nTIMESTAMP_DIFF(end_ts, start_ts, HOUR)\nDATE_TRUNC(created_at, MONTH)\nTIMESTAMP_TRUNC(created_at, HOUR)\nEXTRACT(YEAR FROM created_at)\nEXTRACT(DAYOFWEEK FROM created_at) -- 1=Sunday\nFORMAT_DATE('%Y-%m-%d', date_column)\n```\n\nStrings, arrays, structs:\n\n```sql\nLOWER(column) LIKE '%pattern%'\nREGEXP_CONTAINS(column, r'pattern')\nREGEXP_EXTRACT(column, r'pattern')\nSPLIT(str, delimiter)\nARRAY_TO_STRING(array, delimiter)\nARRAY_AGG(column)\nUNNEST(array_column)\nARRAY_LENGTH(array_column)\nvalue IN UNNEST(array_column)\nstruct_column.field_name\n```\n\nPerformance:\n- Always filter partition columns to reduce bytes scanned.\n- Use clustering for frequent filters within partitions.\n- Use `APPROX_COUNT_DISTINCT()` for large-cardinality estimates.\n- Avoid `SELECT *` because billing is per byte scanned.\n- Use dry runs for expensive queries.\n\n### Redshift\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE, GETDATE(), SYSDATE\nDATEADD(day, 7, date_column)\nDATEDIFF(day, start_date, end_date)\nDATE_TRUNC('month', created_at)\nEXTRACT(YEAR FROM created_at)\nDATE_PART('dow', created_at)\n```\n\nStrings:\n\n```sql\ncolumn ILIKE '%pattern%'\nREGEXP_INSTR(column, 'pattern') > 0\nSPLIT_PART(str, delimiter, position)\nLISTAGG(column, ', ') WITHIN GROUP (ORDER BY column)\n```\n\nPerformance:\n- Choose DISTKEY for collocated joins.\n- Choose SORTKEY for frequent filters.\n- Use `EXPLAIN` to inspect plans.\n- Watch for cross-node movement.\n- Run `ANALYZE` and `VACUUM` regularly.\n\n### Databricks SQL\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP()\nDATE_ADD(date_column, 7)\nDATEDIFF(end_date, start_date)\nADD_MONTHS(date_column, 1)\nDATE_TRUNC('MONTH', created_at)\nTRUNC(date_column, 'MM')\nYEAR(created_at), MONTH(created_at)\nDAYOFWEEK(created_at)\n```\n\nDelta Lake:\n\n```sql\nSELECT * FROM my_table TIMESTAMP AS OF '2024-01-15';\nSELECT * FROM my_table VERSION AS OF 42;\nDESCRIBE HISTORY my_table;\n\nMERGE INTO target USING source\nON target.id = source.id\nWHEN MATCHED THEN UPDATE SET *\nWHEN NOT MATCHED THEN INSERT *;\n```\n\nPerformance:\n- Use Delta `OPTIMIZE` and `ZORDER`.\n- Use Photon for compute-heavy workloads when available.\n- Cache frequently accessed datasets.\n- Partition by low-cardinality date columns.\n\n## Common Patterns\n\n### Window Functions\n\n```sql\nROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)\nRANK() OVER (PARTITION BY category ORDER BY revenue DESC)\nDENSE_RANK() OVER (ORDER BY score DESC)\n\nSUM(revenue) OVER (\n  ORDER BY date_col ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n) AS running_total\n\nAVG(revenue) OVER (\n  ORDER BY date_col ROWS BETWEEN 6 PRECEDING AND CURRENT ROW\n) AS moving_avg_7d\n\nLAG(value, 1) OVER (PARTITION BY entity ORDER BY date_col) AS prev_value\nLEAD(value, 1) OVER (PARTITION BY entity ORDER BY date_col) AS next_value\n\nrevenue \u002F NULLIF(SUM(revenue) OVER (), 0) AS pct_of_total\nrevenue \u002F NULLIF(SUM(revenue) OVER (PARTITION BY category), 0) AS pct_of_category\n```\n\n### CTE Structure\n\n```sql\nWITH\nbase_users AS (\n  SELECT user_id, created_at, plan_type\n  FROM users\n  WHERE created_at >= DATE '2024-01-01'\n    AND status = 'active'\n),\nuser_metrics AS (\n  SELECT\n    u.user_id,\n    u.plan_type,\n    COUNT(DISTINCT e.session_id) AS session_count,\n    SUM(e.revenue) AS total_revenue\n  FROM base_users u\n  LEFT JOIN events e ON u.user_id = e.user_id\n  GROUP BY u.user_id, u.plan_type\n),\nsummary AS (\n  SELECT\n    plan_type,\n    COUNT(*) AS user_count,\n    AVG(session_count) AS avg_sessions,\n    SUM(total_revenue) AS total_revenue\n  FROM user_metrics\n  GROUP BY plan_type\n)\nSELECT *\nFROM summary\nORDER BY total_revenue DESC;\n```\n\n### Funnel Analysis\n\n```sql\nWITH funnel AS (\n  SELECT\n    user_id,\n    MAX(CASE WHEN event = 'page_view' THEN 1 ELSE 0 END) AS step_1_view,\n    MAX(CASE WHEN event = 'signup_start' THEN 1 ELSE 0 END) AS step_2_start,\n    MAX(CASE WHEN event = 'signup_complete' THEN 1 ELSE 0 END) AS step_3_complete,\n    MAX(CASE WHEN event = 'first_purchase' THEN 1 ELSE 0 END) AS step_4_purchase\n  FROM events\n  WHERE event_date >= CURRENT_DATE - INTERVAL '30 days'\n  GROUP BY user_id\n)\nSELECT\n  COUNT(*) AS total_users,\n  SUM(step_1_view) AS viewed,\n  SUM(step_2_start) AS started_signup,\n  SUM(step_3_complete) AS completed_signup,\n  SUM(step_4_purchase) AS purchased,\n  ROUND(100.0 * SUM(step_2_start) \u002F NULLIF(SUM(step_1_view), 0), 1) AS view_to_start_pct,\n  ROUND(100.0 * SUM(step_3_complete) \u002F NULLIF(SUM(step_2_start), 0), 1) AS start_to_complete_pct,\n  ROUND(100.0 * SUM(step_4_purchase) \u002F NULLIF(SUM(step_3_complete), 0), 1) AS complete_to_purchase_pct\nFROM funnel;\n```\n\n### Deduplication\n\n```sql\nWITH ranked AS (\n  SELECT\n    *,\n    ROW_NUMBER() OVER (\n      PARTITION BY entity_id\n      ORDER BY updated_at DESC\n    ) AS rn\n  FROM source_table\n)\nSELECT *\nFROM ranked\nWHERE rn = 1;\n```\n\n## Debugging\n\nWhen a query fails:\n1. Syntax: check dialect-specific syntax.\n2. Column not found: verify schema, spelling, and case sensitivity.\n3. Type mismatch: cast explicitly.\n4. Division by zero: use `NULLIF` or safe division.\n5. Ambiguous column: qualify with table aliases.\n6. Grouping error: ensure non-aggregated columns are grouped.\n7. Wrong result shape: check grain, join cardinality, and deduplication.\n\n## Validation Queries\n\nFor analytical queries, add checks:\n- Input row counts by source table.\n- Date range coverage.\n- Distinct key counts before and after joins.\n- Duplicate key checks.\n- Null rates for join keys and metric columns.\n- Aggregate reconciliation against known totals.\n","\u003C!-- AUTO-GENERATED from SKILL.md.tmpl - do not edit directly -->\n\u003C!-- Regenerate: npm run skills:generate -->\n\n# SQL Queries\n\n## Productize Preamble\n\nBefore producing the artifact, implementation step, or code change, classify the work:\n\n- **User\u002Fpersona**: founder, product leader, AI PM, AI builder, stakeholder, or mixed\u002Funknown.\n- **Product stage**: idea, validation, PMF search, growth, scale, pivot, or unknown.\n- **Artifact mode**: strategy memo, PRD, research plan, positioning, experiment, deck, roadmap, execution brief, diagnostic, or decision record.\n- **Artifact format**: Markdown for short, repo-native, diff-sensitive artifacts; self-contained HTML for long, visual, shareable, interactive, or explicitly requested artifacts.\n- **Evidence standard**: what is known, assumed, missing, and risky.\n- **Decision mode**: recommend, ask for a blocking input, or proceed with explicit assumptions.\n\nOperating rules:\n\n1. Do not produce generic product strategy filler. Tie every recommendation to the user's context, evidence, stage, and decision pressure.\n2. Separate facts from assumptions. Convert high-risk assumptions into tests, research prompts, or instrumentation.\n3. Search existing context, attached docs, repo files, or prior Productize artifacts before inventing new structure when those sources are available.\n4. Ask only for inputs that materially change the output. If the next step is obvious, proceed and state assumptions.\n5. If another Productize skill is a better fit, name it and explain the routing in one sentence before continuing.\n6. Enforce the output contract for this skill. Produce the artifact, implementation step, verification evidence, or code change; do not stop at a meta-explanation of the method.\n7. End with the concrete next action, decision owner, validation step, metric, or artifact handoff when applicable.\n8. Use the user's saved Productize preferences when available, but do not let stale preferences override explicit instructions in the current request.\n9. If you must ask a blocking question, use this compact format: `AskUserQuestion: \u003Cone question> Why it matters: \u003Cdecision it changes>`.\n10. Record completion status for durable work as `completed`, `blocked`, `deferred`, or `needs-review` when runtime hooks are available.\n\nArtifact format policy:\n\n- Default to Markdown for short notes, repo-native documentation, changelog fragments, or artifacts where clean source diffs matter.\n- Use a self-contained HTML file when the user asks for HTML, the artifact is likely to exceed about 100 lines, the reader needs diagrams\u002Ftables\u002Fcomparisons\u002Fscreenshots, the artifact is meant to be shared, or interaction\u002Fexport controls would help the user stay in the loop.\n- Route by product job first, then choose the format. Do not create a generic HTML workflow when a Productize playbook, gate, or routed skill owns the work.\n- HTML artifacts must be local-first and portable: one file, embedded CSS\u002FJS, no remote dependencies unless explicitly requested, readable without a dev server, responsive, accessible, and easy to skim.\n- Prefer semantic sections, tables, SVG diagrams, annotated code blocks, status chips, collapsible detail, and copy\u002Fexport buttons when they improve review speed. Avoid decorative complexity that hides the decision.\n- For implementation work with ambiguities, use `$implementation-notes` when the user asks for a running notes file, especially `implementation-notes.html` or `implementation-notes.md`.\n\nRuntime hooks, if available:\n\n- Use `productize-workflow start \"\u003Cuser request>\"` at the beginning of durable product work; it restores context, routes the request, records the session, and returns the required artifact contract.\n- Use `productize-workflow complete --id \u003Cid> --status completed|blocked|deferred|needs-review --artifact-type \u003Ctype> --summary \u003Csummary>` before ending durable product work; it records the artifact, saves context, and logs completion status.\n- Use `productize-update-check --strict` at the start of maintenance, setup, release, or generated-output work.\n- Use `productize-config` to read or write user\u002Fteam preferences such as persona, artifact mode, evidence threshold, or update-check policy.\n- Use `productize-session-log` to record important workflow decisions.\n- Use `productize-artifact-log` when a durable artifact is produced.\n- Use `productize-context-restore` before restarting long-running product work from scratch.\n- Use `productize-context-save` after producing a durable strategy, research, spec, or stakeholder artifact.\n- Use `productize-registry-search` or `productize-skill-router` when routing is ambiguous.\n- Use `productize-completion-status` to log whether the workflow completed, blocked, deferred, or needs review.\n\nTelemetry standard:\n\n- Keep telemetry local by default in `.productize\u002F` or `PRODUCTIZE_STATE_DIR`.\n- Log artifact type, routing decision, evidence gaps, and completion status; do not log secrets or private customer data unless the user explicitly asks for it.\n\nCurrent skill metadata:\n\n- **Skill**: `sql-queries`\n- **Lifecycle**: Measure\n- **Category**: Analytics\n- **Primary artifact**: SQL Queries analytics diagnosis with metric readout, caveats, decision, and next instrumented step\n\nHelper skill for writing correct, performant, readable SQL across major warehouse dialects.\n\n## Invocation\n\nThis is primarily a support skill for `analyze`, `explore-data`, `metrics-review`, `create-viz`, `build-dashboard`, and `data-context-extractor`. Use it explicitly when dialect-specific SQL guidance is needed.\n\n## Core Rules\n\n- Identify the SQL dialect before writing syntax-sensitive queries.\n- Prefer readable CTEs for multi-step analysis.\n- Qualify columns with table aliases in joins.\n- Protect division with `NULLIF(denominator, 0)` or dialect-safe functions.\n- Avoid `SELECT *` in analytical warehouse queries unless profiling a small table.\n- Filter partition\u002Fdate columns early on large tables.\n- State assumptions about grain, filters, timezone, and deduplication.\n- Include validation queries for non-trivial analysis.\n\n## Dialect Reference\n\n### PostgreSQL, Aurora, RDS, Supabase, Neon\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE, CURRENT_TIMESTAMP, NOW()\ndate_column + INTERVAL '7 days'\ndate_column - INTERVAL '1 month'\nDATE_TRUNC('month', created_at)\nEXTRACT(YEAR FROM created_at)\nEXTRACT(DOW FROM created_at) -- 0=Sunday\nTO_CHAR(created_at, 'YYYY-MM-DD')\n```\n\nStrings, arrays, JSON:\n\n```sql\nfirst_name || ' ' || last_name\nCONCAT(first_name, ' ', last_name)\ncolumn ILIKE '%pattern%'\ncolumn ~ '^regex_pattern$'\nSPLIT_PART(str, delimiter, position)\ndata->>'key'\ndata->'nested'->'key'\ndata#>>'{path,to,key}'\nARRAY_AGG(column)\narray_column @> ARRAY['value']\n```\n\nPerformance:\n- Use `EXPLAIN ANALYZE`.\n- Index frequently filtered or joined columns.\n- Consider partial indexes for common filters.\n- Use `EXISTS` over correlated `IN` when appropriate.\n\n### Snowflake\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP(), SYSDATE()\nDATEADD(day, 7, date_column)\nDATEDIFF(day, start_date, end_date)\nDATE_TRUNC('month', created_at)\nYEAR(created_at), MONTH(created_at), DAY(created_at)\nDAYOFWEEK(created_at)\nTO_CHAR(created_at, 'YYYY-MM-DD')\n```\n\nSemi-structured data:\n\n```sql\ncolumn ILIKE '%pattern%'\nREGEXP_LIKE(column, 'pattern')\ndata:customer:name::STRING\ndata:items[0]:price::NUMBER\n\nSELECT\n  t.id,\n  item.value:name::STRING AS item_name,\n  item.value:qty::NUMBER AS quantity\nFROM my_table t,\nLATERAL FLATTEN(input => t.data:items) item;\n```\n\nPerformance:\n- Use clustering keys on large tables.\n- Filter on clustering columns for pruning.\n- Use appropriate warehouse size.\n- Use `RESULT_SCAN(LAST_QUERY_ID())` to avoid rerunning expensive queries.\n- Use transient tables for staging.\n\n### BigQuery\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP()\nDATE_ADD(date_column, INTERVAL 7 DAY)\nDATE_SUB(date_column, INTERVAL 1 MONTH)\nDATE_DIFF(end_date, start_date, DAY)\nTIMESTAMP_DIFF(end_ts, start_ts, HOUR)\nDATE_TRUNC(created_at, MONTH)\nTIMESTAMP_TRUNC(created_at, HOUR)\nEXTRACT(YEAR FROM created_at)\nEXTRACT(DAYOFWEEK FROM created_at) -- 1=Sunday\nFORMAT_DATE('%Y-%m-%d', date_column)\n```\n\nStrings, arrays, structs:\n\n```sql\nLOWER(column) LIKE '%pattern%'\nREGEXP_CONTAINS(column, r'pattern')\nREGEXP_EXTRACT(column, r'pattern')\nSPLIT(str, delimiter)\nARRAY_TO_STRING(array, delimiter)\nARRAY_AGG(column)\nUNNEST(array_column)\nARRAY_LENGTH(array_column)\nvalue IN UNNEST(array_column)\nstruct_column.field_name\n```\n\nPerformance:\n- Always filter partition columns to reduce bytes scanned.\n- Use clustering for frequent filters within partitions.\n- Use `APPROX_COUNT_DISTINCT()` for large-cardinality estimates.\n- Avoid `SELECT *` because billing is per byte scanned.\n- Use dry runs for expensive queries.\n\n### Redshift\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE, GETDATE(), SYSDATE\nDATEADD(day, 7, date_column)\nDATEDIFF(day, start_date, end_date)\nDATE_TRUNC('month', created_at)\nEXTRACT(YEAR FROM created_at)\nDATE_PART('dow', created_at)\n```\n\nStrings:\n\n```sql\ncolumn ILIKE '%pattern%'\nREGEXP_INSTR(column, 'pattern') > 0\nSPLIT_PART(str, delimiter, position)\nLISTAGG(column, ', ') WITHIN GROUP (ORDER BY column)\n```\n\nPerformance:\n- Choose DISTKEY for collocated joins.\n- Choose SORTKEY for frequent filters.\n- Use `EXPLAIN` to inspect plans.\n- Watch for cross-node movement.\n- Run `ANALYZE` and `VACUUM` regularly.\n\n### Databricks SQL\n\nDate\u002Ftime:\n\n```sql\nCURRENT_DATE(), CURRENT_TIMESTAMP()\nDATE_ADD(date_column, 7)\nDATEDIFF(end_date, start_date)\nADD_MONTHS(date_column, 1)\nDATE_TRUNC('MONTH', created_at)\nTRUNC(date_column, 'MM')\nYEAR(created_at), MONTH(created_at)\nDAYOFWEEK(created_at)\n```\n\nDelta Lake:\n\n```sql\nSELECT * FROM my_table TIMESTAMP AS OF '2024-01-15';\nSELECT * FROM my_table VERSION AS OF 42;\nDESCRIBE HISTORY my_table;\n\nMERGE INTO target USING source\nON target.id = source.id\nWHEN MATCHED THEN UPDATE SET *\nWHEN NOT MATCHED THEN INSERT *;\n```\n\nPerformance:\n- Use Delta `OPTIMIZE` and `ZORDER`.\n- Use Photon for compute-heavy workloads when available.\n- Cache frequently accessed datasets.\n- Partition by low-cardinality date columns.\n\n## Common Patterns\n\n### Window Functions\n\n```sql\nROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)\nRANK() OVER (PARTITION BY category ORDER BY revenue DESC)\nDENSE_RANK() OVER (ORDER BY score DESC)\n\nSUM(revenue) OVER (\n  ORDER BY date_col ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n) AS running_total\n\nAVG(revenue) OVER (\n  ORDER BY date_col ROWS BETWEEN 6 PRECEDING AND CURRENT ROW\n) AS moving_avg_7d\n\nLAG(value, 1) OVER (PARTITION BY entity ORDER BY date_col) AS prev_value\nLEAD(value, 1) OVER (PARTITION BY entity ORDER BY date_col) AS next_value\n\nrevenue \u002F NULLIF(SUM(revenue) OVER (), 0) AS pct_of_total\nrevenue \u002F NULLIF(SUM(revenue) OVER (PARTITION BY category), 0) AS pct_of_category\n```\n\n### CTE Structure\n\n```sql\nWITH\nbase_users AS (\n  SELECT user_id, created_at, plan_type\n  FROM users\n  WHERE created_at >= DATE '2024-01-01'\n    AND status = 'active'\n),\nuser_metrics AS (\n  SELECT\n    u.user_id,\n    u.plan_type,\n    COUNT(DISTINCT e.session_id) AS session_count,\n    SUM(e.revenue) AS total_revenue\n  FROM base_users u\n  LEFT JOIN events e ON u.user_id = e.user_id\n  GROUP BY u.user_id, u.plan_type\n),\nsummary AS (\n  SELECT\n    plan_type,\n    COUNT(*) AS user_count,\n    AVG(session_count) AS avg_sessions,\n    SUM(total_revenue) AS total_revenue\n  FROM user_metrics\n  GROUP BY plan_type\n)\nSELECT *\nFROM summary\nORDER BY total_revenue DESC;\n```\n\n### Funnel Analysis\n\n```sql\nWITH funnel AS (\n  SELECT\n    user_id,\n    MAX(CASE WHEN event = 'page_view' THEN 1 ELSE 0 END) AS step_1_view,\n    MAX(CASE WHEN event = 'signup_start' THEN 1 ELSE 0 END) AS step_2_start,\n    MAX(CASE WHEN event = 'signup_complete' THEN 1 ELSE 0 END) AS step_3_complete,\n    MAX(CASE WHEN event = 'first_purchase' THEN 1 ELSE 0 END) AS step_4_purchase\n  FROM events\n  WHERE event_date >= CURRENT_DATE - INTERVAL '30 days'\n  GROUP BY user_id\n)\nSELECT\n  COUNT(*) AS total_users,\n  SUM(step_1_view) AS viewed,\n  SUM(step_2_start) AS started_signup,\n  SUM(step_3_complete) AS completed_signup,\n  SUM(step_4_purchase) AS purchased,\n  ROUND(100.0 * SUM(step_2_start) \u002F NULLIF(SUM(step_1_view), 0), 1) AS view_to_start_pct,\n  ROUND(100.0 * SUM(step_3_complete) \u002F NULLIF(SUM(step_2_start), 0), 1) AS start_to_complete_pct,\n  ROUND(100.0 * SUM(step_4_purchase) \u002F NULLIF(SUM(step_3_complete), 0), 1) AS complete_to_purchase_pct\nFROM funnel;\n```\n\n### Deduplication\n\n```sql\nWITH ranked AS (\n  SELECT\n    *,\n    ROW_NUMBER() OVER (\n      PARTITION BY entity_id\n      ORDER BY updated_at DESC\n    ) AS rn\n  FROM source_table\n)\nSELECT *\nFROM ranked\nWHERE rn = 1;\n```\n\n## Debugging\n\nWhen a query fails:\n1. Syntax: check dialect-specific syntax.\n2. Column not found: verify schema, spelling, and case sensitivity.\n3. Type mismatch: cast explicitly.\n4. Division by zero: use `NULLIF` or safe division.\n5. Ambiguous column: qualify with table aliases.\n6. Grouping error: ensure non-aggregated columns are grouped.\n7. Wrong result shape: check grain, join cardinality, and deduplication.\n\n## Validation Queries\n\nFor analytical queries, add checks:\n- Input row counts by source table.\n- Date range coverage.\n- Distinct key counts before and after joins.\n- Duplicate key checks.\n- Null rates for join keys and metric columns.\n- Aggregate reconciliation against known totals.\n",{"name":5,"description":7},"main","f177680a573a242a81bd0a776f9681f620e6d74c","skills\u002Fproductize-sql-queries",0,"https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize","https:\u002F\u002Fgithub.com\u002Fitseffi","2026-08-07 20:07:32",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add itseffi\u002Fproductize --skill productize-sql-queries",{"tool":37,"command":38},"bunx","bunx skills add itseffi\u002Fproductize --skill productize-sql-queries",{"tool":40,"command":41},"pnpm","pnpm dlx skills add itseffi\u002Fproductize --skill productize-sql-queries","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-sql-queries\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"agents\u002Fopenai.yaml","REFERENCE","参考文档",319,"https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-sql-queries\u002Fagents\u002Fopenai.yaml",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7357QB5M87V95F82E73V2TF","workflow-memory","Maintains workflow-scoped task memory for Productize runs using .productize\u002Ftasks\u002F\u003Cname>\u002Fmemory\u002F files. Use when a task prompt provides workflow memory paths and requires the agent to read, update, compact, and promote durable context across PRD task executions. Do not use for PR review remediation, global user preferences, or programmatic event-log summarization.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fworkflow-memory\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7357K97HSYEHAQTW5ZKM4CE","review-round","Performs a comprehensive code review of a PRD implementation and generates a review round directory with issue files compatible with fix-reviews. Use when reviewing implemented PRD tasks, creating a manual review round without an external provider, or performing a quality audit of code changes. Do not use for fetching reviews from external providers, fixing existing review issues, executing PRD tasks, or editing source code.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Freview-round\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7357F2NZE5NSYM2SJXEGBFZ","productize","Productize root skill for building, shipping, operating, and growing AI products inside a coding harness. Routes work across thesis framing, discovery, research, positioning, finance, decision making, requirements, design, metrics, AI-builder execution, code implementation, verification, stakeholder narratives, growth, launch, operation, and learning workflows. Use when the user wants to build a product from zero, improve an existing product, or needs product work that spans multiple lifecycle stages before code, launch, operation, or growth execution.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7357B48F8MK86EQF135FJQ6","productize-wwas","Why-What-Acceptance. Use when writing backlog items in Why-What-Acceptance format, breaking features into independent valuable work, or adding strategic context to delivery items.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-wwas\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M735783CDA9MQ0SPR9X6QZSE","productize-writing-plans","Create comprehensive implementation plans with bite-sized tasks. Use when you have requirements before touching code.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-writing-plans\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M735750V5Q6WRBX1ZFGNRMEB","productize-write-spec","Write a feature spec or PRD from a problem statement or feature idea. Use when turning a vague idea into a structured document, scoping goals and non-goals, defining success metrics and acceptance criteria, or breaking a big ask into phases.","https:\u002F\u002Fgithub.com\u002Fitseffi\u002Fproductize\u002Fblob\u002Fmain\u002Fskills\u002Fproductize-write-spec\u002FSKILL.md",[],[]]