4: Performance Optimization, Querying, and Transformation

    Evaluate query performance

    Performance work in Snowflake begins with measurement, not configuration.

    A Snowflake warehouse will scale up, scale out, and spill to remote storage without telling the operator that the workload has outgrown its design.

    The first job of an operator is to read the signals the engine emits, attribute cost to the right consumer, and decide whether the right answer is to change the SQL, change the warehouse, or change the table design.

    This section covers the diagnostic surface that ships with the platform:

    • Query Profile in Snowsight
    • The SNOWFLAKE.ACCOUNT_USAGE views for historical analysis
    • The workload management practices that keep mixed traffic from interfering with itself

    How it works

    The diagnostic loop is short.

    A user reports a slow query, the operator opens Query Profile to read the executed plan, walks the operator tree for the four canonical bad signals (spill, pruning, exploding joins, queuing), confirms the pattern across runs with QUERY_HISTORY, and then attributes the cost using QUERY_ATTRIBUTION_HISTORY to decide who pays for the fix.

    Skipping any step in this loop produces optimization based on intuition rather than evidence, which is the most common failure mode for new Snowflake operators.

    Query Performance Tuning

    Snowflake separates the storage layer from the compute layer, which means that performance tuning has two distinct dimensions:

    • The warehouse (size, scaling, type)
    • The data layout (clustering, micro-partitions, materialization)

    Tuning a query in Snowflake is the act of identifying which of those two dimensions is the bottleneck and then applying the cheapest fix that resolves it. The cheapest fix is rarely the one that comes to mind first. The tuning hierarchy is:

    • read the SQL,
    • read the Query Profile,
    • isolate the dominant operator,
    • decide whether the bottleneck is scan-bound or compute-bound,
    • then apply a single change and re-measure.

    Scan-bound queries (high partitions scanned, low effective filter) want better pruning or search optimization.

    Compute-bound queries (high local disk I/O, high CPU time, spill to remote) want a larger warehouse, query acceleration, or rewritten SQL. Mixing both changes at once makes attribution impossible.

    A typical tuning session starts with the worst-offender list. The query below builds that list from QUERY_HISTORY across the last seven days, ranked by total execution time and weighted by how often the same statement repeats.

    SELECT
     query_parameterized_hash,
     ANY_VALUE(query_text) AS sample_text,
     COUNT(*) AS executions,
     SUM(execution_time)/1000 AS total_seconds,
     AVG(execution_time)/1000 AS avg_seconds,
     SUM(bytes_spilled_to_local_storage) AS local_spill,
     SUM(bytes_spilled_to_remote_storage) AS remote_spill,
     AVG(partitions_scanned) AS avg_part_scanned,
     AVG(partitions_total) AS avg_part_total
    FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
    WHERE start_time > DATEADD(day, -7, CURRENT_TIMESTAMP())
     AND warehouse_size IS NOT NULL
     AND execution_status = 'SUCCESS'
    GROUP BY query_parameterized_hash
    HAVING executions >= 5
    ORDER BY total_seconds DESC
    LIMIT 50;
    

    Group by QUERY_PARAMETERIZED_HASH so that the same SQL with different literal values aggregates into one row. Filter on WAREHOUSE_SIZE IS NOT NULL to exclude metadata-only queries that ran in the Cloud Services layer.

    πŸ’‘ Exam Trap: ACCOUNT_USAGE.QUERY_HISTORY has a latency of up to 45 minutes and retains 365 days of history. INFORMATION_SCHEMA.QUERY_HISTORY has no latency but retains only 7 days and is scoped to the current account session. The exam will offer both as the source for "near-real-time" investigation; pick INFORMATION_SCHEMA for that case.

    πŸ“Š Limit: ACCOUNT_USAGE views retain 365 days of history; latency from 45 minutes to 3 hours depending on the view. INFORMATION_SCHEMA functions return between 7 and 14 days depending on the function.

    Query Profile and query insights

    Key points

    Query Profile is the per-query plan visualizer in Snowsight. It draws the operator tree for one execution of one statement and annotates each operator with:

    • row counts
    • partitions scanned
    • partitions total
    • bytes scanned
    • bytes written
    • the percentage of total query time spent in that node. The profile is the single most informative artifact for one-off performance investigations because it ties what the SQL asked for to what the engine actually did.

    Open Query Profile by clicking the query ID in Snowsight's Query History page, or by querying SYSTEM$GET_QUERY_OPERATOR_STATS(<query_id>) for a programmatic view. The profile tab shows the plan as a directed acyclic graph with the result node at the bottom and the scan nodes at the top. Each node has a percentage that represents its share of total query execution time. The operator that consumes the largest share is the first place to look.

    Query Insights is the Snowsight panel sitting next to Query Profile. It calls out specific patterns automatically:

    • "Queries with most local disk spillage"
    • "Queries with inefficient pruning"
    • "Queries with an exploding join"
    • "Queries with most data scanned from cache" Insights do not replace reading the profile; they prioritize which queries to read the profile for.

    The Profile Overview tab on the right side lists the four key statistics:

    • Total Execution Time
    • Bytes Scanned
    • Partitions Scanned of Total
    • Bytes Spilled
    • These four values are sufficient to classify the bottleneck most of the time. The Statistics section below them adds the row counts for IO, DML, Pruning, and Spilling.

    Bytes spilled to storage

    Spill happens when an operator (typically Sort, Hash Aggregate, or Hash Join) cannot hold its working set in the memory of the warehouse node and has to write intermediate state to local SSD (local spill) and then to remote storage (remote spill) when the SSD also fills. Local spill is a yellow flag; remote spill is a red flag because remote I/O is two orders of magnitude slower than memory.

    The fix for spill is one of: (1) size the warehouse up so the per-node memory grows, (2) use a Snowpark Optimized warehouse which has roughly 16x the memory per node of a Standard warehouse of the same size, (3) reduce the working set by pushing filters and projections closer to the scan, or (4) replace a hash-heavy join pattern with a join on a clustered key. Query acceleration service can also offload scan-side work but does not help with the join-side memory pressure.

    πŸ“Š Limit: A Standard Gen 2 X-Small has approximately 16 GB of memory per node and 200 GB of local SSD per node; doubling the warehouse size doubles both. Snowpark Optimized warehouses have roughly 16x the memory per node of a Standard warehouse of the same size, at 1.5x the credit rate.

    Inefficient pruning

    Pruning is Snowflake's term for using micro-partition metadata to skip files at scan time.

    The Profile's Statistics panel shows "Partitions scanned" over "Partitions total".

    • A query that scans 1,000 partitions out of 1,000 has zero pruning.
    • A query that scans 5 out of 1,000 has aggressive pruning.

    Inefficient pruning means the WHERE clause did not give the engine enough information to skip files, so the warehouse paid to read data it did not need.

    The two common causes of bad pruning are filter predicates that do not align with the table's natural clustering (for example, filtering on customer_id when the table is clustered by order_date), and predicates that wrap the column in a function (WHERE TO_DATE(order_ts) = '...') which defeats the metadata range lookup.

    The fix is either to add a clustering key that matches the access pattern, add search optimization for selective point lookups, or rewrite the predicate so it can use the range metadata directly.

    -- Bad: function on the column prevents range pruning
    SELECT * FROM sales
    WHERE DATE_TRUNC('month', sale_ts) = '2026-01-01';
    
    -- Better: open range predicate keeps the metadata usable
    SELECT * FROM sales
    WHERE sale_ts >= '2026-01-01'
     AND sale_ts < '2026-02-01';
    

    πŸ’‘ Exam Trap: Wrapping a column in a function or casting it inside a WHERE clause defeats partition pruning even when the function is deterministic. Snowflake compares the literal to micro-partition min/max metadata on the raw column, not on the function result.

    Exploding joins

    An exploding join is one where the output row count is many multiples of the larger input row count, almost always because the join key has duplicate values on both sides that multiply (a Cartesian-like blow-up).

    In Query Profile the join operator shows an output row count much larger than either input.

    The profile's join node displays input rows on each side and output rows; when output > input_left * input_right / a small factor, the join is exploding. The fix is one of three things:

    • Deduplicate the join keys before the join (a DISTINCT or a window-function rank-and-filter).
    • Tighten the join predicate with an extra equality column.
    • Replace the join with a correlated subquery or a window function when the goal is a per-row lookup rather than a cross product.

    The exam frequently couples exploding joins with spill because the blown-up intermediate result also overflows memory.

    -- Exploding: orders has 10 lines per order_id, customers has 1 row per id
    -- but the predicate is missing a column and produces duplicates
    SELECT o.order_id, c.region, SUM(o.amount) AS total
    FROM orders o
    JOIN customers c
     ON o.customer_id = c.customer_id
     AND c.effective_dt <= o.order_dt -- without an upper bound, joins to every history row
    GROUP BY 1, 2;
    
    -- Fixed: bracket the SCD-2 join with both ends of the effective window
    SELECT o.order_id, c.region, SUM(o.amount) AS total
    FROM orders o
    JOIN customers c
     ON o.customer_id = c.customer_id
     AND o.order_dt >= c.effective_dt
     AND o.order_dt < c.end_dt
    GROUP BY 1, 2;
    

    ⚠️ Anti-Pattern: Adding DISTINCT to the outer SELECT to mask an exploding join. The join still blows up, the engine still spills, and the warehouse still pays for the work; the only thing that changes is the row count in the result. Fix the join predicate instead.

    Queuing

    Queuing happens when a query is admitted to a warehouse but cannot start because all the compute slots are occupied by concurrent queries.

    The Profile and Query History show a non-zero "Queued (overload)" or "Queued (provisioning)" component in the total query time.

    Provisioning queue time means the warehouse cluster is starting; overload queue time means concurrency is saturated. Three controls govern queuing.

    • MAX_CONCURRENCY_LEVEL caps how many queries one cluster will run at once (default 8).
    • STATEMENT_QUEUED_TIMEOUT_IN_SECONDS aborts a query that waits longer than the configured limit.
    • MAX_CLUSTER_COUNT lets a multi-cluster warehouse add clusters when queueing pressure rises.

    For mixed workloads the answer is usually to add a second warehouse rather than to push the concurrency cap higher; pushing the cap higher just degrades all queries on that cluster simultaneously.

    🎯 Scenario: A BI team complains that dashboards are slow between 9:00 and 11:00 each morning. Query History shows 250 ms of pure execution time per query but 4 seconds of queued time. The right fix is to convert the dashboard warehouse to a multi-cluster warehouse with MIN_CLUSTER_COUNT=1, MAX_CLUSTER_COUNT=4, SCALING_POLICY='STANDARD' so that the cluster count expands during the morning peak and contracts after, not to size the warehouse up (which doubles cost without helping concurrency).

    SNOWFLAKE.ACCOUNT_USAGE views

    The Profile shows one query at a time.

    To investigate a pattern across the account, switch to the SNOWFLAKE database, ACCOUNT_USAGE schema.

    This schema holds the long-history operational metadata for the entire account:

    • every query
    • every login
    • every warehouse meter tick
    • every grant

    It is accessible only to roles that have been granted the ACCOUNT_USAGE schema imported privileges (ACCOUNTADMIN by default, plus any roles granted IMPORTED PRIVILEGES on the SNOWFLAKE database). The view set relevant to performance investigation includes:

    • QUERY_HISTORY (per-query metrics)
    • QUERY_ATTRIBUTION_HISTORY (credit attribution per query)
    • WAREHOUSE_LOAD_HISTORY (warehouse-level concurrency and queue depth)
    • WAREHOUSE_METERING_HISTORY (credits per warehouse per hour)
    • AUTOMATIC_CLUSTERING_HISTORY (clustering service spend per table)

    Query attribution

    QUERY_ATTRIBUTION_HISTORY is the view that translates wall-clock query time into credit cost. It contains one row per query with a CREDITS_ATTRIBUTED_COMPUTE column that divides the warehouse's metered credits across the queries that ran on it during the metering window. Sum credits by user, role, or query tag to attribute cost to teams.

    SELECT
     query_tag,
     user_name,
     SUM(credits_attributed_compute) AS credits,
     COUNT(*) AS executions
    FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_ATTRIBUTION_HISTORY
    WHERE start_time > DATEADD(day, -30, CURRENT_TIMESTAMP())
    GROUP BY 1, 2
    ORDER BY credits DESC;
    

    The view is the only correct source for per-query credit allocation. Multiplying query execution time by a warehouse credit rate produces a wrong answer because it double-counts when queries run in parallel and under-counts the idle-warehouse minimums.

    πŸ’‘ Exam Trap: WAREHOUSE_METERING_HISTORY is the source for total credits billed by a warehouse. QUERY_ATTRIBUTION_HISTORY is the source for credits attributed to individual queries. The two should reconcile within a metering window but they are distinct views; do not interchange them.

    Query history

    QUERY_HISTORY is the workhorse view: 365 days of one row per query with columns for execution time, bytes scanned, partitions scanned, bytes spilled, warehouse size, warehouse type, error code, query tag, and user.

    Sort by EXECUTION_TIME for slow queries, by BYTES_SCANNED for expensive queries, by BYTES_SPILLED_TO_REMOTE_STORAGE for spilling queries.

    The view also exposes QUERY_HASH (hash of the normalized text) and QUERY_PARAMETERIZED_HASH (hash with literal values masked).

    • Use parameterized hash to group runs of the same template SQL together.
    • Use the plain hash when you want exact text matches.

    INFORMATION_SCHEMA.QUERY_HISTORY (a table function, not a view) is the no-latency alternative. Call it with QUERY_HISTORY_BY_USER, QUERY_HISTORY_BY_WAREHOUSE, or QUERY_HISTORY_BY_SESSION to scope. It returns the last 7 days for most calls.

    -- Worst spilling queries in the last day, near real time
    SELECT query_id, query_text, bytes_spilled_to_remote_storage
    FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
     DATEADD('hour', -24, CURRENT_TIMESTAMP()),
     CURRENT_TIMESTAMP()
    ))
    WHERE bytes_spilled_to_remote_storage > 0
    ORDER BY bytes_spilled_to_remote_storage DESC
    LIMIT 20;
    

    πŸ“Š Limit: ACCOUNT_USAGE.QUERY_HISTORY: 365 days retention, 45 minute latency. INFORMATION_SCHEMA.QUERY_HISTORY: 14 days retention, no latency, account-scoped table function.

    Workload management best practices

    Workload management is the practice of assigning queries to the right warehouse so that one workload's noise does not push another workload into queueing or spill. The default failure mode of new Snowflake accounts is one big warehouse that serves every workload; the symptom is a hot dashboard slowed by a long ELT job, or an ELT job paused behind interactive SQL.

    The rule is one warehouse per workload class, sized for that class's working set and concurrency. Run loading jobs on a load warehouse, transformations on a transform warehouse, BI on a BI warehouse, ad-hoc on a separate ad-hoc warehouse.

    The cost penalty for splitting is small (only the 60-second per-resume minimum applies independently) and the noise isolation benefit is large.

    Grouping similar workloads

    Within each workload class, group jobs by their working set size and runtime characteristics, not by team.

    Two long-running aggregations from different teams belong on the same transform warehouse; a long-running aggregation and a small interactive query do not, because the long job will own the warehouse cache and the small query will see a cold cache on every run. The four canonical groupings for Snowflake workloads are:

    1. Ingest: small writes, low memory, high concurrency. Size X-Small to Small. Use a multi-cluster warehouse if pipes or tasks fan out.
    2. Transform: large scans, high memory, long-running. Size Medium to X-Large. Use Snowpark Optimized if Python UDFs or Snowpark workloads dominate.
    3. BI and reporting: predictable medium scans, very high concurrency. Multi-cluster warehouse, Standard scaling policy.
    4. Ad-hoc and data science: highly variable. Multi-cluster warehouse with Economy scaling policy or auto-suspend at 60 seconds.

    ⚠️ Anti-Pattern: Sharing one warehouse between ingestion and BI to "save credits". Ingestion bursts evict the BI cache on every micro-batch, and BI's concurrency holds ingest's COPY INTO statements in queue. The credit savings are illusory because both workloads run longer.

    πŸ’‘ Exam Trap: Multi-cluster warehouses scale out (add clusters) for concurrency, not for individual query performance. A single slow query does not run faster on a multi-cluster warehouse; it runs on one cluster. Use a larger warehouse size for query latency and more clusters for concurrent throughput.

    Decision Anchor

    Choose Query Profile when investigating one specific slow execution and you need the operator-level breakdown. Choose ACCOUNT_USAGE.QUERY_HISTORY when looking at patterns over days or weeks and accepting the 45-minute latency is fine. Choose INFORMATION_SCHEMA.QUERY_HISTORY when investigating something that happened in the last hour and the 7-to-14-day account-scoped retention is acceptable.

    Diagnostic decision flow

    🎯 Scenario: A nightly transform takes 90 minutes on a Large warehouse. Query Profile shows the dominant operator is a HashJoin with 600 GB written to remote storage and a partitions-scanned ratio of 990/1000. The join is exploding because the SCD-2 dimension join is missing the end-date predicate, and the spill follows from the blown-up intermediate. Fix the join predicate first; only then evaluate whether the warehouse size still needs to change.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Core learning hub.