Zero Labs
Industry News / AI

Stop Writing Cost Queries. Just Ask Cortex Code.

Source · Towards AI By Satish Kumar

From the publisher’s feed, collected in the ZeroLabs newsroom.

The complete cost-intelligence prompt playbook — every question, what the skill does, and the SQL it generates under the hood.The shift that happened quietlyFor years, FinOps on Snowflake meant opening a worksheet, remembering which ACCOUNT_USAGE view you needed, writing a CTE-heavy SQL query, and hoping you got the date math right.That workflow still works. But there’s a faster path now.Open Cortex Code in Snowsight. Ask your cost question in plain English:"Which workloads had unusual cost spikes in the last 24 hours?""Where is my money going?""Which budgets are at risk of going over their limit?"Cortex Code detects the cost intent, activates the cost-intelligence skill, routes your question to the right ACCOUNT_USAGE view, assembles production-grade SQL, executes it against your live account data, and returns an answer — with an offer to drill deeper. No context switching. No external tools. No stale dashboards.This article is the complete playbook: every cost-intelligence prompt organized by category, what the skill does behind the scenes, and the SQL it generates. Whether you’re using the skill conversationally or building your own cost governance workflows, this is the reference.What you’ll know by the end of this postHow cost intelligence works inside Cortex Code — and how to activate itThe complete prompt library organized by domain — 60+ prompts across 14 categoriesWhat the skill actually does for each category (which views, which SQL patterns)The production SQL behind the most important prompts, annotatedThe caveats that determine whether your results are trustworthyHow to chain prompts for investigative workflows — from anomaly to root cause to fixTLDR⚡ Quick TakeCortex Code activates cost intelligence automatically when you ask cost-related questions — no special command syntax requiredIt covers 14 cost domains: spend baseline, warehouses, trends, users, Cortex AI, anomalies, budgets, chargebacks, storage, serverless, containers, data transfer, optimization, and continuous governanceThe skill translates plain-English questions into verified ACCOUNT_USAGE SQL — no query authoring requiredAnomaly detection uses native Snowflake procedures (ANOMALY_INSIGHTS) for statistical deviation — not just threshold checksCortex AI cost queries enforce a maximum 1-month time window — narrower than general cost queriesEvery query generated appears in QUERY_HISTORY — fully auditableYour data never leaves Snowflake. No external tools. Governed by your existing RBAC.How cost intelligence works in Cortex CodeOpen Snowsight. Start a Cortex Code chat. Ask any cost-related question in natural language:┌─────────────────────────────────────────────────────────────┐│ 🤖 Cortex Code — Cost Intelligence ││ ││ Here's your credit breakdown for the last 7 days: ││ ││ service_type | total_credits | pct_of_total ││ VIRTUAL_WAREHOUSE | 4,821.40 | 67.3% ││ CORTEX_AI | 1,102.80 | 15.4% ││ SNOWPARK_CONTAINER_SVCS | 834.20 | 11.6% ││ SERVERLESS_TASKS | 302.10 | 4.2% ││ STORAGE | 97.60 | 1.4% ││ ││ Virtual warehouses are your largest spend at 67%. ││ Want me to break down Cortex AI by service? │└─────────────────────────────────────────────────────────────┘No special invocation. No slash command. Cortex Code detects cost intent from your question and routes to the appropriate skill and views automatically.Before your first prompt: the one setup step that unlocks chargebacksIf your account has no tags, chargeback queries will return empty results. Set these up before running any team attribution prompts:-- Create a cost center tag (run once, before using chargeback prompts)CREATE TAG IF NOT EXISTS COST_CENTER ALLOWED_VALUES = ('data_engineering', 'analytics', 'ml_platform', 'finance', 'marketing');-- Apply to each warehouse you want to attributeALTER WAREHOUSE COMPUTE_WH SET TAG COST_CENTER = 'data_engineering';-- Verify the tag is appliedSELECT object_name, tag_name, tag_value, domainFROM TABLE(INFORMATION_SCHEMA.TAG_REFERENCES_ALL_COLUMNS('COMPUTE_WH', 'WAREHOUSE'));Critical timing note: TAG_REFERENCES in ACCOUNT_USAGE carries up to 2-hour latency after a tag is applied. Apply tags, wait two hours, then run chargeback prompts. This is the most common setup failure on new accounts.The ACCOUNT_USAGE cost surface — what the skill queries acrossThe skill routes prompts across 40+ views and native class procedures. Note the important distinction: ANOMALY_INSIGHTS and COST_INSIGHTS are native class procedures (invoked via CALL) — the skill routes to them automatically, not via direct SELECT. ANOMALIES_DAILY is a view that provides the same anomaly data for users with direct view access.Category 1: Spend baseline and overviewUse these prompts to establish what “normal” looks like before hunting anomalies."Where is my money going?""Show me a breakdown of all credit consumption by service type for the last 7 days""How many credits were used last week?""Which service is consuming the most money?""What are my top 10 most expensive workloads this month?""Show me a complete breakdown of spending""Which are the 5 most expensive warehouses, compute pools, databases?""Total credits used last week"What the skill does: Queries METERING_HISTORY with a window aggregate to rank service types by total credits and percentage of spend. For "top resources," it unions WAREHOUSE_METERING_HISTORY and SNOWPARK_CONTAINER_SERVICES_HISTORY into a single cross-category ranking.-- Skill-generated SQL for "Where is my money going?"SELECT service_type, ROUND(SUM(credits_used), 2) AS total_credits, ROUND(SUM(credits_used) / SUM(SUM(credits_used)) OVER () * 100, 1) AS pct_of_totalFROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORYWHERE start_time >= DATEADD(DAY, -7, CURRENT_DATE()) AND start_time GROUP BY service_typeORDER BY total_credits DESC;Run this weekly. Build your baseline intuition. When something looks different, investigate before the invoice arrives.Category 2: Warehouse cost analysisUse these prompts to understand compute — almost always the biggest line item."Which warehouses consumed the most credits last week?""Which warehouses increased compute spend by more than 40% this week?""Which warehouses saw the largest change in month cost?""Have any warehouses been resized recently?""Which warehouses used the most query acceleration service credits this month?""Warehouse comparison — last 14 days vs prior 14 days"What the skill does: Routes to WAREHOUSE_METERING_HISTORY for credit totals, WAREHOUSE_EVENTS_HISTORY for resize events, and QUERY_ACCELERATION_HISTORY for QAS credits. Period-over-period comparisons use a FULL OUTER JOIN on two CTEs partitioned by date range — returning all warehouses ranked by absolute change, with your specified threshold applied as a filter.┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Which warehouses increased compute spend by more than ││ 40% this week? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ ││ warehouse_name | prior_wk | curr_wk | pct_change ││ TRANSFORM_WH | 420.10 | 1,102.40 | +162.4% ││ DS_SANDBOX_WH | 88.30 | 143.60 | +62.6% ││ ││ TRANSFORM_WH is a significant outlier at +162%. ││ Want me to drill into QUERY_HISTORY for TRANSFORM_WH ││ to find the top credit-consuming queries this week? │└─────────────────────────────────────────────────────────────┘-- Skill-generated SQL for warehouse period comparisonWITH recent AS ( SELECT warehouse_name, SUM(credits_used) AS credits FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY WHERE start_time >= DATEADD(day, -14, CURRENT_DATE()) GROUP BY warehouse_name),prior AS ( SELECT warehouse_name, SUM(credits_used) AS credits FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY WHERE start_time >= DATEADD(day, -28, CURRENT_DATE()) AND start_time GROUP BY warehouse_name)SELECT COALESCE(r.warehouse_name, p.warehouse_name) AS warehouse_name, ROUND(COALESCE(p.credits, 0), 2) AS prior_14_days, ROUND(COALESCE(r.credits, 0), 2) AS recent_14_days, ROUND(COALESCE(r.credits, 0) - COALESCE(p.credits, 0), 2) AS change, ROUND(((COALESCE(r.credits, 0) - COALESCE(p.credits, 0)) / NULLIF(p.credits, 0)) * 100, 1) AS pct_changeFROM recent rFULL OUTER JOIN prior p ON r.warehouse_name = p.warehouse_nameORDER BY ABS(COALESCE(r.credits, 0) - COALESCE(p.credits, 0)) DESCLIMIT 15;Category 3: Trend analysisUse these to answer “why is my bill higher?” — the most common FinOps question."How did my Snowflake spend change compared to the previous week?""How did my Snowflake spend change compared to last month?""Why has my cost increased?""What's causing my cost spike?""Why is my bill higher?""Which services increased costs in the last 14 days?""Compare month-over-month storage costs across environments"What the skill does: Pairs a current-period and prior-period CTE against METERING_HISTORY, then surfaces the service types with the largest absolute and percentage change. "Why is my bill higher?" triggers a root-cause decomposition ranked by credit_increase DESC.-- Skill-generated SQL for "Why has my cost increased?"WITH monthly_service_costs AS ( SELECT DATE_TRUNC('month', start_time) AS cost_month, service_type, SUM(credits_used) AS total_credits FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY WHERE start_time >= DATE_TRUNC('month', DATEADD('month', -2, CURRENT_DATE())) GROUP BY 1, 2),service_comparison AS ( SELECT service_type, SUM(CASE WHEN cost_month = DATE_TRUNC('month', CURRENT_DATE()) THEN total_credits ELSE 0 END) AS current_month_credits, SUM(CASE WHEN cost_month = DATE_TRUNC('month', DATEADD('month', -1, CURRENT_DATE())) THEN total_credits ELSE 0 END) AS previous_month_credits FROM monthly_service_costs GROUP BY service_type),service_increases AS ( SELECT service_type, current_month_credits, previous_month_credits, current_month_credits - previous_month_credits AS credit_increase, CASE WHEN previous_month_credits > 0 THEN ROUND(((current_month_credits - previous_month_credits) / previous_month_credits) * 100, 2) ELSE NULL END AS percentage_increase FROM service_comparison WHERE current_month_credits > previous_month_credits)SELECT * FROM service_increasesORDER BY credit_increase DESC;Category 4: User and query cost attributionUse these to find who and what is driving spend — not just which warehouse."Which individual queries consumed the most compute credits last week?""What are the top 5 queries grouped by parameterized hash?""Which parameterized queries were the most expensive last week?""What users are spending the most?""Who are the top-5 users with the greatest increase in query cost?""Which are the top 5 individuals who ran up the biggest bills?"What the skill does: Routes to QUERY_ATTRIBUTION_HISTORY — not QUERY_HISTORY. This is the critical distinction. Only QUERY_ATTRIBUTION_HISTORY carries credits_attributed_compute at the individual query level. For "parameterized hash" prompts, it groups by query_parameterized_hash to find expensive query patterns across thousands of executions.┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ What are the top 5 queries grouped by parameterized hash? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ ││ hash | total_credits | exec_count | avg_per_run ││ a1b2c3d4... | 842.30 | 14,201 | 0.0593 ││ e5f6g7h8... | 611.10 | 892 | 0.6851 ││ i9j0k1l2... | 388.40 | 44,103 | 0.0088 ││ ││ The second pattern (e5f...) runs 7x less often but costs ││ 12x more per execution. Want me to pull an example query ││ ID to inspect the actual SQL? │└─────────────────────────────────────────────────────────────┘-- Skill-generated SQL for parameterized hash analysisSELECT query_parameterized_hash, ROUND(SUM(credits_attributed_compute), 2) AS total_credits, COUNT(query_id) AS execution_count, ROUND(SUM(credits_attributed_compute) / NULLIF(COUNT(query_id), 0), 4) AS avg_credits_per_execution, ANY_VALUE(query_id) AS example_query_idFROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_ATTRIBUTION_HISTORYWHERE start_time >= DATEADD(DAY, -7, CURRENT_DATE()) AND start_time AND query_parameterized_hash IS NOT NULLGROUP BY query_parameterized_hashORDER BY total_credits DESCLIMIT 5;Use example_query_id to look up the actual SQL in QUERY_HISTORY. You'll almost always find a bad join pattern running inside a scheduled pipeline.Category 5: Cortex AI cost visibilityThe most under-monitored cost surface in Snowflake right now."Show Cortex AI costs by service for the last 30 days""Which Cortex services drove the most inference spend this week?""Which Cortex Agent instances are consuming the most credits?""What's our fine-tuning spend this quarter?""Show me Cortex Analyst usage by user""How much did Cortex Search cost this month?""What is our Cortex Code usage?""Show Cortex REST API token consumption by model""How much are we spending on Snowflake Intelligence?""What's our provisioned throughput utilization?""Show top 10 most expensive Cortex AI services this month"What the skill does: Routes to the correct service-specific view based on the keyword in your prompt. Each Cortex service has its own ACCOUNT_USAGE view with its own schema.Critical constraint: Cortex AI queries enforce a maximum 1-month time window to avoid query timeouts. If you ask for “this quarter” or “last 90 days,” Cortex Code will ask you to narrow the range. Plan prompts accordingly.| Prompt Keyword | Routed To View || ------------------------- | ------------------------------------------- || Agent | CORTEX_AGENT_USAGE_HISTORY || Analyst | CORTEX_ANALYST_USAGE_HISTORY || Search | CORTEX_SEARCH_SERVING_USAGE_HISTORY || Code (Snowsight) | CORTEX_CODE_SNOWSIGHT_USAGE_HISTORY || Code (CLI) | CORTEX_CODE_CLI_USAGE_HISTORY || REST API | CORTEX_REST_API_USAGE_HISTORY || Fine-Tuning | CORTEX_FINE_TUNING_USAGE_HISTORY || Provisioned Throughput | CORTEX_PROVISIONED_THROUGHPUT_USAGE_HISTORY || AI Function / AI_CLASSIFY | CORTEX_AISQL_USAGE_HISTORY || Intelligence | SNOWFLAKE_INTELLIGENCE_USAGE_HISTORY |┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Which Cortex Agent instances are consuming the most ││ credits this month? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ ││ agent_name | requests | tokens | credits ││ SUPPORT_TRIAGE_AGENT | 14,821 | 42.1M | 884.20 ││ CONTRACT_REVIEW_AGENT | 2,102 | 18.8M | 392.40 ││ CLAIMS_CLASSIFIER_AGENT| 8,301 | 9.2M | 193.10 ││ ││ SUPPORT_TRIAGE_AGENT is your largest consumer. ││ 42M tokens in one month suggests either high volume or ││ long context windows. Want me to show daily token trend ││ to check if there's a runaway recursion pattern? │└─────────────────────────────────────────────────────────────┘-- Skill-generated SQL for Cortex Agent cost breakdown by agentSELECT AGENT_DATABASE_NAME, AGENT_SCHEMA_NAME, AGENT_NAME, ROUND(SUM(TOKEN_CREDITS), 4) AS total_credits, SUM(TOKENS) AS total_tokens, COUNT(DISTINCT REQUEST_ID) AS request_count, COUNT(DISTINCT COALESCE(PARENT_REQUEST_ID, REQUEST_ID)) AS conversation_count, COUNT(DISTINCT USER_NAME) AS unique_usersFROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AGENT_USAGE_HISTORYWHERE START_TIME >= DATEADD('day', -30, CURRENT_DATE()) AND START_TIME GROUP BY AGENT_DATABASE_NAME, AGENT_SCHEMA_NAME, AGENT_NAMEORDER BY total_credits DESC;Production note: Agent chains without proper termination conditions are the most common runaway cost failure mode. If an agent’s daily token count grows exponentially over several days, that’s recursion — not volume. Create a dedicated custom budget for AI workloads with a 20% buffer and configure week-over-week anomaly alerting on it.Category 6: Cost anomaly detectionUse these for proactive spike detection — not just post-mortem investigation."Which workloads had unusual cost spikes in the last 24 hours?""Detect unusual serverless compute spikes in the last 24 hours""Are there any cost anomalies in the last 90 days?""For each cost anomaly over the past 4 months, what resources contributed most to the excessive spending?""What caused the cost spike on [date]?""Which warehouses used the most credits on that anomaly day?""When did the spike happen during the day?""Which queries ran on that warehouse during the spike?""Detect abnormal Snowpark Container Services spending"What the skill does: The primary anomaly investigation path uses the SNOWFLAKE.LOCAL.ANOMALY_INSIGHTS class — a set of procedures that apply statistical baselines (not just threshold checks) to identify significant deviations:| Function | Purpose || -------------------------------------- | ------------------------------------------------------------------------------------- || GET_ACCOUNT_ANOMALIES_IN_CREDITS | Detect account-level anomalies in Snowflake credit consumption || GET_DAILY_CONSUMPTION_ANOMALY_DATA | Identify organization-wide or account-specific spending anomalies in currency terms || GET_TOP_WAREHOUSES_ON_DATE | Analyze which warehouses contributed most to a cost anomaly on a specific day || GET_HOURLY_CONSUMPTION_BY_SERVICE_TYPE | Break down hourly consumption by service type to investigate anomaly patterns || GET_TOP_QUERIES_FROM_WAREHOUSE | Identify queries responsible for warehouse cost spikes and unusual consumption events |Fallback: If you lack access to the ANOMALY_INSIGHTS procedures, the skill queries the ANOMALIES_DAILY view directly (account-level, credits only, up to 8-hour latency), then joins with METERING_HISTORY to rank contributing resources.The investigative workflow chains naturally:┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Are there any cost anomalies in the last 90 days? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ 3 anomaly days detected. Largest: May 14th (+$2,841 vs ││ baseline). Want to see what caused it? │└─────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ What caused the cost spike on May 14? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ Top contributor: TRANSFORM_WH (+680 credits above normal). ││ That's 162% above its 30-day baseline. ││ Want me to pull which queries ran on TRANSFORM_WH that day? │└─────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Which queries ran on that warehouse during the spike? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ Top query: MERGE statement, parameterized hash a1b2c3d4. ││ Ran 412 times between 02:00–06:00 UTC. This is a retry ││ loop — the job failed and kept retrying. │└─────────────────────────────────────────────────────────────┘That three-turn conversation — anomaly → contributor → query — replaces a two-hour manual investigation.-- Fallback SQL for anomaly contributor analysis (ANOMALIES_DAILY view path)WITH anomaly_dates AS ( SELECT DISTINCT date AS anomaly_date, actual_value, forecasted_value, (actual_value - forecasted_value) AS anomaly_impact FROM SNOWFLAKE.ACCOUNT_USAGE.ANOMALIES_DAILY WHERE is_anomaly = TRUE AND date >= DATEADD('month', -4, CURRENT_DATE())),anomaly_day_spending AS ( SELECT DATE(m.start_time) AS usage_date, m.service_type, m.name AS resource_name, SUM(m.credits_used) AS daily_credits FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY m JOIN anomaly_dates ad ON DATE(m.start_time) = ad.anomaly_date WHERE m.start_time >= DATEADD('month', -4, CURRENT_DATE()) GROUP BY DATE(m.start_time), m.service_type, m.name),normal_day_baseline AS ( SELECT service_type, name AS resource_name, AVG(daily_credits) AS avg_normal_credits FROM ( SELECT DATE(m.start_time) AS usage_date, m.service_type, m.name, SUM(m.credits_used) AS daily_credits FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY m WHERE m.start_time >= DATEADD('month', -4, CURRENT_DATE()) AND DATE(m.start_time) NOT IN (SELECT anomaly_date FROM anomaly_dates) GROUP BY DATE(m.start_time), m.service_type, m.name ) normal_days GROUP BY service_type, name),anomaly_contributors AS ( SELECT ads.usage_date AS anomaly_date, ads.service_type, ads.resource_name, ROUND(ads.daily_credits, 2) AS anomaly_day_credits, ROUND(COALESCE(nb.avg_normal_credits, 0), 2) AS avg_normal_day_credits, ROUND(ads.daily_credits - COALESCE(nb.avg_normal_credits, 0), 2) AS credits_above_normal, CASE WHEN nb.avg_normal_credits > 0 THEN ROUND(((ads.daily_credits - nb.avg_normal_credits) / nb.avg_normal_credits) * 100, 2) ELSE NULL END AS percent_above_normal, CASE WHEN nb.avg_normal_credits > 0 AND ((ads.daily_credits - nb.avg_normal_credits) / nb.avg_normal_credits) >= 2.0 THEN 'Major Contributor' WHEN nb.avg_normal_credits > 0 AND ((ads.daily_credits - nb.avg_normal_credits) / nb.avg_normal_credits) >= 1.0 THEN 'Significant Contributor' WHEN nb.avg_normal_credits > 0 AND ((ads.daily_credits - nb.avg_normal_credits) / nb.avg_normal_credits) >= 0.5 THEN 'Moderate Contributor' ELSE 'Minor Contributor' END AS contribution_level, ROW_NUMBER() OVER ( PARTITION BY ads.usage_date ORDER BY (ads.daily_credits - COALESCE(nb.avg_normal_credits, 0)) DESC ) AS contributor_rank FROM anomaly_day_spending ads LEFT JOIN normal_day_baseline nb ON ads.service_type = nb.service_type AND ads.resource_name = nb.resource_name WHERE ads.daily_credits > 0)SELECT anomaly_date, contributor_rank, contribution_level, service_type, resource_name, anomaly_day_credits, avg_normal_day_credits, credits_above_normal, percent_above_normalFROM anomaly_contributorsWHERE credits_above_normal > 0 AND contributor_rank ORDER BY anomaly_date DESC, contributor_rank ASC;Category 7: Budget governanceUse these to move from “we went over budget” to “we won’t go over budget.”"Which of my budgets are on track to exceed their limits before end of month?""Are any of my Budgets over their spending limit?""Which Budgets are at risk of going over their spending limit?""What Budgets were created in the past 3 months?""Create a budget for my AI workloads with a 2000 credit limit""Set up a custom budget for the data engineering team""Show me budget utilization trends""Alert me if any budget exceeds 80% of its limit"What the skill does: Queries BUDGET_DETAILS and applies a month-elapsed ratio to project end-of-month spend. The projected_month_end_spend and projected_over_by columns tell you how far over you'll land before the billing cycle closes. For "create a budget" prompts, it generates correct SNOWFLAKE.CORE.BUDGET class syntax and offers to execute it.┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Which budgets are at risk of going over their limit? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ ││ budget_name | limit | spent | pct_elapsed | proj_eom ││ AI_WORKLOADS_BDG | 2,000 | 1,340 | 55.6% | 2,412 ││ TRANSFORM_BDG | 800 | 560 | 55.6% | 1,008 ││ ││ Both budgets will breach their limits at current pace. ││ AI_WORKLOADS_BDG is projected 20.6% over. ││ ││ Want me to drill into which Cortex AI services are driving ││ the AI_WORKLOADS_BDG overage so you can act now? │└─────────────────────────────────────────────────────────────┘-- Skill-generated SQL for budget risk scoringWITH m AS ( SELECT DATE_TRUNC('month', CURRENT_TIMESTAMP()) AS month_start, DATEADD('month', 1, DATE_TRUNC('month', CURRENT_TIMESTAMP())) AS next_month_start),r AS ( SELECT DATEDIFF('second', m.month_start, CURRENT_TIMESTAMP())::FLOAT / NULLIF(DATEDIFF('second', m.month_start, m.next_month_start), 0) AS ratio FROM m)SELECT bd.budget_name, bd.database_name, bd.schema_name, bd.credit_limit, ROUND(bd.current_month_spending, 2) AS current_month_spending, ROUND(r.ratio * bd.credit_limit, 2) AS expected_spend_to_date, ROUND(CASE WHEN r.ratio > 0 THEN bd.current_month_spending / r.ratio ELSE NULL END, 2) AS projected_month_end_spend, ROUND((CASE WHEN r.ratio > 0 THEN bd.current_month_spending / r.ratio ELSE NULL END) - bd.credit_limit, 2) AS projected_over_byFROM SNOWFLAKE.ACCOUNT_USAGE.BUDGET_DETAILS bdCROSS JOIN rWHERE r.ratio > 0 AND (bd.current_month_spending / r.ratio) > bd.credit_limitORDER BY projected_over_by DESC;Budget syntax gotcha that trips up every team:Snowflake Budgets are class instances — not standard objects. If you ever run budget queries manually outside Cortex Code:✅ SHOW SNOWFLAKE.CORE.BUDGET INSTANCES IN ACCOUNT❌ SHOW BUDGETS — this will failThe account-level root budget (SNOWFLAKE.LOCAL.ACCOUNT_ROOT_BUDGET) monitors all account spending automatically but does not support ADD_RESOURCE, REMOVE_RESOURCE, or tag management methods. Use custom budgets for team-level tracking.Category 8: Tag-based chargebacksUse these to move from “Snowflake bill” to “team-level P&L.”"What did each team spend in total?""What is the total cost breakdown by team across all warehouses?""Which teams or cost centers have the highest warehouse costs?""Show me a quick overview of all tag combinations and their spending""Which resources are consuming credits but have no tags assigned?""Which teams consumed the most across warehouse, cortex, and storage costs?""Show department-level chargeback report for last month"What the skill does: Joins WAREHOUSE_METERING_HISTORY to TAG_REFERENCES to attribute costs by team. The "no tags assigned" prompt runs a LEFT JOIN governance gap query that surfaces untagged resources consuming credits — then offers to generate the DDL to fix them.┌─────────────────────────────────────────────────────────────┐│ 🧑 You ││ Which resources are consuming credits but have no tags? │├─────────────────────────────────────────────────────────────┤│ 🤖 Cortex Code ││ ││ resource_name | service_category | credits ││ ANALYTICS_WH | WAREHOUSE_METERING | 1,841.20 ││ UNNAMED_CORTEX_AI | CORTEX_AI | 392.10 ││ EXPERIMENTAL_POOL | CONTAINER_SVCS | 204.80 ││ ││ 2,438 credits (18% of total spend) can't be attributed. ││ Want me to generate the DDL to tag these resources? │└─────────────────────────────────────────────────────────────┘That last offer — generating tagging DDL automatically — is where cost reporting becomes governance action.Category 9: Storage costsUse these to surface the silent, slow-growing bill."Which databases used the most storage on average?""Which 5 databases are contributing the most to storage costs?""How is storage usage trending across databases over time?""How much have I spent so far this calendar year on database storage?""Which teams are taking up the most storage over the past month?""Which tables are driving up our clustering expenses?""Compare month-over-month storage costs""What's our stage storage usage?"What the skill does: Routes to DATABASE_STORAGE_USAGE_HISTORY for database-level storage, AUTOMATIC_CLUSTERING_HISTORY for clustering costs, and STAGE_STORAGE_USAGE_HISTORY for stage storage. YTD storage spend filters METERING_HISTORY by service_type = 'STORAGE' from DATE_TRUNC('YEAR', CURRENT_DATE()).For clustering costs specifically: if a table appears in the top results of AUTOMATIC_CLUSTERING_HISTORY but is under 500GB, question whether it's justified. Below 1TB with no proven query patterns on the clustered columns, auto-clustering is almost always waste.Category 10: Serverless computeUse these for the cost surface that fails silently."How many credits did serverless tasks consume last week?""Which databases have the highest serverless task credit usage?""What serverless task activity happened in the last 12 hours?""Set up week-over-week monitoring for serverless task costs""Alert me if serverless costs increase more than 20% week-over-week""Detect unusual serverless compute spikes in the last 24 hours"What the skill does: Queries SERVERLESS_TASK_HISTORY. For monitoring and alert setup prompts, it generates both the monitoring query and the ALERT object DDL — wrapping the week-over-week comparison in a trigger condition at your specified threshold. The skill generates this DDL for your review; it never auto-executes governance objects.A task with high retry count and no error handling will consume exponentially more credits than expected. Always pair any serverless spike investigation with a check on task failure rates.-- Skill-generated SQL for serverless task credits last weekSELECT task_name, database_name, schema_name, ROUND(SUM(credits_used), 2) AS total_creditsFROM SNOWFLAKE.ACCOUNT_USAGE.SERVERLESS_TASK_HISTORYWHERE start_time >= DATEADD('D', -7, CURRENT_DATE) AND start_time GROUP BY task_name, database_name, schema_nameORDER BY total_credits DESC;Category 11: Snowpark Container Services (SPCS)The compute cost that grows while nobody’s looking."Which compute pools used the most credits over the past week?""How many total credits were used by Snowpark container services last week?""Which applications used the most Snowpark container credits last week?""Which compute pools are consuming the least number of credits (under utilized)?""Detect abnormal Snowpark Container Services spending"What the skill does: Routes to SNOWPARK_CONTAINER_SERVICES_HISTORY. The underutilization prompt is sorted intentionally by total_credits_used ASC — the lowest-spend pools with the highest days_active are the idle waste candidates.-- Skill-generated SQL for idle SPCS pool detectionSELECT compute_pool_name, ROUND(SUM(credits_used), 2) AS total_credits_used, COUNT(*) AS usage_hours, ROUND(AVG(credits_used), 4) AS avg_credits_per_hour, DATEDIFF('day', MIN(start_time), MAX(start_time)) + 1 AS days_active, MAX(application_name) AS associated_applicationFROM SNOWFLAKE.ACCOUNT_USAGE.SNOWPARK_CONTAINER_SERVICES_HISTORYWHERE start_time >= DATEADD('month', -1, CURRENT_DATE())GROUP BY compute_pool_nameORDER BY total_credits_used ASC -- intentional: low credits + high days_active = idle wasteLIMIT 5;A compute pool with 30 days_active and near-zero credits is almost always a pool someone provisioned for an experiment and never suspended. These are the most reliable quick wins in SPCS cost reduction.Category 12: Data transfer, pipes, and replicationThe line items nobody watches until the invoice arrives."How much data was transferred by region, cloud, and transfer type?""What are the top data transfer costs by region and cloud provider?""Show cross-region transfer costs for the last 30 days""Which pipes consumed the most credits last week?""Show Snowpipe credit usage by pipe""What's our streaming ingest cost?""How much are we spending on database replication?""Show replication group credit usage"What the skill does: Routes to DATA_TRANSFER_HISTORY (grouped by cloud/region pair), PIPE_USAGE_HISTORY, SNOWPIPE_STREAMING_CLIENT_HISTORY, and DATABASE_REPLICATION_USAGE_HISTORY. Large cross-cloud transfers (AWS → GCP) are almost always architectural mistakes — data sharing or replication configured against the wrong region. This prompt surfaces them.Category 13: Optimization insightsUse these to move from reporting to action."What can I save?""Recommend opportunities to reduce warehouse spend""Show me idle warehouses""Which tables are never queried?""Show unused materialized views""Which warehouses have query gaps longer than 24 hours?""Are there tables that were only written to but never read?""Show auto-clustering waste""Which warehouses have the same min and max cluster count?"What the skill does: Invokes the SNOWFLAKE.LOCAL.COST_INSIGHTS class procedures to surface quantified optimization recommendations — each with a credit impact estimate. This requires the APP_USAGE_VIEWER or APP_USAGE_ADMIN application role (or ACCOUNTADMIN). For structural queries like "same min and max cluster count," it queries the WAREHOUSES catalog object directly.The “never queried tables” and “only written to, never read” prompts are governance gold for storage cost reduction — especially in accounts with years of accumulated data.Category 14: Executive summaries and continuous governanceUse these for recurring reporting and automated governance."Give me a weekly cost summary""What are the top 5 cost drivers this month?""Show me a cost breakdown by service, warehouse, and team""Which workloads are growing fastest in cost?""Summarize our AI spend vs compute spend""Alert me if serverless costs increase more than 20% week-over-week""Set up a weekly spend baseline check""Create a custom budget for AI workloads with a 20% buffer""Show me which budgets will breach their limit this month""What untagged resources are consuming credits?""Which new warehouses appeared this month with no tags?"What the skill does: For summary prompts, it assembles a multi-section report across METERING_HISTORY, WAREHOUSE_METERING_HISTORY, TAG_REFERENCES, and Cortex AI views. For governance automation prompts ("alert me if…", "set up monitoring for…"), it generates ALERT or TASK DDL ready for your review and execution — it never auto-executes governance objects without confirmation.“New warehouses this month with no tags” is the prompt to run at the start of every sprint. Catching ungoverned resources before they accumulate spend is fundamentally easier than retroactively attributing them.The investigative workflow in practiceThe real power isn’t any single prompt. It’s chaining them — letting each answer drive the next question:"Are there any cost anomalies in the last 90 days?" → "What caused the spike on May 14?" → "Which warehouses drove it?" → "Which queries ran on that warehouse during the spike?" → "Which user submitted those queries?" → "Which team owns that user? Generate tagging DDL."Six natural language turns. Zero SQL written manually. That’s the workflow.Key operational caveats| Caveat | What It Means in Practice || ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || ACCOUNT_USAGE Latency | ACCOUNT_USAGE views have approximately 45-minute latency. For live incident investigations, use INFORMATION_SCHEMA equivalents where available (with shorter retention but near real-time visibility). || Credits ≠ Dollars | Credit consumption does not directly represent actual spend. Apply your organization's negotiated Snowflake rate before presenting costs to finance teams. || Budget Class Syntax | Use `SHOW SNOWFLAKE.CORE.BUDGET INSTANCES IN ACCOUNT`. The legacy `SHOW BUDGETS` command will fail for budget class objects. || TAG_REFERENCES Latency | Allow up to 2 hours after applying a tag before chargeback and cost attribution queries return complete results. || Anomaly Baseline Window | New accounts should accumulate 2–4 weeks of usage history before `ANOMALIES_DAILY` signals become statistically reliable. || SPCS Idle Detection | To identify underutilized Snowpark Container Services workloads, sort by ascending credits consumed. Low credits combined with high `days_active` often indicates idle resource waste. || Root Account Budget Limitations | `SNOWFLAKE.LOCAL.ACCOUNT_ROOT_BUDGET` does not support `ADD_RESOURCE` operations or tag-based allocations. Use custom budgets for advanced governance scenarios. || Cortex AI One-Month Window | Cortex AI cost analysis queries enforce a maximum one-month date range to avoid long-running queries and timeouts. || ANOMALY_INSIGHTS Access | Requires either `APP_USAGE_VIEWER` or `APP_USAGE_ADMIN` application role privileges. || COST_INSIGHTS Access | Requires `APP_USAGE_VIEWER`, `APP_USAGE_ADMIN`, or `ACCOUNTADMIN` privileges. || Governance Automation | The skill generates recommended `ALERT` and `TASK` DDL statements for review but never automatically deploys governance objects. |Open Snowsight and start a Cortex Code chatAsk “Where is my money going?” — establish your spend baseline before anything elseAsk “Are there any cost anomalies in the last 90 days?” — there’s almost always a spike you haven’t investigatedAsk “Which resources are consuming credits but have no tags?” — this is your chargeback gapAsk “Which Cortex Agent instances are consuming the most credits?” if you’re running agents — runaway recursion is the #1 surprise AI costAsk “Which budgets are at risk of going over their limit this month?” before your next billing cycleCost governance isn’t a dashboard you build once. It’s a conversation you have continuously. Start it now.Further readingSnowflake ACCOUNT_USAGE referenceSnowflake Budgets documentationCortex AI overviewCortex Code documentationResource MonitorsShare this with whoever on your team owns the FinOps conversation — or whoever gets the Monday morning “why did our credits spike?” message.Disclaimer: The views expressed in this article are my own and do not represent my employer. All prompts, SQL patterns, and workflow descriptions are based on publicly available Snowflake documentation and hands-on exploration of the cost-intelligence skill inside Cortex Code. Some SQL patterns are representative of what the skill generates and have been formatted for readability — they may differ slightly from verbatim output. Feature availability may vary by Snowflake edition, region, and release. Always verify against the official Snowflake docs before deploying to production.If this playbook saved you time, a clap (or 50 👏) helps it reach more Snowflake practitioners. Share it with your data team — and follow Snowflake Chronicles on Medium @snowflakechronicles and LinkedIn @satishkumar-snowflake for more practitioner-first content on Snowflake, Cortex AI, and cloud data engineering.#Snowflake #CortexCode #FinOps #DataEngineering #SQL #CostOptimization #CortexAI #CloudCostManagement #DataPlatformStop Writing Cost Queries. Just Ask Cortex Code. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.