Sub topic 13
Performance and caching basics
This chapter explains what makes a query on a SQL warehouse fast or slow, and how the caching layers work. It assumes you can run queries in the SQL editor, know the three-level catalog.schema.table naming, and have opened the query profile at least once. You should also know how warehouse size and auto stop affect cost.
Where query time goes
A query's runtime is mostly the sum of four things:
- Startup. A stopped warehouse must start before it can run anything. Serverless warehouses start in seconds. Pro and classic warehouses take longer.
- Reading data. Scanning files from cloud object storage is usually the largest cost.
- Computing. Joins, aggregations, and sorts use the cluster's CPU and memory.
- Returning results. Large result sets take time to transfer to the editor or client.
Caching mostly helps with the second item, and sometimes removes the second and third entirely. Table layout also reduces the amount of data read. Warehouse size helps with the third.
SQL warehouses run the Photon engine, a vectorized query engine, so you do not enable it yourself. Your levers are caching, table layout, query shape, and warehouse size.
The caching layers
Databricks SQL uses more than one cache. They differ in what they store and how long it lasts.
| Cache | What it stores | Scope | Lifetime |
|---|---|---|---|
| Result cache | Final results of a completed query | Per warehouse cluster (local). Serverless also keeps a remote copy. | Until the data changes, the warehouse restarts (local copy), or the entry expires |
| Disk cache | Copies of data files read from cloud storage, on local SSDs | Per cluster | Until the cluster stops or the cache evicts the files |
| UI and dashboard cache | Results already shown in the editor or a dashboard | Per user session or dashboard | Short-lived |
Result cache
If you run the same query text again and the underlying data has not changed, the warehouse can return the stored result without scanning anything. This is the fastest outcome, and it uses almost no compute.
Several things stop a result from being reused:
- The table data changed (Delta table versions differ).
- The query contains a non-deterministic function such as
rand()orcurrent_timestamp(). - The query text differs, including a different parameter value.
- The user lacks permission on the tables. Permissions are checked before a cached result is returned.
- The cache entry aged out. Serverless warehouses keep a remote result cache that survives a warehouse restart. Local copies on pro and classic warehouses are lost when the warehouse stops.
Disk cache
When a query reads Parquet files from cloud storage, the warehouse keeps copies on the cluster's local SSDs. A later query that needs the same files reads them locally. Unlike the result cache, this helps queries that differ. Two different aggregations over the same table can share the cached files.
The disk cache is automatic on SQL warehouses. You do not configure it, and you should not try to manage it with CACHE TABLE statements.
Because the cache lives on the cluster, it starts empty after a warehouse starts. The first queries after a cold start are slower. If your workload is bursty and the warehouse stops between bursts, you will often pay this "cold cache" cost. A longer auto stop delay keeps the cache warm but costs more running time.
Seeing the caches work
Run this query twice in the SQL editor and compare the durations.
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;The second run is usually much faster, because the result cache can answer it. Now change the query so it cannot use the result cache.
SELECT
pickup_zip,
COUNT(*) AS trips,
ROUND(AVG(fare_amount), 2) AS avg_fare,
rand() AS noise
FROM samples.nyctaxi.trips
GROUP BY pickup_zip
ORDER BY trips DESC
LIMIT 20;The rand() call makes the result non-deterministic, so each run must execute. Compare the second run of this query with the second run of the first one. The gap shows how much the result cache contributes. The remaining speedup over the very first run comes from the disk cache.
To confirm which path a query took, open it in query history and then open its query profile. The profile reports whether the result came from cache and, for the scan, how much data was read from cache versus remote storage. The exact labels change between releases, so look for cache-related entries in the scan node details.
Reading less data
Caches help repeat reads. The cheapest read is the one you skip. Delta tables store file-level statistics, such as minimum and maximum values per column, and the engine uses them to skip files that cannot match a filter. This is called data skipping or file pruning.
Write filters that can prune
- Filter on columns directly.
WHERE pickup_zip = 10103can prune files. Wrapping the column in a function, as inWHERE CAST(pickup_zip AS STRING) = '10103', often prevents pruning. - Select only the columns you need instead of
SELECT *. Parquet is columnar, so unused columns are never read. - Add
LIMITwhen exploring. It reduces the work for the editor, though it does not help a query that must sort or aggregate everything first.
Organize the table
Pruning only works when similar values sit in the same files. Liquid clustering lays out data by the columns you choose, so filters on those columns skip more files. The shared sample table is read-only, so this example copies it into a table you own. Replace main.default with a catalog and schema where you have CREATE TABLE permission.
CREATE TABLE IF NOT EXISTS main.default.trips_clustered
CLUSTER BY (pickup_zip)
AS SELECT * FROM samples.nyctaxi.trips;
OPTIMIZE main.default.trips_clustered;
SELECT COUNT(*) AS trips, ROUND(AVG(fare_amount), 2) AS avg_fare
FROM main.default.trips_clustered
WHERE pickup_zip = 10103;Look at the scan node in the query profile for this query. A well-clustered table shows a high count of files pruned relative to files read. OPTIMIZE also compacts many small files into larger ones, which reduces per-file overhead. For Unity Catalog managed tables, predictive optimization can run maintenance like this automatically if your account has it enabled.
Keep statistics current
The optimizer picks join strategies and join orders using table statistics. Stale or missing statistics can lead to a poor plan, for example a large table broadcast as if it were small. Refresh them after large loads:
ANALYZE TABLE main.default.trips_clustered COMPUTE STATISTICS FOR ALL COLUMNS;Diagnosing a slow query
Work through the causes in order of cost to fix:
- Check the wait. In query history, compare total duration with execution time. A long gap before execution means the warehouse was starting or the query was queued behind others. That points to auto stop settings or scaling, not the query.
- Check the bytes. In the profile, look at bytes read and files read. If they are close to the table's full size and your query has a selective filter, pruning is failing.
- Check for spill. Spilling to disk during a sort or join means the warehouse size is too small for the data, or the query is producing too many rows.
- Check the plan. Run
EXPLAINbefore a long query to see whether filters are pushed down to the scan.
EXPLAIN
SELECT pickup_zip, COUNT(*) AS trips
FROM samples.nyctaxi.trips
GROUP BY pickup_zip;Common mistakes
- Expecting cache hits across different text. Whitespace or parameter changes can make a query a new one. Use query parameters so the saved query keeps the same text.
- Using
CACHE TABLEout of habit. It is a pattern from other Spark clusters. On SQL warehouses the disk cache already does this job. - Over-extending auto stop to keep the cache warm. Compare the cost of the idle minutes against the cold-start penalty for your workload.
- Clustering on too many columns. Pick the one to four columns used most often in filters.
Exercise
A dashboard query filters on WHERE fare_amount > 20 AND tpep_pickup_datetime > current_timestamp() - INTERVAL 7 DAYS. Users complain that it is slow every time it refreshes, even though the data rarely changes. Give two reasons the result cache does not help, and one change that could make the query faster.
Show answer
The result cache cannot help because (1) current_timestamp() is non-deterministic, so the query is not eligible for result reuse, and (2) the evaluated filter value differs on every run. A change that could help is replacing current_timestamp() with a query parameter or a fixed date boundary, which keeps the text stable and lets repeated runs be served from the cache while the data is unchanged. Clustering the table on the date column would also reduce the files read on a cache miss.
Exercise
You run an aggregation on a pro warehouse. It takes 40 seconds after the warehouse restarts and 6 seconds the next time you run a different aggregation over the same table. Which cache explains the speedup, and why is it not the result cache?
Show answer
The disk cache explains it. The first query read the table's files from cloud storage and left copies on the cluster's local SSDs. The second query was different, so the result cache had nothing to return, but the files it needed were already cached locally.