CertSafari
    Snowflake SnowPro Advanced: Data Engineer (DEA-C02)· Lessons

    Domain 2 · Lesson 8/22

    Troubleshooting slow Snowflake queries with Query History, Query Profile and Query Insights

    Troubleshoot underperforming queries.

    23 min read
    6.33% of exam
    9 sources
    Published 20 Oct 2026
    Docs as of 18 Oct 2026

    What you will be able to do

    • Find the longest-running queries on a warehouse in Snowsight Query History and in ACCOUNT_USAGE.QUERY_HISTORY
    • Choose the telemetry source that fits a slow operation: query, warehouse, task or single operator
    • Split a query's elapsed time into compilation, queuing and execution and say what each part points to
    • Use QUERY_HASH and QUERY_PARAMETERIZED_HASH to tell a slow query pattern from a single slow run
    • Read the Query Profile to spot exploding joins, unnecessary UNION, poor pruning and local or remote spilling
    • Use Query Insights to name a known problem and the fix Snowflake suggests for it
    • Read scan, spill and cache columns as efficiency measures and re-measure after each change
    • Choose between rewriting a query and changing the warehouse, based on the evidence

    Key concept

    Evidence before resizing — A slow query is diagnosed from its telemetry. The elapsed-time breakdown shows whether the time went to waiting or to running. If it went to running, the Query Profile shows which operator used it and why. The fix is chosen from that evidence, and rewriting the query usually comes before buying a bigger warehouse.

    1.Finding the slow queries

    Troubleshooting starts with a list of candidates. A complaint that "the warehouse is slow" rarely names a query, so the first job is to rank the queries by how long they ran. In Snowsight, go to Monitoring » Query History and sort by the Duration column. The longest runs rise to the top. To narrow the list, use the User drop-down for one person's queries, or Filters » Warehouse for everything that ran on one warehouse.

    Your role decides what the page shows. You can always see your own queries. ACCOUNTADMIN sees all query history for the account. A role with MONITOR or OPERATE on a warehouse sees other users' queries on that warehouse. The page also has a time limit: it covers the last 14 days. Details for queries older than seven days do not include User information.

    For anything older, query the QUERY_HISTORY view in the ACCOUNT_USAGE schema, which keeps 365 days of history. The Information Schema QUERY_HISTORY table function covers only the past 7 days. The view can lag by up to 45 minutes, so check a query you just ran in Snowsight instead. The query below lists the 50 longest-running queries on one warehouse in the last day, with their partition counts next to the elapsed time.

    Top 50 longest-running queries on a warehouse in the last day, from ACCOUNT_USAGE.QUERY_HISTORYsql
    SELECT query_id,
      ROW_NUMBER() OVER(ORDER BY partitions_scanned DESC) AS query_id_int,
      query_text,
      total_elapsed_time/1000 AS query_execution_time_seconds,
      partitions_scanned,
      partitions_total,
    FROM snowflake.account_usage.query_history Q
    WHERE warehouse_name = 'my_warehouse' AND TO_DATE(Q.start_time) > DATEADD(day,-1,TO_DATE(CURRENT_TIMESTAMP()))
      AND total_elapsed_time > 0 --only get queries that actually used compute
      AND error_code IS NULL
      AND partitions_scanned IS NOT NULL
    ORDER BY total_elapsed_time desc
    LIMIT 50;

    Telemetry is the record a slow operation leaves behind, and it lives in several places that differ in scope, depth and delay. Picking the right one saves a round of guessing. A query's own history answers "how long, and on what"; the warehouse's load answers "was it crowded"; the operator statistics answer "where inside the plan". Five sources cover the ground:

    • **Query History and ACCOUNT_USAGE.QUERY_HISTORY**: one row per query, with elapsed time, queue time, partitions scanned and spill volumes.
    • **WAREHOUSE_LOAD_HISTORY**: running and queued load per warehouse, with up to 3 hours of latency.
    • **TASK_HISTORY**: how long each task run took, kept for 365 days; sorting succeeded runs by duration shows which task SQL is worth optimizing.
    • **Query Profile and GET_QUERY_OPERATOR_STATS**: statistics per operator, for completed queries from the past 14 days, with OPERATE or MONITOR on the warehouse.
    • **EXPLAIN**: the logical plan without running the query, so it needs no running warehouse, and it reports partitionsAssigned against partitionsTotal.

    The same rows double as efficiency measures. A scan with partitions_scanned close to partitions_total read far more than it needed, so a tighter filter or better data organization is the lever. Non-zero bytes_spilled_to_local_storage or bytes_spilled_to_remote_storage means the operator outgrew warehouse memory. A low percentage_scanned_from_cache means the data came from storage, not the warehouse's local disk cache. Each reading names a different change, so make one, rerun the query, and compare the same columns before touching anything else.

    Checkpoint 1 of 9· Fill the gap

    This query should list the 50 longest-running queries on a warehouse in the last day. Which column completes the ORDER BY clause?

    SELECT query_id,
      ROW_NUMBER() OVER(ORDER BY partitions_scanned DESC) AS query_id_int,
      query_text,
      total_elapsed_time/1000 AS query_execution_time_seconds,
      partitions_scanned,
      partitions_total,
    FROM snowflake.account_usage.query_history Q
    WHERE warehouse_name = 'my_warehouse' AND TO_DATE(Q.start_time) > DATEADD(day,-1,TO_DATE(CURRENT_TIMESTAMP()))
      AND total_elapsed_time > 0 --only get queries that actually used compute
      AND error_code IS NULL
      AND partitions_scanned IS NOT NULL
    ORDER BY  ?  desc
    LIMIT 50;

    Sources12345

    2.Reading where the elapsed time went

    Total elapsed time combines several kinds of time, and each kind has a different fix. QUERY_HISTORY records them in separate millisecond columns. Before you open an execution plan, check whether the query spent its time running or waiting. A query that waited in a queue for four minutes and then ran for ten seconds has no SQL problem worth tuning.

    Elapsed-time columns in QUERY_HISTORY and what each one points to
    ColumnWhat it measuresWhere to look next
    compilation_timeTime to compile the statementThe statement itself, before any warehouse work
    execution_timeTime the warehouse spent running the queryThe Query Profile, to find the expensive operator
    queued_overload_timeTime in the warehouse queue because the current workload overloaded the warehouseWarehouse concurrency, not the SQL
    queued_provisioning_timeTime waiting for compute to provision because of warehouse creation, resume, or resizeWarehouse state, such as a resume from suspended
    queued_repair_timeTime waiting for compute resources in the warehouse to be repairedThe warehouse, not the query
    transaction_blocked_timeTime blocked by a concurrent DMLOther statements writing to the same data

    Overload queuing is a separate case. A high queued_overload_time means other queries were using the warehouse's capacity, and the problem shows up across many queries at once. In Snowsight, the Warehouse Activity chart under Compute » Warehouses shows whether queries were queued. In SQL, WAREHOUSE_LOAD_HISTORY reports the same as avg_queued_load alongside avg_running. Only when execution_time is the large part of the total is the query's own plan the place to look.

    Checkpoint 2 of 9· Check yourself

    A nightly report took five minutes. Its QUERY_HISTORY row shows execution_time of about 12 seconds. Nearly all the rest is queued_overload_time, and other queries on the same warehouse slowed down at the same time. What should you investigate next?

    Sources31

    3.Telling recurring slowness from a one-off with query hashes

    A single slow run and a slow pattern need different responses. One slow execution of a query that is usually fast often means it met contention, a resuming warehouse, or a blocking transaction. A query that is slow every time has a problem in its plan. A cheap query that runs thousands of times a day can also cost more in total than one expensive report. QUERY_HISTORY gives you two columns for grouping executions: query_hash is computed from the canonicalized SQL text, and query_parameterized_hash is computed from the parameterized query.

    The two hashes differ in how much variation they ignore. query_hash groups runs whose SQL text is the same once whitespace and identifier case are set aside, so changing a literal value gives a different hash. query_parameterized_hash goes further and replaces literals with parameters before hashing. SELECT * FROM table1 WHERE table1.name = 'TIM' and the same statement with 'AIHUA' therefore share one parameterized hash. Use query_hash to rank exact statements, and query_parameterized_hash to follow one query shape over time when a dashboard or job keeps changing its filter values. The parameterized hash only collapses literals that sit in an equal, not-equal, greater-than or less-than comparison, and the aliases must match.

    Grouping by query_hash turns a list of runs into a list of patterns. The query below counts executions of each pattern over seven days and ranks the patterns by total elapsed time. Repeated queries that are cheap one at a time but costly in total rise to the top.

    Rank query patterns on a warehouse by total elapsed time over the last 7 dayssql
    SELECT
        query_hash,
        COUNT(*),
        SUM(total_elapsed_time),
        ANY_VALUE(query_id)
      FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
      WHERE warehouse_name = 'MY_WAREHOUSE'
        AND DATE_TRUNC('day', start_time) >= CURRENT_DATE() - 7
      GROUP BY query_hash
      ORDER BY SUM(total_elapsed_time) DESC
      LIMIT 100;

    To see whether a pattern is consistently slow, filter on its query_parameterized_hash and compute the daily average elapsed time. A flat line that is high every day means the pattern itself is slow. A flat line with one bad day means that run was an outlier, and the time breakdown of that run is where to look. The same daily series also tells you whether a later rewrite actually helped.

    Daily average elapsed time for one parameterized query hash over 30 dayssql
    SELECT
        DATE_TRUNC('day', start_time),
        AVG(total_elapsed_time),
        ANY_VALUE(query_id)
      FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
      WHERE query_parameterized_hash = 'cbd58379a88c37ed6cc0ecfebb053b03'
        AND DATE_TRUNC('day', start_time) >= CURRENT_DATE() - 30
      GROUP BY DATE_TRUNC('day', start_time);

    Checkpoint 3 of 9· Check yourself

    Credits on a warehouse keep climbing, but no single query on it ran longer than a few seconds last week. Which approach is most likely to find the workload that is using the time?

    Sources361

    4.Finding the root cause in the Query Profile

    The Query Profile shows the plan the query actually ran, as a tree of operators with statistics. To open it, go to Monitoring » Query History, select the query ID, and open the Query Profile tab. Start with the Most Expensive Nodes pane. It lists the operators that took the longest, so you work on the biggest contributors first instead of reading the whole tree. You can drill into any node to see what percentage of its time went to each category of processing. For scripted analysis, GET_QUERY_OPERATOR_STATS returns the same statistics programmatically. Four causes account for most of what you will find.

    Exploding joins. A join with no condition produces a Cartesian product. A join on a condition where one row matches many rows on the other side also multiplies rows. In both cases, the Join operator produces many more rows than it receives, often by orders of magnitude, and it usually also uses a lot of time. Compare the operator's output row count with its inputs. The fix is in the SQL: add or correct the join condition.

    UNION where UNION ALL would do. UNION ALL just concatenates its inputs. UNION does the same and then removes duplicates. The profile shows this as a UnionAll operator with an extra Aggregate operator on top. If the inputs cannot overlap, that Aggregate does no useful work, and switching to UNION ALL removes it.

    Poor pruning. For a TableScan, compare partitions scanned with partitions total. The total is all micro-partitions of the tables in the query. When the two numbers are nearly equal, the filter did not exclude any data and the scan read almost the whole table. The Micro-partitions and pruning lesson explains why a filter does or does not prune. The profile's job is to show that pruning failed, and on which table.

    Spilling. When a warehouse runs out of memory while running a query, the overflow is written to local disk, and performance drops sharply. That shows up as bytes spilled to local storage. If the query needs even more memory, it spills to remote cloud storage, which is slower still. Local spilling alone means an operator's intermediate result was larger than the memory available. A larger warehouse adds memory and local storage, and that is the direct fix. Remote spilling is the more serious signal. If it continues after a resize, the intermediate data is too large for a resize to absorb. Make the input to the spilling operator smaller: filter it earlier, or process the data in batches.

    These causes often appear together. An exploding join produces a huge intermediate row set, and the operator downstream then spills that row set. Fix the join first. Fewer rows leave less data to spill, and a bigger warehouse would only have spent more credits holding rows that should never have existed.

    Query Profile symptoms and the first fix for each
    Root causeWhat the profile showsFirst fix
    Exploding joinJoin operator outputs far more rows than it consumes, and often takes much of the timeAdd or correct the join condition
    UNION instead of UNION ALLUnionAll operator with an extra Aggregate on topUse UNION ALL when the inputs cannot overlap
    Poor pruningPartitions scanned close to partitions total on a TableScanMake the filter more selective
    Local spillingBytes spilled to local storageA larger warehouse for more memory
    Remote spillingBytes spilled to remote storageShrink the operator's input or batch the work, then resize if needed

    Checkpoint 4 of 9· Match them up

    Match each Query Profile symptom to the first fix you should try.

    Tap a term, then the definition that fits it.

    Checkpoint 5 of 9· Exam question

    A data engineer opens the Query Profile for a report query that took 40 seconds and wants to focus tuning effort where it will matter most. Which panel should they check first to find which operators consumed the largest share of execution time?

    Checkpoint 6 of 9· Exam question

    A nightly transformation query is taking far longer than usual, and the Query Profile Statistics pane shows a large value for 'Bytes spilled to local storage' with none spilled to remote storage. What does this indicate, and what is the most direct fix?

    Checkpoint 7 of 9· Exam question

    During a performance review, a query's Query Profile shows a very large value for 'Bytes spilled to remote storage,' and the query still runs slowly even after moving it to a next-size-up warehouse. What should the data engineer conclude and try next?

    Sources1237

    5.Letting Query Insights name the problem

    Query Insights does part of this diagnosis for you. When Snowflake detects a condition that affects performance, it records an insight. The insight explains the condition, identifies the part of the query that caused it, and suggests a next step. In the Query Profile tab, nodes with insights are highlighted, and the Query Insights pane lists each one. Select View on an entry to see its details and recommendation. The same data is available in SQL from the QUERY_INSIGHTS view, grouped by INSIGHT_TOPIC.

    Query insights that match the root causes above, with Snowflake's suggested fix
    InsightCondition detectedSuggested fix
    Join with no join conditionA cross join that returns every possible combination of rowsSpecify one or more join conditions
    Exploding join (not nested)A join returns many more rows than the joined tables containAdd or change the join condition, or add a WHERE clause to a subquery the join uses
    Unnecessary UNION [ DISTINCT ] clauseThe input sets are disjointUse UNION ALL
    Unnecessary aggregationDISTINCT or GROUP BY returns the same rows as without itRemove the clause
    No filter on table scanNo WHERE clause, so the whole table is scannedAdd a WHERE clause
    LIKE filter with leading wildcardA pattern starting with a wildcard scans a lot of dataAvoid the leading wildcard, or consider search optimization
    Remote spillageThe query scanned more data than the warehouse could holdUse a larger warehouse, or process smaller batches
    Query was in the queue for the warehouse for too longLong wait in the warehouse queueUse a larger warehouse, or one with fewer concurrent queries

    Some insights report good news. Messages such as "Filter uses clustering key" or "Query benefited from search optimization" confirm that an optimization worked. If an insight is missing, that does not prove the query is healthy. Insights are produced only for SQL queries against databases that a warehouse processes. They are not produced for queries that reuse results, queries involving secure objects, queries against hybrid tables, EXPLAIN queries, or queries whose plan takes multiple steps. A query answered from the result cache will never show one. In those cases, read the profile yourself.

    Checkpoint 8 of 9· Match them up

    Each insight below appeared in a query's Query Insights pane. Match each one to the next step Snowflake suggests for it.

    Tap a term, then the definition that fits it.

    Sources8

    6.Fixing the query before resizing the warehouse

    Matching the fix to the evidence keeps costs down. Exploding joins, unnecessary UNION or DISTINCT, and unselective filters are defects in the SQL. A bigger warehouse makes them run faster at a higher cost per hour, and the defect stays. Rewrite these first. Warehouse changes are for problems a rewrite cannot remove. After every change, rerun the query and compare its execution time, or watch its parameterized-hash trend, to confirm the change helped.

    Two kinds of evidence point at the warehouse, and they point in different directions. As a recap of Warehouse sizing: scale up vs scale out (multi-cluster): scaling up gives each query more compute and memory, and scaling out adds clusters for concurrency. Spilling that remains after the SQL is clean is evidence for a larger warehouse, because the data no longer fits in memory. High overload queuing is evidence of concurrency pressure. For that, the fix is more clusters or fewer concurrent queries on the warehouse, because a single query did not run out of memory. The spill query below finds the worst spilling queries of the last 45 days, so you can decide which ones need a rewrite and which need more memory.

    Top 10 queries by bytes spilled to local and remote storage over 45 dayssql
    SELECT query_id, SUBSTR(query_text, 1, 50) partial_query_text, user_name, warehouse_name,
      bytes_spilled_to_local_storage, bytes_spilled_to_remote_storage
    FROM  snowflake.account_usage.query_history
    WHERE (bytes_spilled_to_local_storage > 0
      OR  bytes_spilled_to_remote_storage > 0 )
      AND start_time::date > dateadd('days', -45, current_date)
    ORDER BY bytes_spilled_to_remote_storage, bytes_spilled_to_local_storage DESC
    LIMIT 10;

    Checkpoint 9 of 9· Check yourself

    Your manager wants to move a slow dashboard query from a Medium to a Large warehouse. In its Query Profile, a Join outputs about 40 times more rows than it receives, and the Aggregate after it spills to local storage. What should you do first?

    Sources98

    Practise it for real

    Find your warehouse's most expensive query pattern and diagnose it from its telemetry

    1. 1.Run the query_hash ranking query against ACCOUNT_USAGE.QUERY_HISTORY, with MY_WAREHOUSE replaced by your warehouse name.

      Why: It ranks query patterns by total elapsed time, not single runs, so repeated queries are counted at their full cost.

      You should see: Up to 100 rows, each with a query_hash, an execution count, a summed elapsed time and a sample query_id.

    2. 2.For the top pattern, look up the query_parameterized_hash of its sample query_id, then run the 30-day daily-average query with that hash.

      Why: A steady daily average means the pattern is slow every time. One spike means a single run was an outlier.

      You should see: One row per day with the average total_elapsed_time.

    3. 3.In Snowsight, open Monitoring » Query History, select the sample query ID, and open the Query Profile tab.

      Why: The Most Expensive Nodes pane shows which operator took the time, and the Query Insights pane shows any known condition Snowflake detected.

      You should see: A ranked list of operators, and possibly highlighted nodes with insights.

    4. 4.Check the expensive operator for rows multiplying at a Join, an Aggregate above a UnionAll, partitions scanned close to the total, or bytes spilled.

      Why: Each symptom has a different fix, and rewriting the SQL comes before resizing the warehouse.

      You should see: A named root cause and the fix you will try first.

    Stuck? Get a nudge

    If the time breakdown shows mostly queued time, stop here. The warehouse is the bottleneck, not this query.

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Use the Duration column to understand how long it took a query to execute.”
      ↩︎ Finding the slow queries
      “Be aware that the ACCOUNT_USAGE views are not updated immediately after running a query or task.”
      ↩︎ Finding the slow queries
      “which can indicate an opportunity to optimize the SQL being executed by the task.”
      ↩︎ Finding the slow queries
      “Use the Warehouse Activity chart to visualize the load of the warehouse, including whether queries were queued.”
      ↩︎ Reading where the elapsed time went
      “although a query might not be excessively expensive during any single execution, a frequently repeated query could lead to high costs”
      ↩︎ Telling recurring slowness from a one-off with query hashes
      “It includes a Most Expensive Nodes pane that identifies the operator nodes that are taking the longest to execute.”
      ↩︎ Finding the root cause in the Query Profile
      “You can programmatically access the performance statistics of the Query Profile by executing the GET_QUERY_OPERATOR_STATS function.”
      ↩︎ Finding the root cause in the Query Profile
      “It includes a Most Expensive Nodes pane that identifies the operator nodes that are taking the longest to execute.”
      ↩︎ Key concept
      “a frequently repeated query could lead to high costs, based on the number of times the query runs”
      ↩︎ Checkpoint
    2. 2.
      “The Query History page lets you explore queries executed in your Snowflake account over the last 14 days.”
      ↩︎ Finding the slow queries
      “The efficiency of pruning can be observed by comparing Partitions scanned and Partitions total statistics in the TableScan operators.”
      ↩︎ Finding the slow queries
      “the Join operator produces significantly (often by orders of magnitude) more tuples than it consumes.”
      ↩︎ Finding the root cause in the Query Profile
      “UNION ALL simply concatenates inputs, while UNION does the same, but also performs duplicate elimination.”
      ↩︎ Finding the root cause in the Query Profile
      “The Query History page lets you explore queries executed in your Snowflake account over the last 14 days.”
      ↩︎ Exam trap 2
      “These queries show in Query Profile as a UnionAll operator with an extra Aggregate operator on top (which performs duplicate elimination).”
      ↩︎ Exam trap 3
    3. 3.
      “the table function restricts the results to activity over the past 7 days, versus 365 days for the Account Usage view”
      ↩︎ Finding the slow queries
      “Time (in milliseconds) spent in the warehouse queue, waiting for the warehouse compute resources to provision, due to warehouse creation, resume, or resize.”
      ↩︎ Reading where the elapsed time went
      “Time (in milliseconds) spent in the warehouse queue, due to the warehouse being overloaded by the current query workload.”
      ↩︎ Reading where the elapsed time went
      “The hash value computed based on the canonicalized SQL text.”
      ↩︎ Telling recurring slowness from a one-off with query hashes
      “Total micro-partitions of all tables included in this query.”
      ↩︎ Finding the root cause in the Query Profile
      “Time (in milliseconds) spent in the warehouse queue, due to the warehouse being overloaded by the current query workload.”
      ↩︎ Exam trap 5
    4. 4.
      “EXPLAIN compiles the SQL statement, but does not execute it, so EXPLAIN does not require a running warehouse.”
      ↩︎ Finding the slow queries
    5. 5.
      “You can run this function for any completed query that was executed in the past 14 days.”
      ↩︎ Finding the slow queries
    6. 6.
      “which means the version of the query after parameterizing all literals.”
      ↩︎ Telling recurring slowness from a one-off with query hashes
      “the following queries have the same QUERY_PARAMETERIZED_HASH value”
      ↩︎ Telling recurring slowness from a one-off with query hashes
    7. 7.
      “If the query requires even more memory, it spills onto remote cloud-provider storage, which results in even worse performance.”
      ↩︎ Finding the root cause in the Query Profile
      “Using a larger warehouse (effectively increasing the available memory/local storage space for the operation)”
      ↩︎ Finding the root cause in the Query Profile
      “Performance degrades drastically when a warehouse runs out of memory while executing a query because memory bytes must “spill” onto local disk storage.”
      ↩︎ Exam trap 1
    8. 8.
      “Each insight includes a message that explains how query performance might be affected and provides a general recommendation for improving performance.”
      ↩︎ Letting Query Insights name the problem
      “In Query Profile tab under Query History, you can view the insights for a query. The nodes that have corresponding insights are highlighted.”
      ↩︎ Letting Query Insights name the problem
      “The UNION [ DISTINCT ] clause isn’t necessary because the input sets are disjoint.”
      ↩︎ Letting Query Insights name the problem
      “The join is missing the join condition. The result is a cross join, which returns every possible combination of rows.”
      ↩︎ Letting Query Insights name the problem
      “use a larger warehouse that has more capacity, or use a warehouse that has fewer concurrent queries.”
      ↩︎ Fixing the query before resizing the warehouse
      “This query scanned more data than the warehouse had capacity to store.”
      ↩︎ Fixing the query before resizing the warehouse
      “Queries that reuse results.”
      ↩︎ Exam trap 4
      “If using a larger warehouse is not an option, change the query to process data in smaller batches.”
      ↩︎ Prediction
      “larger warehouse that has more capacity. If using a larger warehouse is not an option, change the query to process data in smaller batches”
      ↩︎ Checkpoint
      “To avoid this problem, use a larger warehouse that has more capacity, or use a warehouse that has fewer concurrent queries.”
      ↩︎ Checkpoint
      “To prevent the join from producing more rows than are in the tables being joined, add or change the join condition.”
      ↩︎ Checkpoint
    9. 9.
      “they can test the change by re-running the query and checking its execution time.”
      ↩︎ Fixing the query before resizing the warehouse

    Ready to test yourself?

    Practise the 24 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.