Optimizing Query Text logo

Optimizing Query Text

Organization
AltimateAI
optimizing-query-text

Optimizes Snowflake SQL query performance from provided query text. Use when optimizing Snowflake SQL for: (1) User provides or pastes a SQL query and asks to optimize, tune, or improve it (2) Task mentions "slow query", "make faster", "improve performance", "optimize SQL", or "query tuning" (3) Reviewing SQL for performance anti-patterns (function on filter column, implicit joins, etc.) (4) User asks why a query is slow or how to speed it up

Overview

PublisherAltimateAI
Repositorydata-engineering-skills
Skill nameoptimizing-query-text
Stars
133
Forks
12
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by AltimateAI on GitHub. Read the source before you install it.

Installation

Install the Optimizing Query Text AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/AltimateAI/data-engineering-skills/tree/main/skills/snowflake/optimizing-query-text
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AltimateAI/data-engineering-skills.git /tmp/data-engineering-skills
mkdir -p .claude/skills
cp -r /tmp/data-engineering-skills/skills/snowflake/optimizing-query-text .claude/skills/optimizing-query-text
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Optimizing Query Text in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Optimizing Query Text on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Optimizing Query Text is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Optimize Query from SQL Text

OUTPUT FORMAT

Return ONLY the optimized SQL query. No markdown formatting, no explanations, no bullet points - just pure SQL that can be executed directly in Snowflake.

CRITICAL: Semantic Preservation Rules

The optimized query MUST return IDENTICAL results to the original.

Before returning ANY optimization, verify:

  • Same columns: Exact same columns in exact same order with exact same aliases
  • Same rows: Filter conditions must be semantically equivalent
  • Same ordering: Preserve ORDER BY exactly as written
  • Same limits: If original has LIMIT N, keep LIMIT N. If no LIMIT, do NOT add one.

If you cannot guarantee identical results, return the original query unchanged.


Pattern 1: Function on Filter Column

Problem: Functions on columns in WHERE clause prevent partition pruning and index usage.

CAN Fix

OriginalOptimizedWhy Safe
WHERE DATE(ts) = '2024-01-01'WHERE ts >= '2024-01-01' AND ts < '2024-01-02'Equivalent range
WHERE YEAR(dt) = 2024WHERE dt >= '2024-01-01' AND dt < '2025-01-01'Equivalent range
WHERE MONTH(dt) = 3 AND YEAR(dt) = 2024WHERE dt >= '2024-03-01' AND dt < '2024-04-01'Equivalent range
WHERE DATE(ts) >= '2024-01-01' AND DATE(ts) < '2024-02-01'WHERE ts >= '2024-01-01' AND ts < '2024-02-01'Same boundaries
WHERE YEAR(dt) BETWEEN 1995 AND 1996WHERE dt >= '1995-01-01' AND dt < '1997-01-01'Equivalent range

CANNOT Fix

PatternWhy Not
WHERE YEAR(dt) IN (SELECT year FROM ...)Dynamic values, cannot precompute range
WHERE DATE(ts) = DATE(other_col)Comparing two columns, both need function
WHERE EXTRACT(DOW FROM dt) = 1Day-of-week has no contiguous range
WHERE DATE_TRUNC('month', dt) = '2024-01-01' in GROUP BYNeeded for grouping logic
SELECT YEAR(dt) AS yr ... GROUP BY YEAR(dt)Function in SELECT/GROUP BY is fine, only filter matters

Pattern 2: Function on JOIN Column

Problem: Functions on JOIN columns prevent hash joins, forcing slower nested loop joins.

CAN Fix

OriginalOptimizedWhy Safe
ON CAST(a.id AS VARCHAR) = CAST(b.id AS VARCHAR)ON a.id = b.idIf both are same type (e.g., INTEGER)
ON UPPER(a.code) = UPPER(b.code)ON a.code = b.codeIf data is already consistently cased
ON TRIM(a.name) = TRIM(b.name)ON a.name = b.nameIf data has no leading/trailing spaces

CANNOT Fix

PatternWhy Not
ON CAST(a.id AS VARCHAR) = b.string_idTypes genuinely differ, CAST required
ON DATE(a.timestamp) = b.date_colDifferent granularity, DATE() required
ON UPPER(a.code) = b.codeIf b.code might have different case
ON a.id = b.id + 1Arithmetic transformation, cannot remove

