The Art of AI-Assisted Query Tuning: When Your SQL Needs a Little… Persuasion

by

in

If the last post was about using AI to argue with your SQL, this one is about using AI to negotiate with it — the way JR Ewing negotiated: confidently, with a smirk, and fully prepared to expose what someone doesn’t want you to see.

Welcome to the next chapter in this Snowflake + AI series. Today we’re talking AI-assisted optimization, practical tuning patterns, and the “here’s where AI saves your bacon” moments every data pro knows too well.


AI-Driven Performance Triage: Your New Second Opinion

Think of Snowflake Cortex as the consultant you bring in when your query goes over budget… again. The one who walks into the room, glances at your 730-line SQL beast, and says:

“Oh honey, you cross-joined half the warehouse and didn’t even notice, did you?”

You know — friendly, but savage.

Now you can send Cortex your worst-performing query and ask it to:

Identify bottlenecks

SELECT SNOWFLAKE.CORTEX.ANALYZE(
    'sql_explainer',
    $$ SELECT * 
       FROM bigtable a 
       JOIN bigtable b ON a.id > b.id 
       WHERE DATE(a.created_at) = CURRENT_DATE() $$,
    { "detail": "performance" }
);

It’ll call out things like:

  • Accidental CROSS JOINs
  • Expressions that destroy pruning
  • Window functions doing heavy lifting they weren’t designed for
  • Filters that force full scans
  • Redundant logic nested like Russian dolls

Suggest structural improvements

SELECT SNOWFLAKE.CORTEX.ANALYZE(
    'sql_optimizer',
    $$ SELECT ... complex query ... $$,
    { "suggest": "rewrite" }
);

This is where it politely informs you that your CTE stack is almost as big as Texas. Almost…


AI-Assisted Indexing & Modeling Checks (Snowflake Style)

Snowflake doesn’t do traditional indexes, but it does rely on:

  • Clustering
  • Micro-partition pruning
  • Search Optimization
  • Good columnar hygiene

Cortex can guide you with advice like:

  • “Clustering on (col1, col2) will actually help here.”
  • “Stop wrapping your date columns in functions. Let pruning do its thing.”
  • “A Search Optimization service is way cheaper than brute-force compute.”

For example:

SELECT SNOWFLAKE.CORTEX.ANALYZE(
    'sql_explainer',
    $$ SELECT * FROM sales WHERE YEAR(order_date) = 2023 $$,
    { "detail": "pruning" }
);

Wrapping your date columns is the Snowflake equivalent of putting your keys in the best hiding spot, then getting mad when it’s not the first 3 places you look.


Rewriting Queries the JR Way: Sharp, Clean, and Just a Bit Smug

Sometimes you don’t just want analysis — you just want the SQL cleaned up and ready to strut.

SELECT SNOWFLAKE.CORTEX.REWRITE(
    'sql_rewriter',
    $$ SELECT * FROM orders o 
       JOIN customers c ON o.cust_id = c.id 
       WHERE LOWER(TRIM(c.state)) = 'tx' $$,
    { "style": "performance" }
);

Expect:

  • Pushed-down predicates
  • Reduced function calls
  • Better join structure
  • More efficient filtering
  • Leaner logic in general

It’s like handing your SQL a tailored suit and cufflinks.


Telemetry + AI: Query Forensics You Can Actually Use

Pair Cortex with Snowflake’s built-in goodness:

  • QUERY_HISTORY
  • WAREHOUSE_METERING_HISTORY
  • QUERY_ACCELERATION_HISTORY
  • AUTOMATIC_CLUSTERING_HISTORY

…and let AI summarize anomalies:

SELECT SNOWFLAKE.CORTEX.ANALYZE(
    'data_summary',
    TABLE(
        SELECT *
        FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
        WHERE START_TIME >= DATEADD('day', -1, CURRENT_TIMESTAMP())
    ),
    { "focus": "anomalies" }
);

Cortex will point out things like:

  • Dashboard queries suddenly doubling in cost
  • New jobs consuming way more than the normal number of credits
  • Joins that unexpectedly balloon output

It’s JR-level “know the room before you walk in” intelligence.


Real-World Example: Fixing a Warehouse Burn Rate Spike

Let’s get practical.

Your warehouse costs jump 40% overnight. Instead of guessing (or blaming the nearest BI developer), use AI to diagnose it.

1. Identify the top offenders

WITH offenders AS (
    SELECT
        QUERY_ID,
        QUERY_TEXT,
        CREDITS_USED,
        BYTES_SCANNED,
        ROWS_PRODUCED,
        START_TIME
    FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
    WHERE START_TIME >= DATEADD('hour', -2, CURRENT_TIMESTAMP())
      AND QUERY_TEXT IS NOT NULL
    ORDER BY CREDITS_USED DESC
    LIMIT 20
)
SELECT * FROM offenders;

2. Send the ugliest one to Cortex

SELECT SNOWFLAKE.CORTEX.ANALYZE(
    'sql_explainer',
    (SELECT QUERY_TEXT FROM offenders LIMIT 1),
    { "detail": "performance" }
);

3. Ask for a rewritten version

SELECT SNOWFLAKE.CORTEX.REWRITE(
    'sql_optimizer',
    (SELECT QUERY_TEXT FROM offenders LIMIT 1),
    { "style": "performance" }
);

4. Measure the before/after

ALTER SESSION SET QUERY_TAG = 'optimization_test';

Compare bytes scanned, rows scanned, duration, pruning, and memory usage.

5. Fix the root cause

Common culprits:

  • BI dashboards are refreshing too frequently
  • Logic moved into the BI layer instead of SQL
  • Joins generating “infinite enthusiasm” row counts
  • Date logic breaking pruning

Like JR always said:
“It’s not personal. It’s business. And your query is bad for business.”


Wrap-Up

AI-assisted optimization makes tuning faster, cheaper, and (let’s be honest) a whole lot less painful. With Snowflake Cortex, you can go beyond guesswork and get real, explainable intelligence about what your SQL is doing — and what it should be doing instead.

After working with Snowflake Cortex, your queries should be cleaner than an Ewing family cover-up, so kick your feet up, cue the Dallas theme, and enjoy a moment of peace before someone deploys something reckless again.