Sub topic 12
Using query history and the query profile
This chapter assumes you can write basic SQL, run queries in the SQL editor, and use three-level Unity Catalog names (catalog.schema.table). It also assumes you know what a SQL warehouse is. You will learn how to find a past query, read its summary, and use the query profile to see which step made it slow.
Why look at a query after it runs
A query that returns the right rows can still be slow or expensive. The result grid tells you nothing about why. Databricks records every statement that runs on a SQL warehouse and keeps timing and data-volume details for it. Two tools expose those records:
- Query history is a list of past statements, with who ran them, where, when, and how long they took.
- Query profile is a per-query view that breaks one execution into operators (scan, filter, join, aggregate) with time, rows, and memory for each.
Use history to find the query worth investigating. Use the profile to find out why it is slow.
Query history
Open Query History from the sidebar. Each row is one statement execution. A row typically shows:
- The statement text (shortened).
- The status: running, finished, failed, or canceled.
- The start time and total duration.
- The user who ran it.
- The warehouse it ran on.
- The rows returned.
Filtering
A busy workspace produces thousands of rows, so filter first. You can narrow the list by:
- User
- Warehouse
- Status
- Time range
- Statement ID
- Statement text, by searching for a fragment of SQL
Permissions affect what you see. Without extra rights you normally see only your own queries. Users with Can Manage permission on a warehouse can see all queries that ran on it. Workspace admins can see all queries.
What a history entry tells you
Click a row to open its details. The panel splits the total time into stages. The exact labels change between releases, but the idea is stable:
| Part of the time | Meaning |
|---|---|
| Scheduling or waiting for compute | The query waited for the warehouse to start or for a free slot. |
| Planning (optimizing and compiling) | The engine read table metadata and built a plan. |
| Executing | The cluster ran the plan. |
| Fetching results | The client downloaded the result. |
This split is the first diagnostic. A query that spent most of its time waiting did not have a bad plan. The warehouse was starting, or it was saturated by other queries. A query that spent most of its time executing is a candidate for the profile.
The details also show metrics such as rows read, bytes read, bytes spilled to disk, and bytes read from cache. Watch for a large gap between rows read and rows returned. That gap means the engine scanned much more data than the query needed.
Opening the query profile
From a history entry, choose See query profile. You can also open it from the result area of the editor after a query finishes. The profile exists only for queries that ran, so it complements EXPLAIN, which shows a plan without running anything.
The profile has two main views:
- Tree view shows operators as a graph, with data flowing from the scans at the bottom to the final result at the top.
- Graph view is a flatter layout of the same operators. It is useful for wide plans.
A summary panel lists total wall-clock time, time spent in tasks, rows and bytes read, and spill figures.
Reading the operator tree
Each node in the tree is an operator. Common ones:
| Operator | What it does |
|---|---|
| Scan | Reads files from a table. |
| Filter | Drops rows that do not match a condition. |
| Join | Combines two inputs. |
| Aggregate | Computes `GROUP BY` results. |
| Sort | Orders rows. |
| Exchange (shuffle) | Moves rows between workers so related rows meet. |
Each node shows time spent, rows produced, and sometimes peak memory. Nodes that take a large share of total task time are highlighted. Start there.
The following diagram shows the order of questions to ask when reading a profile.
A worked example
Run the aggregation from the editor on the sample taxi data:
SELECT
pickup_zip,
COUNT(*) AS trips,
ROUND(AVG(fare_amount), 2) AS avg_fare
FROM samples.nyctaxi.trips
GROUP BY pickup_zip
ORDER BY trips DESC
LIMIT 20;After it finishes, open the query profile and read it from the bottom up.
- Scan. Note how many rows and bytes the scan read. The query uses only three columns (
pickup_zipandfare_amount, plus the count), so a columnar format reads only those columns. If the scan shows many more columns than you need, you probably usedSELECT *somewhere. - Aggregate. The engine computes partial counts and averages on each worker, then combines them. The row count drops sharply here, from every trip to one row per zip code.
- Exchange. Partial results move between workers so each zip code is finished in one place. This step is normal for a
GROUP BY. - Sort and limit. Only the top 20 rows need ordering, so the engine can keep a small top-N list and avoid a full sort.
On this small sample table, no step should dominate. The point is to learn what a healthy profile looks like before you meet an unhealthy one.
Comparing with EXPLAIN
You can see the planned operators before running anything:
EXPLAIN
SELECT pickup_zip, COUNT(*) AS trips
FROM samples.nyctaxi.trips
GROUP BY pickup_zip;EXPLAIN shows what the engine intends to do. The profile shows what happened: actual row counts, time, and spill. When the two disagree, for example when a planned join is much larger than expected, the actual numbers in the profile are the ones to trust.
Common patterns and what they mean
The scan reads far more than it returns
If a filter node discards 99 percent of the scanned rows, the filter is being applied after the data was read. Check whether the filter is on a column that the table is organized by. Filters on clustering or partition columns let the engine skip files. Filters on unrelated columns do not. Select only the columns you need, which reduces bytes read.
One operator dominates the time
A single join or aggregate that holds most of the task time is your main target. Check the input row counts. A join whose output has far more rows than either input usually means the join keys are not unique, which multiplies rows. This is a correctness problem as well as a performance problem.
Spill to disk
Spill means an operator ran out of memory and wrote intermediate data to disk. Large spill figures slow a query. Fixes include reducing the data entering the operator (filter earlier) or moving to a larger warehouse size, which gives each task more memory.
Long waiting time with a short execution time
This points to the warehouse, not the SQL. The warehouse may have been stopped and had to start, or many queries were competing for the same cluster. Review auto stop settings, the minimum and maximum cluster counts, and the warehouse size from the earlier chapters.
Fast second run
If the same query runs much faster the second time, the result or the data may have come from a cache. History shows bytes read from cache. Do not compare a cold run and a warm run as if they measured the same thing.
Edge cases
- Failed queries. A failed entry still has a message and often a partial profile. Read the error text in the history details first. Many failures, such as a missing table or a permission error, never reach execution.
- Canceled queries. The profile may be incomplete. Operator times reflect only what ran before cancellation.
- Query text is shortened. History may truncate long statements. Open the entry to see the full text.
- Other people's queries. You may be able to see a colleague's profile only if you have the right permissions on the warehouse. Without them the entry does not appear.
- Queries from other clients. Statements sent through the Statement Execution API, dashboards, or BI tools also appear in history, with their source noted. This makes history useful for finding what is loading a shared warehouse.
- Retention. History is kept for a limited time. If you need a long-term record for cost analysis, use the system tables rather than relying on the UI.
A short workflow to remember
- Filter query history to the warehouse and time window of interest.
- Sort by duration and open the slowest entry.
- Read the time split. If waiting dominates, look at warehouse settings.
- If execution dominates, open the profile and find the largest operator.
- Compare rows read with rows returned, and check spill.
- Change one thing, run again, and compare the new profile with the old one.
Exercise
A query in history shows 40 seconds total. The details show 32 seconds waiting for compute and 6 seconds executing. A teammate suggests rewriting the joins. What do you check first, and why?
Show answer
Check the warehouse, not the SQL. Most of the time was spent waiting, so the plan is not the bottleneck. Look at whether the warehouse was stopped and had to start (auto stop and startup time), whether it was queueing queries because it was saturated (cluster count and size), and whether other users were running heavy statements at the same time. Rewriting the joins can save at most part of the 6 seconds of execution.
Exercise
In a query profile, a Scan operator read 500 million rows, and a Filter directly above it passed only 2 million rows. Name two changes that could reduce the work, and say which number in the profile you would check afterward.
Show answer
Select only the columns you need instead of using SELECT *, and filter on a column the table is partitioned or clustered by so the engine can skip files. Afterward, check the rows and bytes read by the Scan operator. They should drop, and the gap between rows read and rows passed by the Filter should shrink.