Pattern 3: NOT IN Subquery

Problem: NOT IN has poor performance and unexpected NULL behavior.

CAN Fix

OriginalOptimizedWhy Safe
WHERE id NOT IN (SELECT id FROM t WHERE ...)WHERE NOT EXISTS (SELECT 1 FROM t WHERE t.id = main.id AND ...)Equivalent when subquery column is NOT NULL
WHERE id NOT IN (SELECT id FROM t) where id has NOT NULL constraintWHERE NOT EXISTS (SELECT 1 FROM t WHERE t.id = main.id)NOT NULL guarantees equivalence

CANNOT Fix

PatternWhy Not
WHERE id NOT IN (SELECT nullable_col FROM t)If subquery returns NULL, NOT IN returns no rows; NOT EXISTS doesn't
WHERE (a, b) NOT IN (SELECT x, y FROM t)Multi-column NOT IN has complex NULL semantics

Key Rule: Only convert NOT IN to NOT EXISTS if you can verify the subquery column cannot be NULL.


Pattern 4: Repeated Subquery

Problem: Same subquery executed multiple times causes redundant scans.

CAN Fix

OriginalOptimized
Subquery appears 2+ times identicallyExtract to CTE, reference CTE multiple times
Same aggregation used in multiple placesCompute once in CTE

CANNOT Fix

PatternWhy Not
Correlated subquery (references outer table)Each execution is different, cannot cache
Subqueries with different filtersNot actually the same subquery
Subquery in SELECT that depends on current rowCorrelation prevents extraction

Pattern 5: Implicit Comma Joins

Problem: Comma-separated tables in FROM clause are harder to read and optimize.

CAN Fix - Always

Convert FROM a, b, c WHERE a.id = b.id AND b.id = c.id to explicit JOIN syntax.

This is always safe - just restructuring, no semantic change.


UNSAFE Optimizations (NEVER apply)

  • UNION to UNION ALL: UNION deduplicates rows, UNION ALL does not - different results
  • Changing window functions: Do not modify SUM(SUM(x)) OVER(...) or similar nested aggregates
  • Adding redundant filters: Do not add filters in JOIN ON if same filter exists in WHERE
  • Changing column names: Copy column names EXACTLY from original - do not "simplify" or rename
  • Changing column aliases: Keep all aliases exactly as original
  • Adding early filtering in JOINs: If a filter is in WHERE, do not duplicate it in JOIN ON clause

Principles

  1. Minimal changes: Make the fewest changes necessary. Simpler optimizations are more reliable.
  2. Preserve structure: Keep subqueries, CTEs, and overall query structure unless there's a clear benefit.
  3. When in doubt, don't: If unsure whether a change preserves semantics, skip it.
  4. Copy exactly: Column names, table aliases, and expressions should be copied character-for-character.

Priority Order

  1. Date/time functions on filter columns - Highest impact
  2. Implicit joins to explicit JOIN - Always safe, improves readability
  3. NOT IN to NOT EXISTS - Only if NULL-safe

Requirements

  • Results must be identical: Same rows, same columns, same order
  • Valid Snowflake SQL: Output must execute without errors in Snowflake

Frequently asked questions

What does the Optimizing Query Text AI skill do?

Optimizes Snowflake SQL query performance from provided query text. Use when optimizing Snowflake SQL for: (1) User provides or pastes a SQL query and asks to optimize, tune, or improve it (2) Task mentions "slow query", "make faster", "improve performance", "optimize SQL", or "query tuning" (3) Reviewing SQL for performance anti-patterns (function on filter column, implicit joins, etc.) (4) User asks why a query is slow or how to speed it up

Why use Optimizing Query Text on TypingMind?

Because you install it once and use it with any model. Optimizing Query Text is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Optimizing Query Text in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/AltimateAI/data-engineering-skills/tree/main/skills/snowflake/optimizing-query-text. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Optimizing Query Text?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Optimizing Query Text?

As many as you like. As long as a model supports skills, you can use Optimizing Query Text with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Optimizing Query Text AI skill free?

Yes. It is published on GitHub by AltimateAI under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