Analytical Query Performance and Optimization Questions
Diagnosing and tuning analytical queries on distributed and warehouse engines. Covers reading and reasoning about query plans, join strategy and ordering including broadcast versus shuffle, statistics and cardinality estimation, materialized views and result caching, skew and spill diagnosis, workload management and concurrency, and the cost side of query performance on engines billed by bytes scanned or compute time. The altitude is the deep, engine-specific operational layer: what a real plan on a real warehouse engine is telling you and what to change. Generic single-engine query-tuning fundamentals, the physical layout of the data being scanned, and the choice of which managed platform to run on are covered separately.
Compare ETL and ELT specifically for a cloud data warehouse: where does transformation happen in each, and how does that choice affect downstream query performance and compute cost (not just pipeline architecture)? Why have modern cloud warehouses pushed many teams toward ELT?
Sample Answer
Compare ETL and ELT specifically on where the transformation compute happens and who pays for it, since that is what actually drives downstream query performance and cost, not just a naming difference.
Where transformation happens
In ETL, data is transformed in a separate processing layer (a dedicated ETL tool or compute cluster) before it lands in the warehouse, so the warehouse only ever stores already-clean, already-shaped data. In ELT, raw data is loaded into the warehouse first, and transformation happens inside the warehouse using its own compute, typically via SQL (often orchestrated by a tool like dbt).
Effect on query performance and cost
ELT means transformation work competes for the same warehouse compute that serves ad-hoc and dashboard queries, so a heavy nightly ELT transformation run can directly degrade interactive query latency during that window unless workload isolation (routing the transformation job to its own separate compute pool) is in place. ETL keeps that transformation load off the warehouse entirely, at the cost of running and maintaining a separate transformation system. On the cost side, ELT's transformation cost is warehouse compute (usually billed per query or per second of warehouse time), which is easy to see and attribute per transformation, while ETL's transformation cost lives in a separate system's compute budget, which can be cheaper or more expensive depending on that system, but is a genuinely separate cost line to manage.
Why cloud warehouses pushed teams toward ELT
Modern cloud warehouses decouple storage from compute and can scale compute elastically, which removes the traditional reason to do transformation somewhere else first: warehouse compute used to be a fixed, expensive, hard-to-scale resource you wanted to protect from heavy transformation jobs, but an elastically scalable warehouse can absorb that load (in its own dedicated pool) without permanently starving other workloads. Combined with SQL-based transformation tooling becoming mature and version-controllable, ELT collapsed the operational reason to maintain a separate ETL system for many teams.
Trade-offs and pitfalls
ELT is not free of the workload-isolation problem, it just moves the isolation decision inside the warehouse (a dedicated transformation compute pool) rather than outside it (a separate ETL cluster); teams that adopt ELT without also isolating transformation compute from serving compute reproduce the exact resource-contention problem ETL was originally designed to avoid, just inside one platform instead of across two.
Given events(id, user_id, amount, event_time) and a materialized daily_user_totals(date, user_id, total_amount), write SQL (or precise pseudo-SQL) that incrementally updates daily_user_totals for only the dates present in a staging_events table, correctly handling inserts, updates, and deletes idempotently while minimizing locks on the target table.
Sample Answer
Given events(id, user_id, amount, event_time) and a materialized daily_user_totals(date, user_id, total_amount), the incremental update needs to fold only the dates present in staging_events into the existing totals, adding new activity to matching (date, user_id) rows and inserting fresh rows for combinations that do not exist yet, all without holding a lock on the whole target table for longer than necessary.
Approach
- Aggregate
staging_eventsdown to one row per(date, user_id)first, so the merge step only ever has to reconcile one summarized delta row per key, not many raw event rows. - Upsert that delta into
daily_user_totals: insert a new row where the key does not exist, and add the delta's amount onto the existing total where it does. - For deletes (a correction that removes a previously-counted event), apply the negative of that row's amount as a delta in the same way, rather than trying to recompute the whole day from scratch.
Code (executed and verified)
-- fixture: existing totals plus a new staging batch
CREATE TABLE daily_user_totals (date DATE, user_id INT, total_amount DECIMAL(12,2), PRIMARY KEY(date, user_id));
INSERT INTO daily_user_totals VALUES (DATE '2024-01-01', 1, 100.00), (DATE '2024-01-01', 2, 50.00);
CREATE TABLE staging_events (id INT, user_id INT, amount DECIMAL(12,2), event_time TIMESTAMP);
INSERT INTO staging_events VALUES
(100, 1, 25.00, '2024-01-01 10:00:00'),
(101, 3, 40.00, '2024-01-01 11:00:00'),
(102, 1, 5.00, '2024-01-01 12:00:00');
-- 1. summarize new/changed activity to one row per (date, user_id)
CREATE TABLE staging_daily AS
SELECT CAST(event_time AS DATE) AS date, user_id, sum(amount) AS delta_amount
FROM staging_events
GROUP BY 1, 2;
-- 2. upsert the delta into the materialized target
INSERT INTO daily_user_totals (date, user_id, total_amount)
SELECT date, user_id, delta_amount FROM staging_daily
ON CONFLICT (date, user_id)
DO UPDATE SET total_amount = daily_user_totals.total_amount + EXCLUDED.total_amount;
Executed against a target table pre-seeded with (2024-01-01, user 1, 100.00) and (2024-01-01, user 2, 50.00), and a staging batch containing two new events for user 1 (25.00 and 5.00) and one new event for user 3 (40.00): the result was user 1 = 130.00 (100 + 25 + 5, correctly accumulated), user 2 = 50.00 (untouched, as expected since no new activity existed for them), and user 3 = 40.00 (a new row inserted). All three outcomes matched the expected arithmetic exactly.
Handling deletes and idempotency
For a genuine delete of a previously-processed event, apply it as a negative delta through the same staging_daily aggregation path (summing a negative amount for a deleted row) rather than a separate code path, so the merge logic only has one shape to reason about. Concretely, using the fixture above: if event id 100 (user 1, amount = 25.00) later turns out to be a duplicate that needs to be removed, a later staging batch carries a compensating row, (user_id=1, amount=-25.00, event_time='2024-01-01 13:00:00'), rather than deleting anything from staging_events. That row flows through the same step-1 GROUP BY and sum(amount), contributing -25.00 to staging_daily for (2024-01-01, user 1), and the step-2 upsert applies it exactly like any other delta: total_amount = daily_user_totals.total_amount + EXCLUDED.total_amount becomes 130.00 + (-25.00) = 105.00, which is exactly the total user 1 would have had if the erroneous 25.00 event had never been staged (the 100.00 seed plus the remaining 5.00 event). The negative amount is not produced by a special delete code path; it is simply the deleted row's own original amount, sign-flipped, staged like any other event. For idempotency (the same staging batch being replayed, for example after a job retry), the delta must be computed from events not yet applied, not from all events in the staging table unconditionally; track a processed-flag or a watermark on staging_events and only aggregate unprocessed rows, or the same delta will be double-applied on a retry.
Complexity and edge cases
The aggregation step is a single pass over the staging batch, and the upsert is bounded by the number of distinct (date, user_id) pairs touched, not the full target table, so cost scales with the size of the incoming batch rather than the table's total history. Edge cases worth naming explicitly: a staging_events batch that spans more than one date needs the GROUP BY to include date (as written above) so events do not get folded into the wrong day; and a batch containing both an insert and a same-key correction in the same run must net out correctly before the upsert, which the sum(amount) in step 1 already handles since it aggregates all of a key's staged rows together before touching the target.
Trade-offs and pitfalls
A blind INSERT ... ON CONFLICT without first deduplicating and aggregating the staging batch (skipping step 1) would apply each raw event row as its own tiny update, which is both slower (many small writes instead of one aggregated write per key) and more exposed to a partial-batch retry double-applying individual rows rather than one clean delta per key.
You need to choose between an OLAP-cube pre-aggregation layer and ad-hoc SQL directly on a columnar warehouse for business reporting. List the pros and cons of each, and recommend an approach for a product analytics team that needs metrics refreshed roughly every 5 minutes.
Sample Answer
An online-analytical-processing (OLAP) cube pre-computes aggregates across a fixed set of dimension combinations ahead of time, so a query that matches one of those combinations returns instantly from stored results; ad-hoc SQL directly on a columnar warehouse computes the aggregation fresh for whatever combination the query actually asks for, with no pre-computation, at whatever cost that scan and aggregation takes.
Trade-offs
A cube gives predictable, fast latency for the combinations it covers, but its build and refresh cost grows with the number of dimension combinations it materializes, and any query outside its pre-defined combinations either falls back to the raw data (losing the speed benefit) or cannot be answered at all. Ad-hoc SQL on a columnar warehouse has no such coverage limitation, any combination is queryable, but latency and cost scale with data volume and the specific query's selectivity, which can be unpredictable and, for a wide or unfiltered aggregation over a large table, genuinely slow.
Recommendation for metrics refreshed roughly every 5 minutes
For a product analytics team needing metrics updated close to every 5 minutes, a full OLAP cube's refresh cycle is usually too heavy to keep pace at that cadence without significant infrastructure investment, since re-materializing a wide set of dimension combinations every 5 minutes is expensive even on a modern warehouse. Ad-hoc SQL on a well-partitioned and clustered columnar warehouse, backed by a narrow set of the most-queried pre-aggregations (not a full cube) refreshed on that same 5-minute cadence, is usually the more practical fit: it keeps the freshness target achievable, covers unusual filter combinations gracefully by falling back to the raw scan, and avoids committing to a wide cube's storage and refresh overhead before usage patterns are well understood.
When a full cube is still the right call
A cube becomes worth its cost once the query patterns are well understood, largely fixed, and few enough combinations dominate real usage that a much narrower, purpose-built pre-aggregation covers the vast majority of traffic, at which point it behaves like a fast, near-real-time-refreshed answer to a known set of questions rather than a general-purpose ad-hoc layer.
Pitfalls
The common mistake is committing to a full cube before usage patterns are known, which tends to produce a structure that is both expensive to maintain and still misses the queries people actually ask; start with ad-hoc SQL plus targeted pre-aggregation of the highest-traffic combinations, and only formalize into a broader cube once real usage data justifies the investment.
You optimize a query so it now scans 200 GB per run instead of 5 TB. If the warehouse charges $5 per TB scanned and the query runs 100 times a day, estimate the daily and annualized savings. State your assumptions and what could make the real savings differ.
Sample Answer
Cutting a query's scanned bytes from 5TB to 200GB is a 25x reduction, and at $5 per TB scanned, running 100 times a day, that turns a $2,500-per-day query into a $100-per-day query, a savings of $2,400 per day, or roughly $876,000 per year at that same run rate.
The arithmetic
- Before: 5TB x $5/TB x 100 runs/day = $2,500/day
- After: 0.2TB x $5/TB x 100 runs/day = $100/day
- Daily savings: $2,500 - $100 = $2,400/day
- Annualized: $2,400 x 365 = $876,000/year
Assumptions this rests on
- The $5/TB rate and the 100-runs/day frequency are both held constant going forward; if the query's run frequency grows (more users, more automation triggering it) the savings scale up further, and if the organization negotiates a different pricing tier or moves to a flat-rate/reserved-capacity billing model instead of pure pay-per-byte, the whole calculation no longer applies in the same form.
- The 200GB post-optimization figure is itself stable, not a one-time favorable measurement on an unusually small run; verify it against a few different runs (different filter values, different days) before committing to it as the ongoing baseline, since a partition-pruning fix's savings can vary with which partitions a given run's filter actually touches.
- 365 days a year is used as a simple annualization, not accounting for the query possibly running less often on weekends or holidays, which would make the true annual figure somewhat lower than this straight-line estimate.
What could make the real savings differ
If the optimization that reduced bytes scanned also changed the query's results in some subtle way (a stricter filter that silently excludes rows it should include), the "savings" partly reflect doing less work rather than doing the same work more efficiently, which is not a real win and needs to be ruled out by comparing outputs, not just costs, before and after. Separately, if the warehouse has a minimum billing granularity or a base cost per query independent of bytes scanned, the actual per-run savings could be somewhat smaller than the pure bytes-scanned arithmetic suggests, since that fixed cost does not shrink with the optimization.
Explain bucketing (or co-partitioning) in a distributed engine like Hive/Spark/Presto: what it offers beyond partitioning, how it lets two large tables join without a full shuffle when both are bucketed on the join key, and what constraints and ongoing maintenance it requires.
Sample Answer
Bucketing (also called co-partitioning when applied to a join) pre-groups a table's rows into a fixed number of physical buckets based on a hash of a chosen key, and writes each bucket to its own file or file set; this is stronger than ordinary partitioning because partitioning only groups rows by directory for pruning, while bucketing guarantees that all rows sharing a bucket-key value live in the same physical bucket, which a join can exploit directly.
How it enables shuffle-free joins
If two tables are both bucketed into the same number of buckets on the same join key (with the same hash function), then bucket i of table A can only ever match rows in bucket i of table B; no other bucket combination can possibly join. The engine can therefore join bucket i to bucket i independently, worker by worker, without redistributing any data across the network first, because the co-location the shuffle would have produced already exists on disk.
This is the same underlying mechanism Hive, Spark, and Presto/Trino all support, but the terminology is more portable than the hash function is: Hive and Spark both call it bucketing directly, and Presto/Trino recognizes bucketed layouts, but Spark's default bucketing hash (a Murmur3-based hash) is not the same algorithm as Hive's default bucketing hash (Hive 2.x and Hive 3.x each use their own hash), so a table Spark bucketed with its default settings and a table Hive bucketed on the same key do not actually line up bucket-for-bucket even with matching bucket counts. In practice, a cross-engine bucketed join routinely falls back to an extra shuffle and sort for exactly this reason: the tables look identically bucketed (same key, same bucket count) but were written with different default hash functions. Avoiding the shuffle across engines requires explicitly writing one side with a Hive-compatible hash mode (Presto/Trino and newer Spark versions support this), not just matching bucket counts.
Constraints that must hold
- Matching bucket counts between the two tables (or one being an exact multiple of the other, depending on the engine), since the hash-to-bucket mapping only lines up under that condition.
- A compatible, identical hash function used when both tables were written, so bucket i genuinely means the same set of key values on both sides. This is not automatic across engines: Spark's and Hive's default bucketing hashes differ, so a Spark-bucketed table and a Hive-bucketed table on the same key usually need an explicit Hive-compatible write mode before a cross-engine join can actually skip the shuffle.
- The join predicate must be exactly the bucketing key (or a subset the engine can still reason about); joining on a different column gets no benefit and falls back to a normal shuffle join.
Maintenance implications
Bucketing is a write-time decision baked into how the table's files are laid out, so every write path that adds data to either table has to preserve the bucketing scheme (write with the same bucket count and hash function), or later joins silently fall back to shuffling. A table that starts unbucketed, or that gets re-bucketed with a different bucket count as data volume grows, breaks the invariant for any table still joined against the old scheme, so a bucket-count change has to be coordinated across every table sharing that join key, not made unilaterally on one side.
Trade-offs and pitfalls
Bucketing is a strong tool for a join pattern that repeats often against tables that do not change bucket scheme frequently (a fact table repeatedly joined to a dimension on the same key), but it is a poor fit for ad-hoc, exploratory joins on arbitrary columns, since you would need every plausible join key bucketed in advance, which is not realistic. Also watch for bucket skew: if the join key itself is skewed (one value vastly more common than others), bucketing does not fix that, since a hash-based bucket assignment still sends all of that value's rows to one bucket; bucketing and skew mitigation (like salting) address different problems and are sometimes both needed together.
Unlock Full Question Bank
Get access to all 46 Analytical Query Performance and Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.