<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eduardo Peña on Medium]]></title>
        <description><![CDATA[Stories by Eduardo Peña on Medium]]></description>
        <link>https://medium.com/@epenav81?source=rss-e1042ab6a237------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dNIliY7ISmbqzT7mPG55bA.jpeg</url>
            <title>Stories by Eduardo Peña on Medium</title>
            <link>https://medium.com/@epenav81?source=rss-e1042ab6a237------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:49:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@epenav81/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Snowflake FinOps in Practice: From Weekly Monitoring to Cost Accountability]]></title>
            <link>https://medium.com/@epenav81/snowflake-finops-in-practice-from-weekly-monitoring-to-cost-accountability-35666003b1d7?source=rss-e1042ab6a237------2</link>
            <guid isPermaLink="false">https://medium.com/p/35666003b1d7</guid>
            <category><![CDATA[budget]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Eduardo Peña]]></dc:creator>
            <pubDate>Mon, 25 May 2026 21:47:14 GMT</pubDate>
            <atom:updated>2026-05-25T22:14:07.357Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You can already see how much you are spending. The harder part is knowing why, who, and what to do about it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijpIyMzCWzyo-Q-jX8g4nA.png" /></figure><blockquote><strong><em>Disclaimer:</em></strong><em> I work at Snowflake. This article is not related to my job — it is something I think about in my own accounts, with my own projects, on my own time. The queries here work for me. Some things will need adjustments for your environment. Don’t use this as official documentation. For real billing data, always check </em><a href="https://docs.snowflake.com/en/user-guide/cost-understanding-overall"><em>Snowflake’s cost management interfaces</em></a><em> and your contract.</em></blockquote><h3>What this is about</h3><p>If you manage a Snowflake account shared by multiple teams, you already know the situation: costs accumulate without a clear owner. One team creates a warehouse, configures it generously, and moves on. Another enables a feature that runs in the background and nobody looks at the bill for three months. FinOps — Financial Operations — is the set of practices that makes this detectable before the invoice surprises everyone.</p><p>If you read my previous article about automated weekly reports, you have part of this in place already — a Monday email with credit totals, warehouse rankings, week-over-week trends. That is useful. But there is a difference between seeing that ANALYTICS_WH spent 40% more this week and knowing who owns it, whether they have a budget, or whether anyone knew the increase was coming. Most accounts have the first. The second is what this article is about.</p><h3>What you are actually paying for</h3><p>This matters for governance because the controls are different for each billing category, and as a Snowflake admin you are responsible for understanding where each dollar is coming from.</p><p><strong>Warehouse compute</strong> is the most visible cost and also the one most people focus on. What is easy to miss: Snowflake bills by running time, not by query volume. A warehouse sitting idle with nothing queued is still accumulating credits. The clock starts when it wakes up and stops when it suspends. This is why AUTO_SUSPEND matters more than most people realize when they first configure things.</p><p><strong>Serverless compute</strong> is a separate category — Snowpipe, Automatic Clustering, Search Optimization, Materialized View refreshes, Serverless Tasks. None of these appear in warehouse metrics. They also tend to be harder to attribute because there is no warehouse to tie them to.</p><p><strong>Storage</strong> is billed per TB per month and has three components: active data, time travel retention copies, and a 7-day failsafe window Snowflake maintains automatically. Storage does not show up in compute reports and is easy to overlook until it becomes a meaningful line item.</p><p><strong>AI and Cortex</strong> is its own billing bucket. Function calls like AI_COMPLETE, <a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-agents/overview">Cortex Agents</a>, <a href="https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code">Cortex Code (CoCo)</a> — each with separate billing, none of it in warehouse metrics.</p><p><strong>Cloud services</strong> — query compilation, metadata, authentication. Usually small. Snowflake covers up to 10% of compute for free. Cloud services are only billed when it exceeds the 10% of your daily Warehouse compute.</p><p>The controls are different for each category: resource monitors apply to warehouses only, budgets are broader. Which tool you need depends on what you are trying to control.</p><h3>Resource monitors and budgets</h3><p>These two get confused often — the names do not explain the difference by themselves.</p><p><a href="https://docs.snowflake.com/en/user-guide/resource-monitors"><strong>Resource Monitors</strong></a> are hard stops at the virtual warehouse level. You set a credit limit and a time window, attach the monitor to one or more warehouses, and when the limit hits, the warehouse suspends. New queries cannot start until the window resets or someone intervenes.</p><pre>-- Create a resource monitor for the analytics team&#39;s warehouse.<br>-- CREDIT_QUOTA = 200 means the warehouse can consume at most 200 credits<br>-- within the WEEKLY window before the SUSPEND action fires.<br>CREATE RESOURCE MONITOR analytics_team_monitor<br>  WITH CREDIT_QUOTA = 200             -- max credits allowed per week<br>  FREQUENCY = WEEKLY<br>  START_TIMESTAMP = IMMEDIATELY<br>  TRIGGERS<br>    ON 75 PERCENT DO NOTIFY           -- sends an email alert at 75% usage<br>    ON 90 PERCENT DO NOTIFY           -- another email alert at 90%<br>    ON 100 PERCENT DO SUSPEND;        -- blocks new queries when limit is reached<br><br>-- Attach the monitor to the warehouse.<br>-- A warehouse can only have one resource monitor at a time.<br>ALTER WAREHOUSE ANALYTICS_WH<br>  SET RESOURCE_MONITOR = analytics_team_monitor;</pre><p>Two things worth knowing: SUSPEND stops new queries from starting but does not kill jobs that are already running. If someone submits a heavy query at 99%, it will finish. And resource monitors only cover warehouses — serverless services, Snowpipe, AI costs are all invisible to them.</p><p><a href="https://docs.snowflake.com/en/user-guide/budgets"><strong>Budgets</strong></a> work differently. You assign a budget to a group of objects — a set of warehouses, a schema, a full account — and it tracks total spend across all of them, including serverless activity. By default a budget does not stop anything; it alerts when you approach the limit.</p><pre>-- Create a budget for a specific team.<br>-- Budgets track total spending across ALL assigned objects —<br>-- including warehouses, schemas, and any serverless activity in those objects.<br>CREATE SNOWFLAKE.CORE.BUDGET team_data_budget<br>  WITH SPENDING_LIMIT = 500;          -- 500 credits per month<br><br>-- Add the team&#39;s warehouse to this budget.<br>CALL team_data_budget!ADD_RESOURCE(<br>  SYSTEM$REFERENCE(&#39;WAREHOUSE&#39;, &#39;ANALYTICS_WH&#39;, &#39;SESSION&#39;, &#39;APPLYBUDGET&#39;)<br>);<br><br>-- Add a schema they own. This covers all objects in it,<br>-- including serverless costs like Automatic Clustering on their tables.<br>CALL team_data_budget!ADD_RESOURCE(<br>  SYSTEM$REFERENCE(&#39;SCHEMA&#39;, &#39;PROD.ANALYTICS&#39;, &#39;SESSION&#39;, &#39;APPLYBUDGET&#39;)<br>);</pre><p>The practical split: resource monitors for hard limits on specific warehouses where you need a guarantee, budgets to track what a team is actually spending across everything including serverless. They address different parts of the problem and you typically need both.</p><h3>Tags and cost attribution</h3><p>Without tags, attribution is mostly guesswork. You look at which warehouses spent the most and try to remember which team owns which one. That works until someone shares a warehouse, or a new team appears, or someone creates a warehouse with a name that tells you nothing about who is responsible for it.</p><p><a href="https://docs.snowflake.com/en/user-guide/object-tagging">Tagging</a> is the mechanism that makes systematic attribution possible. You define tag objects with allowed values, apply them to warehouses, databases, schemas, and then join that metadata to usage data.</p><pre>-- Define tag objects first.<br>-- ALLOWED_VALUES restricts what values can be applied, which helps enforce consistency.<br>CREATE TAG cost_center ALLOWED_VALUES &#39;analytics&#39;, &#39;data_engineering&#39;, &#39;ml_platform&#39;, &#39;finance&#39;;<br>CREATE TAG team_owner;                -- free text, for email or team name<br>CREATE TAG environment ALLOWED_VALUES &#39;prod&#39;, &#39;dev&#39;, &#39;staging&#39;;<br><br>-- Apply tags to warehouses.<br>-- These appear in TAG_REFERENCES and allow joining tags to usage data.<br>ALTER WAREHOUSE ANALYTICS_WH SET TAG cost_center = &#39;analytics&#39;, team_owner = &#39;data-team@company.com&#39;;<br>ALTER WAREHOUSE ML_WH         SET TAG cost_center = &#39;ml_platform&#39;, team_owner = &#39;ml-team@company.com&#39;;<br><br>-- Tags can also be applied at the database or schema level<br>-- to cover all objects within them.<br>ALTER DATABASE ANALYTICS_DB SET TAG cost_center = &#39;analytics&#39;;</pre><p>Once tags are applied, <a href="https://docs.snowflake.com/en/sql-reference/account-usage/tag_references">ACCOUNT_USAGE.TAG_REFERENCES</a> is what you join against usage data. Credits by cost center for the current month:</p><pre>-- Credits consumed by each cost center this month,<br>-- broken down into compute and cloud services.<br>-- COALESCE ensures untagged warehouses appear as &#39;Untagged&#39; instead of NULL.<br>SELECT<br>  COALESCE(t.TAG_VALUE, &#39;Untagged&#39;)             AS cost_center,<br>  ROUND(SUM(w.CREDITS_USED), 2)                 AS total_credits,<br>  ROUND(SUM(w.CREDITS_USED_COMPUTE), 2)         AS compute_credits,<br>  ROUND(SUM(w.CREDITS_USED_CLOUD_SERVICES), 2)  AS cloud_services_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY w<br>LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.TAG_REFERENCES t<br>  ON  t.OBJECT_NAME   = w.WAREHOUSE_NAME<br>  AND t.DOMAIN = &#39;WAREHOUSE&#39;<br>  AND t.TAG_NAME      = &#39;COST_CENTER&#39;<br>WHERE w.START_TIME &gt;= DATE_TRUNC(&#39;month&#39;, CURRENT_DATE)<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><p>Use a LEFT JOIN here, not an inner join. An inner join silently drops all untagged spend from the results, and your totals will be wrong. In most accounts the first time you run this query the “Untagged” bucket is the largest one — which is actually useful information. It tells you where to focus tagging efforts first.</p><pre>-- Warehouses with spend this month that have no cost_center tag.<br>-- The most Snowflake accounts that I see have this as their largest bucket<br>-- when they first start doing attribution work.<br>SELECT<br>  w.WAREHOUSE_NAME,<br>  ROUND(SUM(w.CREDITS_USED), 2) AS credits_this_month<br>FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY w<br>LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.TAG_REFERENCES t<br>  ON  t.OBJECT_NAME   = w.WAREHOUSE_NAME<br>  AND t.DOMAIN = &#39;WAREHOUSE&#39;<br>  AND t.TAG_NAME      = &#39;COST_CENTER&#39;<br>WHERE w.START_TIME &gt;= DATE_TRUNC(&#39;month&#39;, CURRENT_DATE)<br>  AND t.TAG_VALUE IS NULL           -- no tag applied to this warehouse<br>GROUP BY 1<br>HAVING credits_this_month &gt; 0<br>ORDER BY 2 DESC;</pre><h3>Cost by warehouse, user, and query</h3><p>Totals are fine for a weekly report. For governance you need the detail.</p><p><strong>By warehouse</strong> — <a href="https://docs.snowflake.com/en/sql-reference/account-usage/warehouse_metering_history">WAREHOUSE_METERING_HISTORY</a> is the starting point:</p><pre>-- Total credits per warehouse in the last 30 days.<br>-- avg_credits_per_day helps identify warehouses that run every day<br>-- vs ones that only run occasionally.<br>SELECT<br>  WAREHOUSE_NAME,<br>  ROUND(SUM(CREDITS_USED), 4)                            AS total_credits,<br>  COUNT(DISTINCT DATE(START_TIME))                       AS active_days,<br>  ROUND(SUM(CREDITS_USED)<br>    / NULLIF(COUNT(DISTINCT DATE(START_TIME)), 0), 4)    AS avg_credits_per_day<br>FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY<br>WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><p><strong>By user</strong> — <a href="https://docs.snowflake.com/en/sql-reference/account-usage/query_attribution_history">QUERY_ATTRIBUTION_HISTORY</a> became generally available in August 2024. It attributes compute cost at the individual query level using a weighted average across concurrent execution — when multiple queries run at the same time on a warehouse, cost is split proportionally among them. Not a perfect measure, but much better than what you could calculate manually from query history alone.</p><p>A few things to know before relying on it: very short queries (roughly 100ms or under) are excluded. The view has up to 8 hours of latency. And it does not include a ROLE_NAME column — if you need role-level attribution you have to join to QUERY_HISTORY on QUERY_ID.</p><pre>-- Top users by attributed compute cost in the last 30 days.<br>-- CREDITS_ATTRIBUTED_COMPUTE is a weighted average based on resource consumption —<br>-- when multiple queries run concurrently, cost is split proportionally.<br>-- Note: short-running queries (&lt;= ~100ms) are excluded from this view.<br>-- Latency can be up to 8 hours, so recent activity may not appear immediately.<br>-- Note: QUERY_ATTRIBUTION_HISTORY does not include a ROLE_NAME column.<br>-- To add role-level breakdown, join to QUERY_HISTORY on QUERY_ID.<br>SELECT<br>  USER_NAME,<br>  WAREHOUSE_NAME,<br>  ROUND(SUM(CREDITS_ATTRIBUTED_COMPUTE), 4)     AS attributed_credits,<br>  COUNT(*)                                      AS query_count<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_ATTRIBUTION_HISTORY<br>WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>GROUP BY 1, 2<br>ORDER BY 3 DESC<br>LIMIT 50;</pre><p>If you need an estimate before the attribution data catches up, you can calculate it from <a href="https://docs.snowflake.com/en/sql-reference/account-usage/query_history">QUERY_HISTORY</a> using warehouse size and elapsed time. This depends of the warehouse size being populated in the query history, which may not always be the case for very short queries. Keep in mind this is an approximation — concurrent queries share warehouse time, and idle time, auto-scaling, and cloud services overhead are not accounted for at the per-query level.</p><pre>-- Credit estimation from QUERY_HISTORY.<br>-- This is an approximation only — concurrent queries share warehouse time,<br>-- so per-query cost cannot be measured exactly from this view alone.<br>-- Use QUERY_ATTRIBUTION_HISTORY whenever possible.<br>WITH wh_rates AS (<br>  -- Standard credit rates by warehouse size (adjust if your contract differs).<br>  SELECT $1 AS warehouse_size, $2 AS credits_per_hour FROM VALUES<br>    (&#39;X-Small&#39;, 1), (&#39;Small&#39;, 2), (&#39;Medium&#39;, 4), (&#39;Large&#39;, 8),<br>    (&#39;X-Large&#39;, 16), (&#39;2X-Large&#39;, 32), (&#39;3X-Large&#39;, 64), (&#39;4X-Large&#39;, 128)<br>)<br>SELECT<br>  q.USER_NAME,<br>  q.ROLE_NAME,<br>  q.WAREHOUSE_NAME,<br>  q.WAREHOUSE_SIZE,<br>  COUNT(*)                                                  AS query_count,<br>  -- Estimated cost = (elapsed time in hours) * (credits per hour for that warehouse size)<br>  ROUND(SUM(q.TOTAL_ELAPSED_TIME / 1000.0 / 3600.0<br>    * COALESCE(r.credits_per_hour, 1)), 4)                  AS estimated_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY q<br>LEFT JOIN wh_rates r ON r.warehouse_size = q.WAREHOUSE_SIZE<br>WHERE q.START_TIME    &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  AND q.EXECUTION_STATUS = &#39;SUCCESS&#39;<br>  AND q.WAREHOUSE_SIZE   IS NOT NULL<br>GROUP BY 1, 2, 3, 4<br>ORDER BY 6 DESC<br>LIMIT 50;</pre><h3>Serverless costs</h3><p>This is where a lot of accounts have blind spots. Credits from Snowpipe, Automatic Clustering, Search Optimization, Materialized Views, and Serverless Tasks do not appear in warehouse metrics. Each has its own view in ACCOUNT_USAGE, and since those views have different schemas you cannot merge them in a single query — you need to UNION them manually.</p><pre>-- All serverless costs for the last 30 days, by service type.<br>-- Each service has its own view in ACCOUNT_USAGE — they cannot be combined<br>-- into a single view because they have different schemas.<br>-- This UNION lets you see the total across all of them at once.<br>WITH serverless_costs AS (<br><br>  -- Snowpipe: credits for loading data via pipes.<br>  -- Note: uses START_TIME/END_TIME, not USAGE_DATE.<br>  SELECT &#39;Snowpipe&#39;             AS service,<br>         PIPE_NAME              AS object_name,<br>         SUM(CREDITS_USED)      AS credits<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.PIPE_USAGE_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>  UNION ALL<br>  -- Automatic Clustering: re-clusters tables in the background.<br>  -- These credits do NOT appear in WAREHOUSE_METERING_HISTORY.<br>  SELECT &#39;Auto Clustering&#39;,    TABLE_NAME,    SUM(CREDITS_USED)<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.AUTOMATIC_CLUSTERING_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>  UNION ALL<br>  -- Search Optimization: continuous background process per table.<br>  -- Enterprise Edition feature. Charges even when no queries are running.<br>  -- Note: TABLE_NAME in this view is a system-generated label<br>  -- (e.g. &quot;SEARCH OPTIMIZATION ON TABLE_ID: 1234&quot;), not the actual table name.<br>  -- Use SHOW TABLES to map IDs to actual names if needed.<br>  SELECT &#39;Search Optimization&#39;, TABLE_NAME,   SUM(CREDITS_USED)<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.SEARCH_OPTIMIZATION_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>  UNION ALL<br>  -- Materialized Views: serverless refresh, not tied to any warehouse.<br>  -- Enterprise Edition feature.<br>  SELECT &#39;Materialized Views&#39;,  TABLE_NAME,   SUM(CREDITS_USED)<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.MATERIALIZED_VIEW_REFRESH_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>  UNION ALL<br>  -- Serverless Tasks: tasks that run without a warehouse assigned.<br>  SELECT &#39;Serverless Tasks&#39;,    TASK_NAME,     SUM(CREDITS_USED)<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.SERVERLESS_TASK_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>  UNION ALL<br>  -- Database Replication: credits for replicating databases across accounts.<br>  SELECT &#39;Replication&#39;,         DATABASE_NAME, SUM(CREDITS_USED)<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.DATABASE_REPLICATION_USAGE_HISTORY<br>  WHERE START_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>  GROUP BY 2<br>)<br>SELECT<br>  service,<br>  ROUND(SUM(credits), 4) AS total_credits<br>FROM serverless_costs<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><p>Don’t let Search Optimization catch you off guard. It is an Enterprise Edition feature that runs a background indexing process per table — continuously, regardless of whether any queries are hitting that table. Enable it on a project, the project slows down or changes direction, and the credits keep running until someone explicitly turns it off. Worth checking which tables have it active:</p><pre>-- Find tables with Search Optimization enabled.<br>-- SHOW TABLES returns a &#39;search_optimization&#39; column indicating ON/OFF.<br>-- RESULT_SCAN reads the output of the previous SHOW command.<br>SHOW TABLES IN ACCOUNT;<br><br>SELECT &quot;name&quot;          AS table_name,<br>       &quot;database_name&quot;,<br>       &quot;schema_name&quot;,<br>       &quot;search_optimization&quot;<br>FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))<br>WHERE &quot;search_optimization&quot; = &#39;ON&#39;;</pre><h3>Storage costs</h3><p>Storage billing is separate from compute and does not appear in any of the warehouse or serverless views. It is billed per TB per month with three components that each accumulate differently.</p><p><strong>Active bytes</strong> — what is currently in your tables. <strong>Time travel bytes</strong> — copies Snowflake maintains for your configured retention window (0–90 days), billed at the same rate as active data. <strong>Failsafe bytes</strong> — a 7-day disaster recovery window Snowflake maintains automatically. You cannot disable it. On tables with frequent DELETEs or UPDATEs, failsafe accumulates fast because it retains every historical version of modified data for 7 days.</p><p>To see storage by database:</p><pre>-- Storage by database, most recent snapshot.<br>SELECT<br>  DATABASE_NAME,<br>  ROUND(AVERAGE_DATABASE_BYTES / POWER(1024, 3), 2) AS avg_active_gb,<br>  ROUND(AVERAGE_FAILSAFE_BYTES / POWER(1024, 3), 2) AS avg_failsafe_gb,<br>  ROUND((AVERAGE_DATABASE_BYTES + AVERAGE_FAILSAFE_BYTES)<br>    / POWER(1024, 3), 2)                            AS total_billed_gb<br>FROM SNOWFLAKE.ACCOUNT_USAGE.DATABASE_STORAGE_USAGE_HISTORY<br>WHERE USAGE_DATE = CURRENT_DATE - 1<br>ORDER BY total_billed_gb DESC;</pre><p>For per-table detail — useful when storage is growing in ways that are not obvious from the database view:</p><pre>-- Top tables by total billed storage.<br>-- High failsafe_pct_of_active on large tables often indicates high-churn workloads.<br>-- Consider TRANSIENT tables or shorter DATA_RETENTION_TIME_IN_DAYS for those cases.<br>SELECT<br>  TABLE_CATALOG || &#39;.&#39; || TABLE_SCHEMA || &#39;.&#39; || TABLE_NAME AS full_table_name,<br>  ROUND(ACTIVE_BYTES      / POWER(1024, 3), 2) AS active_gb,<br>  ROUND(TIME_TRAVEL_BYTES / POWER(1024, 3), 2) AS time_travel_gb,<br>  ROUND(FAILSAFE_BYTES    / POWER(1024, 3), 2) AS failsafe_gb,<br>  ROUND(FAILSAFE_BYTES / NULLIF(ACTIVE_BYTES, 0) * 100, 1) AS failsafe_pct_of_active<br>FROM SNOWFLAKE.ACCOUNT_USAGE.TABLE_STORAGE_METRICS<br>WHERE ACTIVE_BYTES &gt; 0<br>ORDER BY (ACTIVE_BYTES + TIME_TRAVEL_BYTES + FAILSAFE_BYTES) DESC<br>LIMIT 30;</pre><p>One thing worth knowing for billing reconciliation: your invoice shows the average daily storage across the month — not a single snapshot. These queries show daily point-in-time readings. To estimate monthly cost, average the daily readings from DATABASE_STORAGE_USAGE_HISTORY across the billing month.</p><h3>Cortex Code: can you limit who uses it?</h3><p><a href="https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code">Cortex Code (CoCo)</a> is Snowflake’s AI coding assistant, available in Snowsight, as a CLI, and in the Desktop application. All three surfaces generate credits and show up under their own service types in METERING_DAILY_HISTORY.</p><p>Is possible to restrict how many credits each user can consume per day, independently per surface. This is controlled through account-level parameters (which set the default) or user-level parameters (which override the default for a specific person):</p><pre>-- Set a daily credit limit for ALL users in the account (all three surfaces).<br>-- A value of -1 means unlimited (the default). Set to 0 to block access entirely.<br>ALTER ACCOUNT SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER       = 20;<br>ALTER ACCOUNT SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 20;<br>ALTER ACCOUNT SET CORTEX_CODE_DESKTOP_DAILY_EST_CREDIT_LIMIT_PER_USER   = 20;<br><br>-- Override for a specific user (user-level always takes precedence over account-level).<br>ALTER USER power_user SET CORTEX_CODE_CLI_DAILY_EST_CREDIT_LIMIT_PER_USER = 50;<br><br>-- Block a specific user from Snowsight Cortex Code entirely.<br>ALTER USER restricted_user SET CORTEX_CODE_SNOWSIGHT_DAILY_EST_CREDIT_LIMIT_PER_USER = 0;</pre><p>The limit works on a rolling 24-hour window. Once a user hits it, that surface returns an error until the window advances. The three surfaces are independent — one hitting the limit does not affect the others.</p><p>For attribution, there are dedicated views per surface. All three use USER_ID (not USER_NAME), USAGE_TIME (not START_TIME), and TOKEN_CREDITS (not CREDITS_USED) — worth being precise here because these column names differ from what you see in other usage views:</p><pre>-- Cortex Code usage in Snowsight, by user, last 30 days.<br>-- Check the official docs for the full column list:<br>-- https://docs.snowflake.com/en/sql-reference/account-usage/cortex_code_snowsight_usage_history<br>SELECT USER_NAME,<br>       COUNT(*)                    AS interaction_count,<br>       SUM(TOKEN_CREDITS)          AS total_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_CODE_SNOWSIGHT_USAGE_HISTORY<br>WHERE USAGE_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_TIMESTAMP())<br>GROUP BY 1<br>ORDER BY 3 DESC;<br><br>-- Cortex Code CLI usage, by user, last 30 days.<br>-- https://docs.snowflake.com/en/sql-reference/account-usage/cortex_code_cli_usage_history<br>SELECT USER_NAME,<br>       COUNT(*)                    AS interaction_count,<br>       SUM(TOKEN_CREDITS)          AS total_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_CODE_CLI_USAGE_HISTORY<br>WHERE USAGE_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_TIMESTAMP())<br>GROUP BY 1<br>ORDER BY 3 DESC;<br><br>-- Cortex Code Desktop usage, by user, last 30 days.<br>-- Verify view availability: SHOW VIEWS IN SCHEMA SNOWFLAKE.ACCOUNT_USAGE LIKE &#39;CORTEX_CODE%&#39;<br>SELECT USER_NAME,<br>       COUNT(*)                    AS interaction_count,<br>       SUM(TOKEN_CREDITS)          AS total_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_CODE_DESKTOP_USAGE_HISTORY<br>WHERE USAGE_TIME &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_TIMESTAMP())<br>GROUP BY 1<br>ORDER BY 3 DESC;</pre><p>These views allow to do something the broader AI cost section in METERING_DAILY_HISTORY cannot: see exactly which user is driving Cortex Code usage, and on which surface. That matters when you have a team of developers on the platform and need to understand where AI spend is coming from before adjusting per-user limits.</p><p>For documentation on credit controls: <a href="https://docs.snowflake.com/en/user-guide/cortex-code/credit-usage-limit">Cost controls for Cortex Code</a>.</p><h3>Cost reports and internal billing</h3><p>Two different goals worth keeping separate.</p><p>The simpler one is visibility per team — each team sees how many credits they consumed, nobody gets charged differently, but everyone knows their number. The harder one is internal cost allocation: you convert credits to dollars and charge them back to business units. Finance gets a number, and that number affects someone’s actual budget.</p><p>The second requires things Snowflake cannot give you on its own: your per-credit price (contract-specific) and an organizational mapping of which team belongs to which business unit. A basic cost visibility query for the first goal:</p><pre>-- Monthly cost visibility report by cost center tag.<br>-- Replace 3.00 with your actual credit unit price.<br>-- Note: dollar amounts here are estimates, not official billing figures.<br>-- Always verify against your Snowflake invoice.<br>SELECT<br>  COALESCE(t.TAG_VALUE, &#39;Untagged&#39;)    AS cost_center,<br>  ROUND(SUM(w.CREDITS_USED), 2)         AS total_credits,<br>  -- Estimated dollar value (adjust credit price to match your contract)<br>  ROUND(SUM(w.CREDITS_USED) * 3.00, 2) AS estimated_usd<br>FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY w<br>LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.TAG_REFERENCES t<br>  ON  t.OBJECT_NAME   = w.WAREHOUSE_NAME<br>  AND t.DOMAIN = &#39;WAREHOUSE&#39;<br>  AND t.TAG_NAME      = &#39;COST_CENTER&#39;<br>WHERE w.START_TIME &gt;= DATE_TRUNC(&#39;month&#39;, CURRENT_DATE)<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><p>The hard part here is rarely the query. It is the organizational edge cases — teams sharing warehouses, projects spanning multiple cost centers, infrastructure that does not clearly belong to anyone. My approach is to attribute what can be clearly attributed and put everything ambiguous into a “shared infrastructure” bucket, allocated proportionally by total compute usage. Not exact, but explainable — and explainable matters more than precise when you are presenting numbers to people who will ask follow-up questions.</p><h3>What is exact and what is an estimate</h3><p>Worth being explicit about this rather than presenting everything as equally precise.</p><p>Warehouse compute by warehouse, by day, or by month is exact. Tag-based attribution works well when tags are actually applied consistently. Per-user costs from QUERY_ATTRIBUTION_HISTORY are reliable within the constraints of the view (short queries excluded, 8-hour latency). Serverless costs by service type are also solid.</p><p>Per-user compute attribution when users share warehouses is an approximation — QUERY_ATTRIBUTION_HISTORY uses weighted averages, which is the best available option but not a perfect split. Per-query costs estimated from QUERY_HISTORY are rougher still, since you cannot separate idle warehouse time from active execution time at the per-query level. Storage attribution by team is essentially an estimate because billing happens at the account level.</p><p>Things that cannot be attributed well with what is currently available: cloud services at the user or team level, Cortex AI token usage broken down by team without query-level tagging, replication costs by downstream consumer.</p><p>This matters because if you build an internal billing model on approximate numbers and present them as exact, someone will eventually ask a question you cannot answer well.</p><h3>Warehouses nobody is watching</h3><p>First: warehouses with AUTO_SUSPEND disabled. AUTO_SUSPEND = 0 means the warehouse never suspends automatically — it runs until someone manually turns it off. Since Snowflake charges by running time and not by query volume, a warehouse with no activity and no auto-suspend is still burning credits at full rate.</p><p>Snowflake does not have an ACCOUNT_USAGE.WAREHOUSES view, so you need two steps — first capture current warehouse config with SHOW WAREHOUSES, then join to metering history:</p><pre>-- Step 1: capture current warehouse configuration.<br>SHOW WAREHOUSES;<br><br>-- Step 2: join configuration to metering history.<br>-- SHOW WAREHOUSES returns current state only — dropped warehouses won&#39;t appear.<br>-- &quot;auto_suspend&quot; = 0 means the warehouse NEVER suspends automatically.<br>SELECT<br>  w.&quot;name&quot;                        AS warehouse_name,<br>  w.&quot;size&quot;                        AS warehouse_size,<br>  w.&quot;auto_suspend&quot;,<br>  ROUND(SUM(m.CREDITS_USED), 2)   AS credits_last_30_days<br>FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) w<br>JOIN SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY m<br>  ON m.WAREHOUSE_NAME = UPPER(w.&quot;name&quot;)<br>WHERE w.&quot;auto_suspend&quot; = 0<br>  AND m.START_TIME    &gt;= DATEADD(&#39;day&#39;, -30, CURRENT_DATE)<br>GROUP BY 1, 2, 3<br>ORDER BY 4 DESC;</pre><p>Second: warehouses where queries spend a lot of time in queue. High queue time means the warehouse is undersized for its concurrent load — users wait, but the warehouse stays busy and keeps billing. You end up paying for poor performance.</p><pre>-- Warehouses with high average queue time over the last 14 days.<br>-- pct_time_queued = what percentage of total elapsed time was just waiting.<br>-- If this is above 20-30%, that warehouse is probably undersized.<br>SELECT<br>  WAREHOUSE_NAME,<br>  WAREHOUSE_SIZE,<br>  COUNT(*)                                                              AS query_count,<br>  ROUND(AVG(QUEUED_OVERLOAD_TIME / 1000.0), 1)                         AS avg_queue_seconds,<br>  ROUND(AVG(TOTAL_ELAPSED_TIME   / 1000.0), 1)                         AS avg_duration_seconds,<br>  ROUND(AVG(QUEUED_OVERLOAD_TIME)<br>    / NULLIF(AVG(TOTAL_ELAPSED_TIME), 0) * 100, 1)                     AS pct_time_queued<br>FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY<br>WHERE START_TIME      &gt;= DATEADD(&#39;day&#39;, -14, CURRENT_DATE)<br>  AND WAREHOUSE_NAME   IS NOT NULL<br>  AND TOTAL_ELAPSED_TIME &gt; 0<br>GROUP BY 1, 2<br>HAVING query_count &gt; 20<br>ORDER BY avg_queue_seconds DESC<br>LIMIT 30;</pre><p>The reverse case is also worth checking — a warehouse with very short average query times (2–3 seconds) but sized XL or larger is probably oversized. Same query, just filter for low avg_duration_seconds with a large WAREHOUSE_SIZE.</p><h3>Anomaly detection with a rolling baseline</h3><p>Week-over-week percentage change is what most weekly reports use. It is fine but it treats every increase the same. A 10% spike at 400 credits is noise. A 10% spike at 4,000 credits is a conversation. What makes those different is context — how stable your spending normally is.</p><p>A rolling average gives you that context:</p><pre>-- Weekly compute spend with a 4-week rolling average and z-score.<br>-- A z-score above 2 means that week was statistically unusual (&gt; 2 std deviations above baseline).<br>-- A z-score around 1 is elevated but probably normal variation.<br>WITH weekly AS (<br>  SELECT<br>    DATE_TRUNC(&#39;week&#39;, USAGE_DATE)  AS week_start,<br>    SUM(CREDITS_USED)               AS weekly_credits<br>  FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_DAILY_HISTORY<br>  WHERE USAGE_DATE   &gt;= DATEADD(&#39;week&#39;, -8, CURRENT_DATE)<br>    AND SERVICE_TYPE  = &#39;WAREHOUSE_METERING&#39;<br>  GROUP BY 1<br>),<br>with_baseline AS (<br>  SELECT<br>    week_start,<br>    weekly_credits,<br>    -- Rolling average of the 4 previous weeks (not including current week)<br>    AVG(weekly_credits)    OVER (ORDER BY week_start ROWS BETWEEN 4 PRECEDING AND 1 PRECEDING) AS rolling_avg,<br>    STDDEV(weekly_credits) OVER (ORDER BY week_start ROWS BETWEEN 4 PRECEDING AND 1 PRECEDING) AS rolling_stddev<br>  FROM weekly<br>)<br>SELECT<br>  week_start,<br>  ROUND(weekly_credits, 2)                              AS credits,<br>  ROUND(rolling_avg, 2)                                 AS baseline_avg,<br>  -- z-score: how many standard deviations above or below the baseline this week was<br>  ROUND((weekly_credits - rolling_avg)<br>    / NULLIF(rolling_stddev, 0), 2)                     AS z_score<br>FROM with_baseline<br>ORDER BY week_start DESC;</pre><p>A z-score above 2 means something statistically unusual happened that week. Around 1 is elevated but probably within normal variation. This works better than raw percentages when usage is growing over time and the “normal” baseline shifts upward.</p><h3>Multi-account environments</h3><p>If you manage more than one account — dev, staging, prod, or different regional deployments — <a href="https://docs.snowflake.com/en/sql-reference/organization-usage">ORGANIZATION_USAGE</a> is the cross-account layer.</p><p>The most useful view there is <a href="https://docs.snowflake.com/en/sql-reference/organization-usage/usage_in_currency_daily">USAGE_IN_CURRENCY_DAILY</a>. It converts usage to your contract currency, which means you can do dollar comparisons without knowing your per-credit rate manually. The USAGE column is in credits when RATING_TYPE = &#39;compute&#39;, and in terabytes for storage and data transfer.</p><pre>-- Total compute spend by account this month, in credits and currency.<br>-- Requires ORGADMIN role or explicit privilege delegation from an org admin.<br>-- Latency for this view can be up to 72 hours.<br>SELECT<br>  ACCOUNT_NAME,<br>  SERVICE_TYPE,<br>  -- USAGE is in credits for compute, TB for storage/transfer<br>  ROUND(SUM(USAGE), 2)              AS total_usage,<br>  -- USAGE_IN_CURRENCY is the dollar (or contract currency) equivalent<br>  ROUND(SUM(USAGE_IN_CURRENCY), 2)  AS total_in_currency,<br>  MAX(CURRENCY)                     AS currency<br>FROM SNOWFLAKE.ORGANIZATION_USAGE.USAGE_IN_CURRENCY_DAILY<br>WHERE USAGE_DATE   &gt;= DATE_TRUNC(&#39;month&#39;, CURRENT_DATE)<br>  AND RATING_TYPE   = &#39;compute&#39;     -- filter to compute-only rows<br>GROUP BY 1, 2<br>ORDER BY 1, 4 DESC;</pre><p>One thing that comes up in practice: ORGADMIN is usually held by a central cloud team, not the data platform team. In some organizations that means you need to ask for the query to be run on your behalf, or request a privilege grant. Worth knowing before you build a report that depends on it.</p><h3>Things worth trying for improvements</h3><p><strong>Tag enforcement at warehouse creation.</strong> Right now nothing stops someone from creating an untagged warehouse and running queries on it for a month. Snowflake has governance features that allow to restrict object creation — a policy that requires the cost_center tag before a warehouse becomes usable would close this gap almost entirely.</p><p><strong>Connecting the anomaly detection to a Snowflake Task.</strong> The z-score query already gives you the signal. Wrapping it in a task that sends an email when the score exceeds 2 makes anomalies self-reporting instead of requiring someone to go look at the report.</p><p><strong>Per-team Cortex Code reporting.</strong> The per-user views exist now. Next step, aggregating by team and including it in the monthly cost report. Probably useful for engineering managers who want to understand whether AI tooling spend is spread evenly or concentrated in a few people.</p><p><strong>Incremental access tracking.</strong> Current approach for finding idle objects is a 90-day lookback in query history, which is slow. A small dedicated table updated daily by a task — recording the last access timestamp per object — would be faster and more accurate.</p><p><strong>Better replication attribution.</strong> Replication credits show up in DATABASE_REPLICATION_USAGE_HISTORY but attributing them to a team is not straightforward. If your account does significant cross-region or cross-account replication, building a tag-based model specifically for replication objects would surface costs that currently just end up in the &quot;other&quot; bucket.</p><h3>Closing</h3><p>Most of what I described is available today in ACCOUNT_USAGE and ORGANIZATION_USAGE. The data is there and it is not that hard to query. The SQL is usually the easy part.</p><p>The harder conversations are the ones you end up having with the data in hand: explaining to the analytics team why their warehouse ran all weekend, or talking to whoever enabled Search Optimization on a 500GB table that nobody queries anymore. Those conversations are awkward without numbers and easier with them. What these queries give you is something concrete to point at.</p><p>What take longer to figure out are the organizational questions — who actually owns the shared infrastructure cost, what happen when someone exceeds a budget and it is not their fault, how to handle a team that grew faster than the cost model expected. Those are not queries. They take longer than any of this took to write.</p><p><em>Useful links:</em></p><ul><li><a href="https://docs.snowflake.com/en/user-guide/cost-understanding-overall">Understanding costs in Snowflake</a></li><li><a href="https://docs.snowflake.com/en/user-guide/resource-monitors">Resource Monitors</a></li><li><a href="https://docs.snowflake.com/en/user-guide/budgets">Snowflake Budgets</a></li><li><a href="https://docs.snowflake.com/en/user-guide/object-tagging">Object Tagging</a></li><li><a href="https://docs.snowflake.com/en/sql-reference/account-usage/tag_references">TAG_REFERENCES view</a></li><li><a href="https://docs.snowflake.com/en/sql-reference/account-usage/query_attribution_history">QUERY_ATTRIBUTION_HISTORY view</a></li><li><a href="https://docs.snowflake.com/en/user-guide/cortex-code/credit-usage-limit">Cost controls for Cortex Code</a></li><li><a href="https://docs.snowflake.com/en/sql-reference/organization-usage/usage_in_currency_daily">USAGE_IN_CURRENCY_DAILY (Organization Usage)</a></li><li><a href="https://docs.snowflake.com/en/user-guide/cost-attributing">Attributing cost in Snowflake</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35666003b1d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Set Up Automated Monitoring for My Snowflake Account]]></title>
            <link>https://medium.com/@epenav81/how-i-set-up-automated-monitoring-for-my-snowflake-account-4f5ef0d72e3b?source=rss-e1042ab6a237------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5ef0d72e3b</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Eduardo Peña]]></dc:creator>
            <pubDate>Wed, 13 May 2026 23:22:48 GMT</pubDate>
            <atom:updated>2026-05-13T23:22:48.621Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Weekly cost reports, monthly audits, and a database inventory — sent by email, no external tools needed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amc1i4-ZcrudfMBHrL-elA.png" /></figure><blockquote><strong><em>Disclaimer:</em></strong><em> I work at Snowflake, but this article has nothing to do with my job. This is something I built for myself, on my own time, to solve my own problems. The scripts are not perfect — they have gaps, edge cases, and things that will probably break as the platform changes. Please don’t use this as official documentation or as a reference for how Snowflake recommends doing things. The numbers in these reports are approximations. For real billing data always check </em><a href="https://docs.snowflake.com/en/user-guide/cost-understanding-overall"><em>Snowflake’s official cost interfaces</em></a><em> and your contract.</em></blockquote><h3>What This Is About</h3><p>I wanted something to look at on Mondays. Not a deep dive — just enough to know if anything went wrong during the week and whether I needed to dig further.</p><p>The data is all there in SNOWFLAKE.ACCOUNT_USAGE. The problem is you have to remember to go check it, and I don&#39;t always do that.</p><p>So I automated it. Two stored procedures, email on a schedule, nothing to click. One covers credit costs, queries, and some security basics. The other is a monthly database inventory. Simple enough, but I actually use it.</p><p>Here’s how I built it, and the things I had to figure out along the way.</p><h3>The Two Procedures</h3><p><strong>SEND_ACCOUNT_USAGE_REPORT(report_type)</strong> — this one has two modes:</p><ul><li><strong>Weekly</strong> (every Monday at 7:00am): shows the last 7 days compared to the 7 days before, plus a month-to-date credit total. Good for catching things fast — like a warehouse that ran all weekend, or a user with a strange spike. Seven days is short enough that you can still react.</li><li><strong>Monthly</strong> (1st of each month at 7:00am): covers the full prior calendar month — not rolling 30 days, a real closed month like billing periods. More for reviewing trends, top consumers, serverless costs, and doing month-over-month comparisons.</li></ul><p><strong>SEND_ACCOUNTADMIN_DB_REPORT()</strong> — this one runs monthly only (1st of each month at 7:15am, staggered 15 minutes so it doesn&#39;t compete with the other task on the same warehouse):</p><ul><li>Builds a visual HTML inventory of every database in the account — what exists, who owns it, how much storage it’s using, and when was the last time someone ran a query against it.</li><li>Flags inactive databases with a recommendation: clean up, delete, or fix the ownership.</li><li>Color-coded by category: System, Project/Shared, Sysadmin-Owned, User personal, and Other.</li></ul><p>Both procedures find who to email by looking up who currently has the ACCOUNTADMIN role.</p><h3>What Each Report Contains</h3><h3>SEND_ACCOUNT_USAGE_REPORT</h3><h3>Sections</h3><p>The report has four sections, each answering a different question.</p><p><strong>Section 1 — Overview</strong> starts with a summary card showing total credits, compute vs. cloud services, and the change vs. the prior period. Then comes the daily credit trend. I put it here on purpose — before reading any details you should see which day drove the numbers.</p><p><strong>Section 2 — Cost Breakdown</strong> answers “where did the money go.” Service types ranked by spend, then AI and Cortex detail, then serverless costs for the monthly version, and finally top users and warehouses by compute hours.</p><p><strong>Section 3 — Performance &amp; Efficiency</strong> has the top 10 longest queries with disk spill detection, warehouse queue time, always-on warehouses with AUTO_SUSPEND disabled, and resource monitor utilization with color alerts.</p><p><strong>Section 4 — Security &amp; Governance</strong> covers failed login attempts, queries run directly under ACCOUNTADMIN, and users inactive for 30+ days who still have active credentials.</p><p>I ordered it that way because it makes more sense to me to see the big picture first — what happened and what it cost — before going into efficiency details and then security stuff at the end.</p><h3>Cortex and AI Costs</h3><p>This part took me some trial and error. I started filtering with SERVICE_TYPE = &#39;AI_SERVICES&#39;, which catches LLM function calls like CORTEX.COMPLETE and CORTEX.SUMMARIZE. But when I actually checked what service types appeared in my account, I found three more:</p><ul><li>CORTEX_AGENTS — Cortex Agents, the multi-step workflow feature</li><li>CORTEX_CODE_SNOWSIGHT — Cortex Code interactions in the Snowsight UI</li><li>CORTEX_CODE_CLI — Cortex usage from the CLI and extensions</li></ul><p>None of those were captured by the single AI_SERVICES filter. So I changed it to an IN clause:</p><pre>ai_credits_result = session.sql(<br>    &quot;SELECT ROUND(SUM(CREDITS_USED), 4) AS AI_CREDITS &quot;<br>    &quot;FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_DAILY_HISTORY &quot;<br>    &quot;WHERE USAGE_DATE &gt;= ? AND USAGE_DATE &lt; ? &quot;<br>    &quot;AND SERVICE_TYPE IN (&quot;<br>    &quot;  &#39;AI_SERVICES&#39;, &#39;CORTEX_AGENTS&#39;,&quot;<br>    &quot;  &#39;CORTEX_CODE_SNOWSIGHT&#39;, &#39;CORTEX_CODE_CLI&#39;)&quot;,<br>    params=[str(start_date), str(end_date)]<br>).collect()[0]</pre><p>And added a breakdown query so you can see how much came from each type.</p><h3>Dynamic Table and Serverless Costs (Monthly Report Only)</h3><p>This section only shows in the monthly report. Dynamic Tables and Materialized Views behave differently here — it’s worth being precise about it.</p><p>Dynamic Tables use a dedicated warehouse for their refreshes. That means their credits already show up in the Warehouse Metering section. This section adds per-object visibility on top of that: how many refreshes ran, on which warehouse, and how many credits each table consumed.</p><p>Materialized Views are genuinely serverless — they refresh without a virtual warehouse, so they don’t appear in the warehouse breakdown at all. Both are read from DYNAMIC_TABLE_REFRESH_HISTORY and MATERIALIZED_VIEW_REFRESH_HISTORY.</p><pre>dynamic_tables = session.sql(<br>    &quot;SELECT r.DATABASE_NAME, r.SCHEMA_NAME, r.NAME AS TABLE_NAME, &quot;<br>    &quot;       COALESCE(t.TABLE_OWNER, &#39;UNKNOWN&#39;) AS OWNER_ROLE, &quot;<br>    &quot;       r.WAREHOUSE_NAME, &quot;<br>    &quot;       COUNT(*)                           AS REFRESH_COUNT, &quot;<br>    &quot;       ROUND(SUM(r.CREDITS_USED), 4)     AS TOTAL_CREDITS &quot;<br>    &quot;FROM SNOWFLAKE.ACCOUNT_USAGE.DYNAMIC_TABLE_REFRESH_HISTORY r &quot;<br>    &quot;LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.TABLES t &quot;<br>    &quot;  ON  r.DATABASE_NAME = t.TABLE_CATALOG &quot;<br>    &quot;  AND r.SCHEMA_NAME   = t.TABLE_SCHEMA &quot;<br>    &quot;  AND r.NAME          = t.TABLE_NAME &quot;<br>    &quot;WHERE r.REFRESH_START_TIME &gt;= ? AND r.REFRESH_START_TIME &lt; ? &quot;<br>    &quot;GROUP BY 1, 2, 3, 4, 5 ORDER BY TOTAL_CREDITS DESC LIMIT 20&quot;,<br>    params=[str(start_date), str(end_date)]<br>).collect()</pre><p>For Materialized Views, Snowflake’s infrastructure runs them without a user — so I attribute their costs to the <strong>owner role</strong> of the object, via a LEFT JOIN to ACCOUNT_USAGE.TABLES. Dynamic Tables do have an associated warehouse, so you can cross-reference with the Warehouse Metering section above.</p><pre>mat_views = session.sql(<br>    &quot;SELECT r.DATABASE_NAME, r.SCHEMA_NAME, r.TABLE_NAME, &quot;<br>    &quot;       COALESCE(t.TABLE_OWNER, &#39;UNKNOWN&#39;) AS OWNER_ROLE, &quot;<br>    &quot;       COUNT(*)                           AS REFRESH_COUNT, &quot;<br>    &quot;       ROUND(SUM(r.CREDITS_USED), 4)     AS TOTAL_CREDITS &quot;<br>    &quot;FROM SNOWFLAKE.ACCOUNT_USAGE.MATERIALIZED_VIEW_REFRESH_HISTORY r &quot;<br>    &quot;LEFT JOIN SNOWFLAKE.ACCOUNT_USAGE.TABLES t &quot;<br>    &quot;  ON  r.DATABASE_NAME = t.TABLE_CATALOG &quot;<br>    &quot;  AND r.SCHEMA_NAME   = t.TABLE_SCHEMA &quot;<br>    &quot;  AND r.TABLE_NAME    = t.TABLE_NAME &quot;<br>    &quot;WHERE r.START_TIME &gt;= ? AND r.START_TIME &lt; ? &quot;<br>    &quot;GROUP BY 1, 2, 3, 4 &quot;<br>    &quot;ORDER BY TOTAL_CREDITS DESC LIMIT 20&quot;,<br>    params=[str(start_date), str(end_date)]<br>).collect()</pre><h3>SEND_ACCOUNTADMIN_DB_REPORT</h3><p>The monthly database report is a full HTML email — same visual style as the usage report. Summary cards at the top, a horizontal color-coded storage bar, and a table with one row per database showing a status dot, size bar, idle days, and action recommendations.</p><h3>Classifying databases</h3><p>The core is a SQL query that puts each database into a category based on its name and owner role. Five categories: SYSTEM (Snowflake-built), PROJECT (team or shared), SYSADMIN, USER (personal), and OTHER.</p><p>The personal vs. project distinction depends on a naming convention I use in my account: personal databases are owned by a role that follows the &lt;NAME&gt;_DB_ROLE pattern, and the database is named &lt;NAME&gt;_DB. If the role matches but the database name doesn&#39;t follow the pattern, it goes to PROJECT.</p><p>There’s a small SQL gotcha here: the underscore _ in a LIKE pattern is a wildcard. To match a literal underscore you have to escape it as \_.</p><pre>WHEN d.database_owner LIKE &#39;%\_DB\_ROLE&#39;<br>  OR d.database_owner LIKE &#39;%\_DB\_ROLE\_NEW&#39;<br>THEN<br>    CASE<br>        WHEN REPLACE(<br>                 REPLACE(d.database_owner, &#39;_DB_ROLE_NEW&#39;, &#39;&#39;),<br>                 &#39;_DB_ROLE&#39;, &#39;&#39;<br>             ) || &#39;_DB&#39; = d.database_name<br>        THEN &#39;USER&#39;      -- e.g., ALICE_DB_ROLE owns ALICE_DB<br>        ELSE &#39;PROJECT&#39;   -- team or shared database<br>    END</pre><p>The _NEW suffix is because I had a role migration going on when I built this. The REPLACE strips the longer suffix first — if you do it the other way, _DB_ROLE_NEW gets partially matched by the _DB_ROLE replacement and you end up with _NEW left over at the end.</p><h3>Recommendations</h3><p>Each database row gets an action label based on its category and idle time. USER databases have a size minimum (0.3 GB) before flagging — a small personal scratch database isn’t really worth mentioning. Shared and other databases have no size minimum because any abandoned shared database is worth a conversation.</p><p>The ownership check runs on top of the idle check. If a database’s owner role doesn’t match what’s expected for its category, “Fix ownership” gets added to whatever recommendation was already there. Both issues show in one cell.</p><pre>if is_user:<br>    if is_inactive and size_bytes &gt;= CLEANUP_THRESHOLD_BYTES:<br>        if days_idle is not None and days_idle &gt; 60:<br>            rec = &quot;ACTION REQUIRED: Clean up&quot;<br>        else:<br>            rec = &quot;Recommend cleanup&quot;<br>else:<br>    if days_idle is not None and days_idle &gt; 60:<br>        rec = &quot;MUST DELETE&quot;<br>    elif is_inactive:<br>        rec = &quot;Recommend delete&quot;<br><br># Ownership check — applies to all non-SYSTEM databases<br>owner_follows_convention = (<br>    owner == &quot;SYSADMIN&quot; or<br>    owner.endswith(&quot;_DB_ROLE&quot;) or<br>    owner.endswith(&quot;_DB_ROLE_NEW&quot;)<br>)<br>if key not in (&quot;SYSTEM&quot;,) and not owner_follows_convention:<br>    rec = (rec + &quot; + Fix ownership&quot;) if rec else &quot;Fix ownership&quot;</pre><h3>The DQ pattern</h3><p>The HTML is built by appending strings to a list and joining at the end. When you build HTML attribute values inside Python strings you have a quoting problem — HTML attributes use double quotes, but Python strings also use them. Instead of backslash-escaping every double quote, I just assign the character to a variable:</p><pre>DQ = chr(34)   # double-quote character<br>h.append(&#39;&lt;td align=&#39; + DQ + &#39;center&#39; + DQ + &#39; bgcolor=&#39; + DQ + &#39;#f0f8ff&#39; + DQ + &#39;&gt;&#39;)</pre><p>A bit unusual but it keeps things readable without a wall of \&quot; everywhere. Same idea applies to the SYSTEM$SEND_EMAIL call, where Q = chr(39) does the same thing for single quotes.</p><h3>Why Keep It All Inside Snowflake</h3><p>Snowflake already has everything needed:</p><ul><li><strong>SNOWFLAKE.ACCOUNT_USAGE</strong> — all the data, no need to extract it anywhere</li><li><strong>Snowpark Python</strong> — a full Python runtime inside the procedure, standard library included</li><li><strong>Snowflake Tasks</strong> — built-in scheduler with CRON support, timeout handling, and execution history</li><li><strong>SYSTEM$SEND_EMAIL</strong> — native email delivery, no external SMTP or API keys</li></ul><p>No external compute. No credentials to manage outside the platform. Data never leaves Snowflake. Access control uses the same roles already in place. And if something breaks, you check the Task history in Snowsight — same place everything else lives.</p><p>Both reports are Snowpark Python stored procedures, scheduled with Snowflake Tasks. No external tools, no cloud functions, nothing to maintain outside Snowflake.</p><pre>CREATE OR REPLACE PROCEDURE UTIL_DB.ADMIN.SEND_ACCOUNT_USAGE_REPORT(&quot;REPORT_TYPE&quot; VARCHAR)<br>RETURNS VARCHAR<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = &#39;3.11&#39;<br>PACKAGES = (&#39;snowflake-snowpark-python&#39;)<br>HANDLER = &#39;main&#39;<br>EXECUTE AS CALLER<br>AS<br>$$<br>def main(session, report_type):<br>    from datetime import datetime, timedelta<br>    from html import escape<br>    ...<br>$$;</pre><p>About EXECUTE AS CALLER — I want to explain this. When you use EXECUTE AS CALLER, the procedure runs with the privileges of whoever is calling it, not the owner. If I had used EXECUTE AS OWNER and the owner is ACCOUNTADMIN, then any user with USAGE on the procedure could basically run ACCOUNTADMIN queries through it — that&#39;s a security problem. With EXECUTE AS CALLER it only works if the caller already has ACCOUNTADMIN. For the Tasks that schedule these, it works fine as long as the tasks were created while ACCOUNTADMIN was the active role.</p><h3>Things I Learned Along the Way</h3><p>Not everything worked the first time. Here are a few things that took me longer to figure out than I expected, in case they save someone else the same time.</p><h3>Getting the Right Recipients</h3><p>The procedures email every ACCOUNTADMIN user in the account. The question is how to get that list.</p><p>My first idea was to query SNOWFLAKE.ACCOUNT_USAGE.GRANTS_TO_USERS. That works, but ACCOUNT_USAGE views can have up to two hours of latency. So if someone just got ACCOUNTADMIN, or just lost it, the report might not reflect that yet.</p><p>I switched to SHOW GRANTS OF ROLE ACCOUNTADMIN plus SHOW USERS. Both are real-time.</p><pre># Step 1: who currently holds ACCOUNTADMIN<br>session.sql(&quot;SHOW GRANTS OF ROLE ACCOUNTADMIN&quot;).collect()<br>users_df = session.sql(&quot;&quot;&quot;<br>    SELECT &quot;grantee_name&quot; AS user_name<br>    FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))<br>    WHERE &quot;granted_to&quot; = &#39;USER&#39;<br>&quot;&quot;&quot;).collect()<br><br># Step 2: get their email addresses<br>session.sql(&quot;SHOW USERS&quot;).collect()<br>user_filter = &quot;,&quot;.join([&quot;&#39;&quot; + sql_esc(u) + &quot;&#39;&quot; for u in user_list])<br>email_df = session.sql(f&quot;&quot;&quot;<br>    SELECT &quot;email&quot;<br>    FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))<br>    WHERE &quot;name&quot; IN ({user_filter})<br>    AND &quot;email&quot; IS NOT NULL AND &quot;email&quot; != &#39;&#39;<br>&quot;&quot;&quot;).collect()</pre><p>RESULT_SCAN(LAST_QUERY_ID()) reads the result of the SHOW that ran right before it in the same session. <strong>These two have to stay adjacent</strong> — if you put any SQL between them it resets LAST_QUERY_ID() and you&#39;ll read the wrong results.</p><h3>The HTML Email</h3><p>This one took me longer to figure out. I built the whole thing, ran it, and when the email arrived it looked completely broken — colors gone, layout collapsed, alternating row colors not there at all. I spent a while thinking it was a Snowpark rendering issue or something in SYSTEM$SEND_EMAIL. It wasn&#39;t. Gmail strips &lt;style&gt; blocks from incoming emails. So every CSS class, every :nth-child() selector, every flexbox layout — all gone.</p><p>The fix is to put every style as an inline attribute and compute anything dynamic in Python.</p><pre># No &lt;style&gt; block anywhere — everything is an inline attribute<br>S_TH = (&quot;background-color:#29B5E8;color:white;padding:10px;&quot;<br>        &quot;text-align:left;font-family:Arial,sans-serif;font-size:14px;&quot;)<br><br># Row alternation in Python — CSS :nth-child() doesn&#39;t work in Gmail<br>def row_bg(idx, level=None):<br>    if level == &quot;critical&quot;: return &quot;#ffcccc&quot;<br>    if level == &quot;alert&quot;:    return &quot;#ffe0b2&quot;<br>    if level in (&quot;warn&quot;, &quot;spill&quot;): return &quot;#fff3cd&quot;<br>    return &quot;#f9f9f9&quot; if idx % 2 == 1 else &quot;&quot;<br><br>def tr(idx, level=None):<br>    bg = row_bg(idx, level)<br>    # bgcolor for Outlook/legacy, style for Gmail/modern clients<br>    return (<br>        &quot;&lt;tr bgcolor=&#39;&quot; + bg + &quot;&#39; style=&#39;background-color:&quot; + bg + &quot;;&#39;&gt;&quot;<br>        if bg else &quot;&lt;tr&gt;&quot;<br>    )</pre><p>Section dividers are just a colored &lt;div&gt; band. The summary cards use an HTML &lt;table&gt; layout because flexbox doesn&#39;t work in Gmail.</p><h3>Cortex Service Types</h3><p><strong>Something to keep in mind:</strong> Cortex is probably the part of Snowflake that changes the most right now. I had to fix this at least twice already — once when CORTEX_AGENTS appeared, and once more when I noticed CORTEX_CODE_CLI in a query I ran out of curiosity. New functions, new services, new billing categories. I&#39;d suggest running SELECT DISTINCT SERVICE_TYPE FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_DAILY_HISTORY every few months to see if something new showed up. If it did, the IN clause needs updating.</p><p>The per-user breakdown only works for SQL function calls because it reads QUERY_TEXT. Cortex Code in Snowsight and CLI usage shows in the credit totals but can&#39;t be broken down per user — that&#39;s a limitation of what ACCOUNT_USAGE exposes today.</p><h3>Keeping Queries Safe</h3><p>All the data queries use Snowpark’s parameterized execution. The ? placeholders get bound at runtime so values are always treated as data, not as SQL.</p><pre>current_summary = session.sql(<br>    &quot;SELECT ROUND(SUM(CREDITS_USED), 2)         AS TOTAL_CREDITS, &quot;<br>    &quot;       ROUND(SUM(CREDITS_USED_COMPUTE), 2) AS COMPUTE_CREDITS &quot;<br>    &quot;FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_DAILY_HISTORY &quot;<br>    &quot;WHERE USAGE_DATE &gt;= ? AND USAGE_DATE &lt; ?&quot;,<br>    params=[str(start_date), str(end_date)]<br>).collect()[0]</pre><p>The one exception is SYSTEM$SEND_EMAIL. That call has to be built as a string. For that I use a small helper that doubles any single quotes before embedding a value:</p><pre>def sql_esc(val):<br>    return str(val).replace(&quot;&#39;&quot;, &quot;&#39;&#39;&quot;)<br><br>session.sql(<br>    &quot;CALL SYSTEM$SEND_EMAIL(&#39;MY_EMAIL_INTEGRATION&#39;, &quot;<br>    &quot;&#39;&quot; + sql_esc(email) + &quot;&#39;, &quot;<br>    &quot;&#39;&quot; + sql_esc(subject) + &quot;&#39;, &quot;<br>    &quot;&#39;&quot; + sql_esc(html_body) + &quot;&#39;, &#39;text/html&#39;)&quot;<br>).collect()</pre><p>And everything that goes from the database into the HTML body passes through Python’s html.escape() to avoid XSS issues in mail clients that render raw HTML.</p><h3>How to Set This Up in Your Account</h3><p>If you want to try this, here is the full path from nothing to working reports. Probably takes 20–30 minutes if things go well.</p><h3>Prerequisites</h3><p>You need the ACCOUNTADMIN role active for everything below. The procedures use EXECUTE AS CALLER, which means the person running them needs ACCOUNTADMIN — and the Tasks that schedule them also need to be created while that role is active.</p><p>You also need:</p><ul><li>At least one user in the account with a valid email address saved in their Snowflake profile. Check with DESCRIBE USER &lt;your_username&gt; and look for the email property.</li><li>Email notifications enabled at the account level. If your account is part of an organization, an Orgadmin might need to enable this first. See <a href="https://docs.snowflake.com/en/user-guide/email-stored-procedures#enabling-email-notifications">Enable email notifications</a>.</li></ul><h3>Step 1 — Create the email notification integration</h3><p>This is the object that allows Snowflake to send email through SYSTEM$SEND_EMAIL. You have to list every email address that will receive reports — Snowflake will reject anything not on the list.</p><pre>USE ROLE ACCOUNTADMIN;<br><br>CREATE NOTIFICATION INTEGRATION MY_EMAIL_INTEGRATION<br>    TYPE            = EMAIL<br>    ENABLED         = TRUE<br>    ALLOWED_RECIPIENTS = (<br>        &#39;admin1@yourcompany.com&#39;,<br>        &#39;admin2@yourcompany.com&#39;<br>    );</pre><p>The name MY_EMAIL_INTEGRATION is hardcoded in the procedures — use that name or search-and-replace it. Every address that could receive a report must be listed in ALLOWED_RECIPIENTS or Snowflake will reject the send.</p><p>Official documentation: <a href="https://docs.snowflake.com/en/sql-reference/sql/create-notification-integration-email">CREATE NOTIFICATION INTEGRATION — Email</a></p><h3>Step 2 — Create a dedicated warehouse (optional)</h3><p>The procedures are pretty light — a few queries against ACCOUNT_USAGE views and an email send. An XS warehouse is more than enough. I use a dedicated one so the tasks don&#39;t interfere with anything else, but using an existing warehouse works fine too.</p><pre>CREATE WAREHOUSE IF NOT EXISTS ACCOUNTADMIN_WH_XS<br>    WAREHOUSE_SIZE   = &#39;XSMALL&#39;<br>    AUTO_SUSPEND     = 60<br>    AUTO_RESUME      = TRUE<br>    INITIALLY_SUSPENDED = TRUE<br>    COMMENT = &#39;Dedicated warehouse for ACCOUNTADMIN monitoring tasks&#39;;</pre><p>If you use a different name, just update the three task files.</p><h3>Step 3 — Adapt the code to your environment</h3><p>Before deploying, there are a few things to adjust:</p><p><strong>In </strong><strong>send_account_usage_report.sql:</strong></p><ul><li>For the Cortex service types: run SELECT DISTINCT SERVICE_TYPE FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_DAILY_HISTORY and see what shows up in your account. If there are Cortex-related types that are not in the IN clause I have, add them.</li></ul><p><strong>In </strong><strong>send_accountadmin_db_report.sql:</strong></p><ul><li>CLEANUP_THRESHOLD_BYTES — adjust the 0.3 GB threshold to what makes sense for your account.</li><li>The _DB_ROLE / _DB_ROLE_NEW convention is mine. If you use a different naming pattern for personal databases, the LIKE patterns and the REPLACE logic in the classification query need to change. If you don&#39;t have personal databases at all, the USER category will just be empty — that&#39;s fine.</li><li>The subject prefix [Monthly DB Report] — change it to whatever fits.</li></ul><h3>Step 4 — Deploy the procedures</h3><p>Run each procedure file in your target database. I keep everything in UTIL_DB.ADMIN but you can use any schema:</p><pre>-- Deploy the usage report procedure<br>USE ROLE ACCOUNTADMIN;<br>USE DATABASE UTIL_DB;<br>USE SCHEMA ADMIN;<br><br>-- Then paste and execute the contents of send_account_usage_report.sql<br>-- and send_accountadmin_db_report.sql</pre><h3>Step 5 — Test before scheduling</h3><p>Call each procedure manually first. This confirms the email integration is working, the queries run, and the report actually arrives.</p><pre>-- Test weekly report<br>CALL UTIL_DB.ADMIN.SEND_ACCOUNT_USAGE_REPORT(&#39;WEEKLY&#39;);<br><br>-- Test monthly report  <br>CALL UTIL_DB.ADMIN.SEND_ACCOUNT_USAGE_REPORT(&#39;MONTHLY&#39;);<br><br>-- Test database inventory report<br>CALL UTIL_DB.ADMIN.SEND_ACCOUNTADMIN_DB_REPORT();</pre><p>Each call returns something like Report sent to: 2 recipients. Failed: 0. If you get No ACCOUNTADMIN users with valid emails found, it means the emails in the Snowflake user profiles don&#39;t match what you put in ALLOWED_RECIPIENTS — fix one or the other.</p><h3>Step 6 — Create the Tasks</h3><p>Once the manual test works, create the three scheduled tasks. Change the timezone in the CRON expression — my files use America/Costa_Rica, you&#39;ll want yours.</p><pre>-- Run the three task files:<br>-- weekly_account_usage_report.sql<br>-- monthly_account_usage_report.sql<br>-- monthly_accountadmin_db_report.sql<br>--<br>-- Each file already includes the ALTER TASK ... RESUME statement.<br>-- The tasks are SUSPENDED by default when created and RESUME activates them.</pre><p>To verify the tasks are active: SHOW TASKS IN SCHEMA UTIL_DB.ADMIN and look for state = started.</p><h3>Quick reference: what runs when</h3><p>Task Schedule Procedure called WEEKLY_ACCOUNT_USAGE_REPORT Every Monday 7:00am SEND_ACCOUNT_USAGE_REPORT(&#39;WEEKLY&#39;) MONTHLY_ACCOUNT_USAGE_REPORT 1st of month 7:00am SEND_ACCOUNT_USAGE_REPORT(&#39;MONTHLY&#39;) MONTHLY_ACCOUNTADMIN_DB_REPORT 1st of month 7:15am SEND_ACCOUNTADMIN_DB_REPORT()</p><h3>Scheduling</h3><p>Both procedures are wrapped in Snowflake Tasks. The two monthly tasks run 15 minutes apart so they don’t queue on the same warehouse.</p><pre>-- Every Monday at 7:00am Costa Rica time<br>CREATE OR REPLACE TASK UTIL_DB.ADMIN.WEEKLY_ACCOUNT_USAGE_REPORT<br>    WAREHOUSE            = ACCOUNTADMIN_WH_XS<br>    SCHEDULE             = &#39;USING CRON 0 7 * * 1 America/Costa_Rica&#39;<br>    USER_TASK_TIMEOUT_MS = 600000<br>    COMMENT              = &#39;Weekly account usage report&#39;<br>AS<br>    CALL UTIL_DB.ADMIN.SEND_ACCOUNT_USAGE_REPORT(&#39;WEEKLY&#39;);<br><br>ALTER TASK UTIL_DB.ADMIN.WEEKLY_ACCOUNT_USAGE_REPORT RESUME;<br><br>-- 1st of each month at 7:00am<br>CREATE OR REPLACE TASK UTIL_DB.ADMIN.MONTHLY_ACCOUNT_USAGE_REPORT<br>    WAREHOUSE            = ACCOUNTADMIN_WH_XS<br>    SCHEDULE             = &#39;USING CRON 0 7 1 * * America/Costa_Rica&#39;<br>    USER_TASK_TIMEOUT_MS = 600000<br>    COMMENT              = &#39;Monthly account usage report&#39;<br>AS<br>    CALL UTIL_DB.ADMIN.SEND_ACCOUNT_USAGE_REPORT(&#39;MONTHLY&#39;);<br><br>ALTER TASK UTIL_DB.ADMIN.MONTHLY_ACCOUNT_USAGE_REPORT RESUME;<br><br>-- 1st of each month at 7:15am (staggered to avoid warehouse contention)<br>CREATE OR REPLACE TASK UTIL_DB.ADMIN.MONTHLY_ACCOUNTADMIN_DB_REPORT<br>    WAREHOUSE            = ACCOUNTADMIN_WH_XS<br>    SCHEDULE             = &#39;USING CRON 15 7 1 * * America/Costa_Rica&#39;<br>    USER_TASK_TIMEOUT_MS = 600000<br>    COMMENT              = &#39;Monthly database inventory report&#39;<br>AS<br>    CALL UTIL_DB.ADMIN.SEND_ACCOUNTADMIN_DB_REPORT();<br><br>ALTER TASK UTIL_DB.ADMIN.MONTHLY_ACCOUNTADMIN_DB_REPORT RESUME;</pre><p>USER_TASK_TIMEOUT_MS = 600000 sets a 10-minute hard limit per task. If the email integration is slow or ACCOUNT_USAGE takes longer than expected, the task stops cleanly instead of holding the warehouse open indefinitely.</p><p>Official documentation: <a href="https://docs.snowflake.com/en/user-guide/tasks-intro">Snowflake Task Scheduling</a> | <a href="https://docs.snowflake.com/en/sql-reference/sql/create-task#schedule-parameters">CRON expressions</a></p><h3>Important: These Scripts Will Need Maintenance</h3><p>Snowflake is not a static platform. New service types show up in METERING_DAILY_HISTORY, new views get added to ACCOUNT_USAGE, and features like Cortex change fast. This matters for these scripts in some very practical ways.</p><p><strong>Cortex especially.</strong> When I first started tracking AI costs there was basically one thing to watch: AI_SERVICES. Then I ran SELECT DISTINCT SERVICE_TYPE FROM METERING_DAILY_HISTORY on my account and found three more: CORTEX_AGENTS, CORTEX_CODE_SNOWSIGHT, and CORTEX_CODE_CLI. Cortex is growing really fast — new capabilities, new billing types, new function names. The patterns in these scripts will need to be updated as new features come out. I&#39;d suggest running that DISTINCT SERVICE_TYPE query every few months just to see if something new appeared.</p><p><strong>The data is an approximation.</strong> ACCOUNT_USAGE views have up to 2 hours of latency. The Cortex per-user detection only catches SQL function calls — Cortex Code in Snowsight and CLI usage shows up in credit totals but can&#39;t be attributed per-user through QUERY_HISTORY. The database access scan only looks back 90 days, so a database inactive for 6 months shows as &quot;no recent access&quot; instead of the actual date. These are trade-offs I made for performance reasons, but it means you should read the reports as directional information, not exact billing data.</p><p><strong>If something breaks,</strong> it’s probably a schema change, a renamed column, or a new service type that changed a GROUP BY result. The procedures return a short VARCHAR — if a task is failing silently, check the task history in Snowsight under <strong>Data</strong> → <strong>Databases</strong> → UTIL_DB → <strong>Tasks</strong>.</p><h3>What I Would Still Improve</h3><p>Statistical anomaly detection would be more useful than fixed thresholds. Comparing this week against a rolling average of the last four weeks would catch real outliers without generating noise on accounts that normally run high.</p><p>The database inventory only looks back 90 days in QUERY_HISTORY — a performance trade-off. A database last used 6 months ago shows as &quot;no recent access&quot; instead of the actual date. A dedicated access tracking table updated incrementally would solve this.</p><p>The Cortex per-user breakdown is incomplete by design — only SQL function calls. There is no way through ACCOUNT_USAGE today to get per-user attribution for Cortex Code in Snowsight or CLI interactions. Maybe that changes as the platform matures.</p><p>Error handling is simple on purpose: if a query fails, the section gets skipped. A future version could write failures to a table and include a “what broke” section at the end of each report.</p><h3>What Would You Add?</h3><p>I’m curious what other people would do with this as a starting point. A few things I’ve thought about but haven’t built yet:</p><ul><li>A threshold configuration table so admins can tune cleanup thresholds per database category without touching the procedure code</li><li>A “change detection” section comparing this month’s database list to last month’s and highlighting new or deleted databases</li><li>Replication and Failover cost tracking — those have their own service types in METERING_DAILY_HISTORY</li><li>Error notification so task failures send an alert email automatically</li></ul><p>If you try this or build something on top of it, I’d love to hear about it in the comments. What did you add? What didn’t work for your environment? What would you have done differently?</p><h3>Closing</h3><p>It works for my setup. Your naming conventions, role structure, and cost thresholds are probably different, so some things will need adapting. That’s expected. Just don’t forget to revisit it when Snowflake releases new things — and they release things often. A new service type, a new Cortex feature, a new serverless capability — any of those could create a gap in what you’re tracking and you won’t know unless you check.</p><p>Anyway, I hope this is useful. If you try it or build something different on top of it, let me know in the comments.</p><h3>Complete Code</h3><p>Please go to <a href="https://github.com/bradypuscr/Snowflake/tree/b0d86ab5688a022d0b787d646b64f2f3afd9d414/Admin_Reports">my repo </a>and get the files, then copy them into your Snowflake worksheet and adjust the notification integration name and email subject prefix to match your setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5ef0d72e3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Dynamic Tables in 2026: A Practitioner’s Honest Take on What Changed]]></title>
            <link>https://medium.com/@epenav81/snowflake-dynamic-tables-in-2026-a-practitioners-honest-take-on-what-changed-2301e5d1432c?source=rss-e1042ab6a237------2</link>
            <guid isPermaLink="false">https://medium.com/p/2301e5d1432c</guid>
            <category><![CDATA[snowflake-dynamic-table]]></category>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Eduardo Peña]]></dc:creator>
            <pubDate>Mon, 04 May 2026 16:03:05 GMT</pubDate>
            <atom:updated>2026-05-04T22:44:29.185Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into before/after examples, new features, and why the product today is not what it was at GA</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpYk5fuAW0INvam809cvuA.png" /></figure><p>I want to be honest about something. When I had my first contact with Snowflake Dynamic Tables with a project of 300+ to be implemented, I was enthusiastic but also cautious. The concept is genuinely elegant — declare your transformation as a SELECT, tell Snowflake how fresh you need the data, and let it handle the rest. No streams to manage. No tasks to resume when they fail. No dependency graphs to maintain by hand.</p><p>But after using them in production for a while, there was a list of things that could be improved. Some DT initializations required you to temporary size-up the warehouse to complete the first run in short time. Insert-override patterns were not so straight to accomplish. Iceberg support was limited. The dbt integration required some more work. Some SQL patterns would silently fall back to a full refresh, and you would only find out by reading the refresh history or it instantly failed if you try INCREMENTAL requiring you to come with cleaver ways overcome this if this mode was truly your way.</p><p>But trust me, Dynamic Tables is a great feature that will ease your way to apply transformations and free your mind from the pains of orchestration.</p><p>What is better, Snowflake’s team has been shipping quietly and consistently, and the experience today is meaningfully different. This post is my attempt to document what changed, with concrete before-and-after examples, so you can evaluate it properly rather than carrying assumptions from an earlier versions.</p><p>This is going to be a long post. So go and get a good hot cup of Costa Rican coffee.</p><h3>A quick refresher before we go into examples</h3><p>If you are already familiar with the basics, skip ahead. If not, here is the one-paragraph version.</p><p>A Dynamic Table is a materialized result of a SQL query that Snowflake keeps fresh automatically. You define it once, with a TARGET_LAG that tells Snowflake how stale the data is allowed to be, and from that point on Snowflake manages the refresh cycle. It figures out what changed in the source tables, applies only the delta when possible (incremental refresh), and skips the refresh entirely if nothing changed. You do not write merge logic. You do not write scheduling code. You write a SELECT.</p><pre>CREATE DYNAMIC TABLE silver.orders_enriched<br>  TARGET_LAG = &#39;5 minutes&#39;<br>  WAREHOUSE = transform_wh<br>AS<br>  SELECT<br>    o.order_id,<br>    o.customer_id,<br>    o.amount,<br>    o.status,<br>    c.customer_name,<br>    c.tier,<br>    p.product_name,<br>    p.category<br>  FROM raw.orders o<br>  JOIN raw.customers c ON o.customer_id = c.id<br>  JOIN raw.products  p ON o.product_id  = p.id;</pre><p>That is the whole definition. Snowflake takes it from there.</p><p>There are three refresh modes: INCREMENTAL, FULL, and AUTO. When you use AUTO (which is the default and generally will suit your needs), Snowflake analyses your query at creation time and decides whether it can maintain it incrementally or whether it needs to recompute from scratch on each refresh. The list of constructs that qualify for incremental refresh has grown significantly over the past year, which I will cover in detail.</p><h3>Before and after #1: Streams + Tasks vs Dynamic Tables</h3><p>This is the comparison most people think about first, and for good reason — Streams and Tasks were the primary tool for building incremental pipelines in Snowflake for years. Let me show what a real pipeline looked like.</p><p>Suppose you have an orders table that receives new inserts and updates throughout the day, and you need to maintain an enriched version of it in a silver layer, joined with customer and product data, refreshed every five minutes.</p><p><strong>The old way — Streams and Tasks:</strong></p><pre>-- Step 1: create the stream to capture changes<br>CREATE STREAM raw.orders_stream ON TABLE raw.orders;<br><br>-- Step 2: create the target table manually<br>CREATE TABLE silver.orders_enriched (<br>  order_id       STRING,<br>  customer_id    STRING,<br>  amount         NUMBER,<br>  status         STRING,<br>  customer_name  STRING,<br>  tier           STRING,<br>  product_name   STRING,<br>  category       STRING<br>);<br><br>-- Step 3: create the task with scheduling and merge logic<br>CREATE TASK process_orders_task<br>  WAREHOUSE    = transform_wh<br>  SCHEDULE     = &#39;5 minute&#39;<br>  WHEN SYSTEM$STREAM_HAS_DATA(&#39;raw.orders_stream&#39;)<br>AS<br>  MERGE INTO silver.orders_enriched t<br>  USING (<br>    SELECT<br>      s.order_id,<br>      s.customer_id,<br>      s.amount,<br>      s.status,<br>      c.customer_name,<br>      c.tier,<br>      p.product_name,<br>      p.category,<br>      s.METADATA$ACTION,<br>      s.METADATA$ISUPDATE<br>    FROM raw.orders_stream s<br>    JOIN raw.customers c ON s.customer_id = c.id<br>    JOIN raw.products  p ON s.product_id  = p.id<br>  ) s<br>  ON t.order_id = s.order_id<br>  -- True deletes: ACTION=&#39;DELETE&#39; and ISUPDATE=FALSE<br>  WHEN MATCHED AND s.METADATA$ACTION = &#39;DELETE&#39; AND NOT s.METADATA$ISUPDATE<br>    THEN DELETE<br>  -- Updates: Snowflake streams emit two records for each UPDATE —<br>  -- one DELETE and one INSERT, both with ISUPDATE=TRUE.<br>  -- We handle the update using the INSERT half and ignore the DELETE half.<br>  WHEN MATCHED AND s.METADATA$ACTION = &#39;INSERT&#39; AND s.METADATA$ISUPDATE<br>    THEN UPDATE SET<br>      t.amount        = s.amount,<br>      t.status        = s.status,<br>      t.customer_name = s.customer_name,<br>      t.tier          = s.tier,<br>      t.product_name  = s.product_name,<br>      t.category      = s.category<br>  -- True inserts: ACTION=&#39;INSERT&#39; and ISUPDATE=FALSE<br>  WHEN NOT MATCHED AND s.METADATA$ACTION = &#39;INSERT&#39; AND NOT s.METADATA$ISUPDATE<br>    THEN INSERT (order_id, customer_id, amount, status,<br>                 customer_name, tier, product_name, category)<br>         VALUES (s.order_id, s.customer_id, s.amount, s.status,<br>                 s.customer_name, s.tier, s.product_name, s.category);<br><br>-- Step 4: do not forget to resume the task (it starts suspended)<br>ALTER TASK process_orders_task RESUME;</pre><p>And that is for a simple single-table pipeline. If you have a chain of five or six tables, each one depending on the previous, you need a task DAG, you need to handle the ordering, and you need to deal with what happens when one task in the middle fails — the stream still consumed the records, so you need to think about recovery carefully.</p><p><strong>The Dynamic Table equivalent:</strong></p><pre>CREATE DYNAMIC TABLE silver.orders_enriched<br>  TARGET_LAG = &#39;5 minutes&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    o.order_id,<br>    o.customer_id,<br>    o.amount,<br>    o.status,<br>    c.customer_name,<br>    c.tier,<br>    p.product_name,<br>    p.category<br>  FROM raw.orders o<br>  JOIN raw.customers c ON o.customer_id = c.id<br>  JOIN raw.products  p ON o.product_id  = p.id;</pre><p>Snowflake creates the stream internally, manages the merge, handles the ordering if this table feeds downstream tables, and retries on failure without consuming the change data. The dependency graph between Dynamic Tables in a pipeline is managed automatically — you just set TARGET_LAG on the tables that serve data to consumers, and Snowflake propagates the freshness requirement upstream.</p><p>I want to be clear: the Streams and Tasks approach still has its place. If you need event-driven triggers, very complex merge logic with multi-table updates, or you need Python-based transformations, tasks are the right tool. But for the large majority of SQL transformation pipelines — particularly in the silver and gold layers — Dynamic Tables reduce the code you need to write and maintain by an order of magnitude.</p><h3>Before and after #2: Primary Key support changes insert-override patterns</h3><p>This is a great feature addition (it went GA in April 2026), and for good reason. Let me explain the problem it solves.</p><p>Many data engineering patterns use what is called an insert-overwrite or INSERT OVERWRITE pattern. A staging table is completely replaced on each load — all rows are deleted and new rows are inserted. This is common when loading from object storage, when using external data tools that do not support CDC, or when the source system only provides full snapshots.</p><p>Before primary key support, a Dynamic Table reading from such a staging table had no way to know which rows actually changed and which were identical to the previous load. From the Dynamic Table’s perspective, the entire table was replaced — so it had to recompute from scratch every time. On large tables, this was very expensive.</p><p><strong>Before — full refresh on every load:</strong></p><pre>-- Source: staging table that gets fully replaced on each load<br>INSERT OVERWRITE INTO raw.orders_staging<br>  SELECT * FROM @external_stage/orders/<br>  WHERE metadata$filename LIKE &#39;%today%&#39;;<br><br>-- Downstream Dynamic Table: forced to full refresh every time<br>-- because it cannot determine which rows changed<br>CREATE DYNAMIC TABLE silver.orders_processed<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    order_id,<br>    customer_id,<br>    amount,<br>    status,<br>    CASE<br>      WHEN amount &gt; 1000 THEN &#39;high_value&#39;<br>      WHEN amount &gt; 100  THEN &#39;standard&#39;<br>      ELSE &#39;low_value&#39;<br>    END AS order_tier,<br>    DATEDIFF(&#39;day&#39;, created_at, CURRENT_DATE) AS age_days<br>  FROM raw.orders_staging;<br><br>-- On a 50M row table where only 200K rows changed today:<br>-- Snowflake still reprocesses all 50M rows on every refresh.</pre><p><strong>After — incremental refresh with PRIMARY KEY RELY:</strong></p><pre>-- Tell Snowflake it can trust order_id as the unique row identifier<br>-- RELY means you are asserting the uniqueness — Snowflake does not enforce it,<br>-- but it uses it to track changes at the row level<br>ALTER TABLE raw.orders_staging<br>  ADD PRIMARY KEY (order_id) RELY;<br><br>-- Same Dynamic Table definition — no changes needed<br>CREATE DYNAMIC TABLE silver.orders_processed<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    order_id,<br>    customer_id,<br>    amount,<br>    status,<br>    CASE<br>      WHEN amount &gt; 1000 THEN &#39;high_value&#39;<br>      WHEN amount &gt; 100  THEN &#39;standard&#39;<br>      ELSE &#39;low_value&#39;<br>    END AS order_tier,<br>    DATEDIFF(&#39;day&#39;, created_at, CURRENT_DATE) AS age_days<br>  FROM raw.orders_staging;<br><br>-- Now: only the 200K changed rows get reprocessed.<br>-- The other 49.8M rows are untouched.</pre><p>The same improvement applies to the very common SCD Type 1 deduplication pattern using QUALIFY ROW_NUMBER() = 1. Snowflake can now automatically derive the primary key from the PARTITION BY clause and maintain these tables incrementally.</p><blockquote><strong><em>Side note:</em></strong><em> SCD stands for Slowly Changing Dimension — a data warehousing concept for dealing with data that changes over time. Type 1 is the simplest variant: when something changes, you simply overwrite the old value with the new one. No history is preserved, you always keep only the most recent state. A good example is a customer’s email address — if it changes, you probably just want the current one, not a record of every previous address. The </em><em>QUALIFY ROW_NUMBER() = 1 pattern is the standard SQL implementation: for each unique entity (identified by the </em><em>PARTITION BY clause), keep only the most recent row ordered by a timestamp. It is one of the most frequently written patterns in the silver layer of a data warehouse.</em></blockquote><pre>-- Latest state per customer, maintained incrementally<br>CREATE DYNAMIC TABLE silver.latest_customer_state<br>  TARGET_LAG = &#39;5 minutes&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT *<br>  FROM raw.customer_events<br>  QUALIFY ROW_NUMBER() OVER (<br>    PARTITION BY customer_id<br>    ORDER BY updated_at DESC<br>  ) = 1;<br>-- Snowflake derives customer_id as the primary key from the PARTITION BY clause.<br>-- This now runs incrementally — only processes new events, not the entire history.</pre><p>There is a third unlock from this feature that is less obvious but equally important: mixed refresh modes in a DAG chain. Previously, if one Dynamic Table in a pipeline used full refresh mode, all downstream tables had to use full refresh as well. With primary key support, a downstream table can be incremental even if its upstream source is full refresh.</p><p>To understand why this matters, consider a ranking table. A RANK() window function assigns a position to every customer based on how many orders they have placed. The problem is that this is a global calculation — if one customer places a new order and moves up in the ranking, every single customer below them shifts by one position. There is no way to update just the rows that changed without recomputing the entire list. Snowflake has no choice but to run a full refresh on this table every time.</p><p>Before primary key support, this propagated downstream: any table reading from this full-refresh table also had to do a full refresh, because Snowflake had no way to know which rows in the output were actually different from the previous run.</p><p>With primary key support, that chain is broken. After the full refresh runs and produces a new result set, Snowflake uses customer_id as the key to compare the new rows against the previous rows — and it finds only the customers whose rank actually changed. The downstream table then receives only those specific changes, and updates incrementally.</p><pre>-- -----------------------------------------------------------------------<br>-- STEP 1: define the primary key on the source table<br>-- Without this, Snowflake has no basis for row-level change tracking.<br>-- RELY means you assert uniqueness — Snowflake trusts you but does not<br>-- enforce it with a constraint check.<br>-- -----------------------------------------------------------------------<br>ALTER TABLE raw.order_summary<br>  ADD PRIMARY KEY (customer_id) RELY;<br><br><br>-- -----------------------------------------------------------------------<br>-- UPSTREAM: forced to FULL refresh<br>-- RANK() is a global window function. If customer A places a new order<br>-- and jumps from rank 50 to rank 49, every customer ranked 49 to 50 also<br>-- shifts. There is no way to update just one row — the entire list must<br>-- be recomputed from scratch on every refresh.<br>-- -----------------------------------------------------------------------<br>CREATE DYNAMIC TABLE silver.customer_rankings<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    customer_id,<br>    total_orders,<br>    RANK() OVER (ORDER BY total_orders DESC) AS global_rank<br>  FROM raw.order_summary;  -- one row per customer with their order count<br><br>-- Because raw.order_summary has PRIMARY KEY (customer_id) RELY,<br>-- Snowflake derives customer_id as the unique key for this Dynamic Table&#39;s<br>-- output as well. You can verify this was picked up correctly by running:<br>--   SHOW UNIQUE KEYS IN silver.customer_rankings;<br><br><br>-- -----------------------------------------------------------------------<br>-- DOWNSTREAM: can be INCREMENTAL, despite reading from a full-refresh table<br>-- After silver.customer_rankings refreshes, Snowflake checks which rows<br>-- actually changed (e.g., customer_id = &#39;C123&#39; moved from rank 51 to 49).<br>-- Only those changed rows are propagated here — not the entire table.<br>-- -----------------------------------------------------------------------<br>CREATE DYNAMIC TABLE gold.customer_segments<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    r.customer_id,<br>    r.global_rank,<br>    c.country,<br>    c.tier,<br>    CASE<br>      WHEN r.global_rank &lt;= 100  THEN &#39;platinum&#39;<br>      WHEN r.global_rank &lt;= 1000 THEN &#39;gold&#39;<br>      ELSE &#39;standard&#39;<br>    END AS segment<br>  FROM silver.customer_rankings r<br>  JOIN raw.customers c ON r.customer_id = c.customer_id;<br><br>-- If 10,000 customers changed rank out of 2 million total,<br>-- only those 10,000 rows get updated here. The other 1,990,000 are untouched.</pre><h3>Before and after #3: If you use dbt, pay attention to this one</h3><p>I use dbt. Most of the teams I work with use dbt. And the relationship between dbt and Dynamic Tables has been awkward since the beginning — the integration worked, but it was not clean, and certain Dynamic Table properties like INITIALIZATION_WAREHOUSE and IMMUTABLE WHERE were not exposed through the adapter.</p><p>The new dbt adapter, available in dbt-adapters 1.12, changes this meaningfully. Let me show the before and after.</p><p><strong>Before — a typical dbt table model (CTAS):</strong></p><pre>-- models/silver/orders_enriched.sql<br>{{ config(<br>    materialized = &#39;table&#39;<br>) }}<br><br>SELECT<br>  o.order_id,<br>  o.customer_id,<br>  o.amount,<br>  o.status,<br>  c.customer_name,<br>  c.tier,<br>  p.product_name,<br>  p.category,<br>  DATEDIFF(&#39;hour&#39;, o.created_at, CURRENT_TIMESTAMP) AS hours_since_order<br>FROM {{ ref(&#39;raw_orders&#39;) }}   o<br>JOIN {{ ref(&#39;customers&#39;) }}    c ON o.customer_id = c.id<br>JOIN {{ ref(&#39;products&#39;) }}     p ON o.product_id  = p.id</pre><p>Every time dbt run executes, this model runs a CREATE TABLE AS SELECT — a full recompute, regardless of whether any source data changed. If your pipeline runs every 30 minutes and the source data only changes twice per day, you are paying for 46 unnecessary full refreshes every day.</p><p><strong>After — same model, materialized as a Dynamic Table:</strong></p><pre>-- models/silver/orders_enriched.sql<br>{{ config(<br>    materialized         = &#39;dynamic_table&#39;,<br>    target_lag           = &#39;30 minutes&#39;,<br>    snowflake_warehouse  = &#39;transform_wh&#39;<br>) }}<br><br>SELECT<br>  o.order_id,<br>  o.customer_id,<br>  o.amount,<br>  o.status,<br>  c.customer_name,<br>  c.tier,<br>  p.product_name,<br>  p.category,<br>  DATEDIFF(&#39;hour&#39;, o.created_at, CURRENT_TIMESTAMP) AS hours_since_order<br>FROM {{ ref(&#39;raw_orders&#39;) }}   o<br>JOIN {{ ref(&#39;customers&#39;) }}    c ON o.customer_id = c.id<br>JOIN {{ ref(&#39;products&#39;) }}     p ON o.product_id  = p.id</pre><p>Three things happen with this change. First, Snowflake analyses the query and, if it can maintain it incrementally, it will — so instead of recomputing all rows, it processes only what changed. Second, if the source tables have not changed since the last refresh, Snowflake skips the refresh entirely — zero compute cost. Third, the TARGET_LAG setting means Snowflake manages the scheduling, so you are no longer depending on the dbt run schedule for data freshness.</p><p>The adapter also now supports schema evolution properly. If you use CREATE OR REPLACE (which is what materialized=&#39;table&#39; does), any schema change in the underlying query rebuilds the table from scratch. With CREATE OR ALTER — which is what the new Dynamic Table adapter uses under the hood — Snowflake applies only the structural change needed, and downstream Dynamic Tables in the same pipeline stay alive and keep refreshing.</p><p>For teams that want to use dbt as their orchestration layer but still want Dynamic Table semantics, the adapter also exposes a scheduler disable option. This means you can trigger refreshes manually from dbt while still benefiting from the incremental processing that Dynamic Tables provide internally.</p><p>There is an important nuance here: the dynamic_table materialization works best for models that do SQL transformations — joins, aggregations, window functions, filtering. If your dbt model does Python transformations or has complex pre/post hooks that need to run on every execution, the fit is less clean. For those, keeping materialized=&#39;table&#39; or using Snowpark is a better call.</p><h3>Before and after #4: Iceberg is now a first-class citizen</h3><p>When Dynamic Tables launched, the output was always a native Snowflake table. That meant the data was in Snowflake’s internal format, and external compute engines — Spark, Trino, Flink — could not read it without going through a connector. For teams building lakehouses with an open format requirement, this was a real limitation.</p><p>That has changed. You can now create Dynamic Iceberg Tables, where the output is written in open Apache Iceberg format, stored in your own object storage, and readable by any engine that supports Iceberg. The transformation semantics are identical — you still define a SELECT, you still set a TARGET_LAG, and Snowflake still manages the incremental refresh. The only difference is what the output looks like on disk.</p><p><strong>Before — native Snowflake table (locked format):</strong></p><pre>CREATE DYNAMIC TABLE analytics.fact_orders<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    customer_id,<br>    DATE_TRUNC(&#39;day&#39;, created_at)     AS order_date,<br>    SUM(amount)                        AS total_amount,<br>    COUNT(*)                           AS order_count<br>  FROM silver.orders_enriched<br>  GROUP BY 1, 2;<br><br>-- This data is only accessible through Snowflake.<br>-- External Spark jobs, Trino queries, or other engines<br>-- cannot read this table without going through Snowflake connectors.</pre><p><strong>After — Dynamic Iceberg Table (open format, external engines can read):</strong></p><pre>CREATE DYNAMIC ICEBERG TABLE analytics.fact_orders<br>  TARGET_LAG       = &#39;1 hour&#39;<br>  WAREHOUSE        = transform_wh<br>  EXTERNAL_VOLUME  = &#39;my_s3_iceberg_volume&#39;<br>  CATALOG          = &#39;SNOWFLAKE&#39;<br>  BASE_LOCATION    = &#39;analytics/fact_orders/&#39;<br>AS<br>  SELECT<br>    customer_id,<br>    DATE_TRUNC(&#39;day&#39;, created_at)     AS order_date,<br>    SUM(amount)                        AS total_amount,<br>    COUNT(*)                           AS order_count<br>  FROM silver.orders_enriched<br>  GROUP BY 1, 2;<br><br>-- This data is now:<br>-- 1. Written in open Iceberg format to your S3 bucket<br>-- 2. Readable by Spark, Trino, Flink via Horizon Catalog<br>-- 3. Still maintained incrementally by Snowflake<br>-- 4. Still managed through standard Snowflake governance and security</pre><p>Iceberg V2 and V3 are both supported. With V3, Snowflake’s semi-structured VARIANT type is now fully supported in open Iceberg format — which was a blocker for many teams that use JSON data heavily.</p><p>The primary key improvement I described earlier also matters a lot here. In Iceberg V2, change tracking at the row level was file-based, which made update and delete operations expensive on Dynamic Tables. With PRIMARY KEY RELY, that changes — Snowflake can identify which specific rows changed and update only those, bringing Iceberg DT performance much closer to what you see with native tables.</p><p>So now is possible to use this pattern effectively where Snowflake does all the transformation work — the join logic, the aggregation, the deduplication — and the output lands in Iceberg format for consumption by downstream systems that might be running on a completely different stack. You get the productivity of writing SQL in Snowflake and the openness of an Iceberg-based lakehouse at the same time.</p><h3>Other things that shipped and deserve mention</h3><p>Beyond the four main before/after scenarios, there are several features that have shipped in the last six to eight months that, while less dramatic individually, add up to a meaningfully better experience.</p><p><strong>Cortex AI functions in incremental refresh.</strong> You can now use Snowflake Cortex AI functions — things like AI_CLASSIFY, AI_SENTIMENT, AI_COMPLETE — directly inside a Dynamic Table definition, and they will run incrementally. This means you can build an AI enrichment pipeline that processes only new records, rather than re-running your LLM calls on the entire dataset every refresh.</p><pre>CREATE DYNAMIC TABLE silver.support_tickets_enriched<br>  TARGET_LAG = &#39;10 minutes&#39;<br>  WAREHOUSE  = transform_wh<br>AS<br>  SELECT<br>    ticket_id,<br>    ticket_text,<br>    created_at,<br>    AI_CLASSIFY(<br>      ticket_text,<br>      [&#39;billing&#39;, &#39;technical&#39;, &#39;account&#39;, &#39;shipping&#39;, &#39;other&#39;]<br>    ) AS category,<br>    AI_SENTIMENT(ticket_text) AS sentiment_score<br>  FROM raw.support_tickets;<br>-- Cortex functions run only on new tickets, not the full history.<br>-- This alone can save significant cost on high-volume tables.</pre><p><strong>Immutability constraints.</strong> This one is underused but very useful. You can mark a portion of a Dynamic Table as immutable — rows that match a certain condition will never be recomputed, even on a full refresh. The practical use case is historical data: if you have millions of rows from two years ago that will never change, you can tell Snowflake to leave them alone.</p><pre>CREATE DYNAMIC TABLE silver.orders_history<br>  TARGET_LAG    = &#39;1 hour&#39;<br>  WAREHOUSE     = transform_wh<br>  IMMUTABLE WHERE created_at &lt; DATEADD(&#39;day&#39;, -90, CURRENT_DATE)<br>AS<br>  SELECT * FROM raw.orders;<br>-- Rows older than 90 days are written once and never touched again,<br>-- even when a full refresh happens. Only the last 90 days of data<br>-- gets reprocessed when the source changes.</pre><p><strong>Refresh boundaries.</strong> If you work in a team where different groups own different parts of a pipeline, this feature solves a real coordination problem. Without refresh boundaries, all Dynamic Tables in a connected DAG share the same pipeline and refresh together. With DYNAMIC_TABLE_REFRESH_BOUNDARY(), you can create a soft break between pipelines — the downstream table reads from the upstream table but does not join its refresh cycle.</p><pre>-- Team A owns and maintains this table<br>CREATE DYNAMIC TABLE team_a.processed_events<br>  TARGET_LAG = &#39;15 minutes&#39;<br>  WAREHOUSE  = team_a_wh<br>AS<br>  SELECT * FROM raw.events WHERE event_type = &#39;purchase&#39;;<br><br>-- Team B consumes it but does not want to be tied to Team A&#39;s refresh schedule<br>CREATE DYNAMIC TABLE team_b.event_aggregates<br>  TARGET_LAG = &#39;1 hour&#39;<br>  WAREHOUSE  = team_b_wh<br>AS<br>  SELECT<br>    DATE_TRUNC(&#39;hour&#39;, event_time) AS hour,<br>    COUNT(*)                        AS event_count,<br>    SUM(amount)                     AS total_amount<br>  FROM DYNAMIC_TABLE_REFRESH_BOUNDARY(team_a.processed_events)<br>  GROUP BY 1;<br>-- team_b.event_aggregates refreshes on its own schedule,<br>-- reading whatever is available in team_a.processed_events at that moment.<br>-- Team B does not pay for Team A&#39;s refresh compute.</pre><p><strong>Schema evolution for SELECT *.</strong> A small but useful improvement. If you define a Dynamic Table with SELECT * and the source table gains a new column, the Dynamic Table now automatically evolves to include it — no manual CREATE OR REPLACE needed. This may sound minor, but in practice it eliminates a whole class of pipeline breakage when upstream teams add columns.</p><p><strong>DCM Projects.</strong> For teams that want proper CI/CD workflows for their Dynamic Table pipelines, DCM (Declarative Change Management) Projects are now in preview. They let you define your entire pipeline as a set of SQL files, run a plan step that shows what will change before you deploy, and promote changes across environments in a controlled way. If you are familiar with Terraform’s plan/apply workflow, the mental model is similar.</p><h3>Myths I keep having to correct in conversations</h3><p><strong>“Dynamic Tables do not work with Iceberg.”</strong> They do. Read from Iceberg, write to Iceberg, full feature parity. I covered this above.</p><p><strong>“You cannot use Cortex AI functions inside a Dynamic Table.”</strong> You can, and they run incrementally. The only limitation is that the same availability restrictions as regular Cortex functions apply.</p><p><strong>“Full refresh mode is always wasteful — you should always force incremental.”</strong> This is a misconception that causes real problems. If your base table changes significantly between refreshes — say, 80% of rows are different — incremental refresh has to process all those change records, track inserts, updates, and deletes separately, and merge them in. A full refresh just runs the query. For volatile tables with large change sets, full refresh can be faster and cheaper. The AUTO mode exists precisely for this reason: let Snowflake decide, and revisit only if you have evidence that the wrong choice is being made.</p><p><strong>“Dynamic Tables are not suitable for near real-time use cases.”</strong> This used to be more true than it is now. The minimum TARGET_LAG in general availability is one minute. But this might change while the product keeps evolving.</p><p><strong>“If my upstream table is full refresh, my downstream tables have to be full refresh too.”</strong> No longer true, as I described in the primary key section. With a primary key defined on the intermediate table, downstream tables can be incremental even when upstream is full.</p><h3>What I think is coming</h3><p>The team is clearly working on: making more complex SQL constructs incrementalizable, reducing the cases where you need to split a query across multiple tables for performance reasons, and improving the expressibility of the pipeline model for use cases that currently require tasks and streams.</p><p>There are also improvements coming in the observability area — the Snowsight monitoring for Dynamic Tables has improved, the integration with Cortex Code for troubleshooting is genuinely useful, and I expect more in that direction.</p><p>If this product area matters to you, the Snowflake release notes are worth following closely in the coming months.</p><h3>Closing thoughts</h3><p>I started this post by saying I was cautious about Dynamic Tables when I had my first contact. I want to close it by being equally honest in the other direction: the product today is strong enough that it should be your default choice for SQL transformation pipelines in Snowflake, with tasks and streams reserved for the specific cases where you need event-driven triggers or procedural logic.</p><p>The combination of features that have shipped — primary key support, full Iceberg parity, the dbt adapter, Cortex AI integration, immutability constraints, refresh boundaries — means that most of the objections I used to hear about Dynamic Tables are no longer valid. The cases where they fall short are narrower than they were, and the cases where they genuinely shine have gotten much larger.</p><p>If you have avoided them because of a bad experience six months ago, or because you heard they did not work with Iceberg, or because the dbt integration was unreliable — it is worth taking another look. What you remember is probably not what exists today.</p><p><em>All SQL examples in this post use generic table and warehouse names. Adapt them to your own naming conventions and test in a non-production environment before applying to production pipelines.</em></p><p><em>Useful links:</em></p><ul><li><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-primary-keys"><em>Primary Key Support in Dynamic Tables</em></a></li><li><a href="https://docs.snowflake.com/en/release-notes/2025/other/2025-09-11-dynamic-tables-cortex-aisql-support"><em>Cortex AI Functions in Incremental Refresh</em></a></li><li><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-create-iceberg"><em>Create Dynamic Iceberg Tables</em></a></li><li><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-immutability-constraints"><em>Immutability Constraints</em></a></li><li><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-refresh-boundary"><em>Dynamic Table Refresh Boundaries</em></a></li><li><a href="https://www.snowflake.com/en/developers/guides/dcm-projects-for-dynamic-tables/"><em>DCM Projects for Dynamic Tables</em></a></li><li><a href="https://medium.com/snowflake/dynamic-tables-dbt-a-powerful-combination-f550ebc23d60"><em>Dynamic Tables + dbt</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2301e5d1432c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>