database_engine
large_stringclasses
8 values
slow_query
large_stringlengths
92
591
execution_plan
large_stringlengths
145
1.86k
diagnostic_thought
large_stringlengths
223
929
remediation_ddl
large_stringlengths
47
481
optimized_query
large_stringlengths
97
733
MariaDB 11.2
SELECT ps.match_id, ps.player_id, AVG(ps.kills) AS average_kills, AVG(ps.score) AS average_score FROM player_stats ps WHERE ps.kills > 10 OR ps.score > 1000 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'EU' AND ms.game_mode = 'Ranked')
{"query_block": {"select_id": 1, "table": {"table_name": "ps", "access_type": "ALL", "rows": 123456, "filtered": 10.0, "attached_condition": "ps.kills > 10 OR ps.score > 1000"}}}
The query planner chose a full table scan on the player_stats table due to the OR condition across unindexed columns kills and score. This is because the optimizer cannot effectively use an index when the condition is not sargable, resulting in a full scan of the table. Additionally, the subquery in the IN clause may a...
CREATE INDEX idx_player_stats_kills_score ON player_stats (kills, score); CREATE INDEX idx_match_sessions_region_game_mode ON match_sessions (region, game_mode);
SELECT ps.match_id, ps.player_id, AVG(ps.kills) AS average_kills, AVG(ps.score) AS average_score FROM player_stats ps USE INDEX (idx_player_stats_kills_score) WHERE ps.kills > 10 OR ps.score > 1000 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms USE INDEX (idx_match_sessions_region_game_mode) WHERE ms.reg...
SQLite 3.45
SELECT le.id, le.account_id, le.posting_date, a.risk_tier FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 1452 AND le.posting_date > '2022-07-01' AND a.balance > 1000.00
EXPLAIN QUERY PLAN SELECT le.id, le.account_id, le.posting_date, a.risk_tier FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 1452 AND le.posting_date > '2022-07-01' AND a.balance > 1000.00; -- output: SCAN TABLE ledger_entries (~20000 rows), SEARCH TABLE accounts USING INTEGER...
The query planner chose a sub-optimal route because it failed to utilize a covering index, instead opting for a full table scan of ledger_entries due to the lack of a composite index on (account_id, posting_date), forcing the database engine to examine every row in the table, resulting in a significant increase in quer...
CREATE INDEX idx_ledger_entries_account_id_posting_date ON ledger_entries (account_id, posting_date);
SELECT le.id, le.account_id, le.posting_date, a.risk_tier FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 1452 AND le.posting_date > '2022-07-01' AND a.balance > 1000.00
PostgreSQL 16.2
WITH ranked_match_stats AS (SELECT ms.match_id, ms.region, ps.player_id, ps.kills, ps.score, ps.ping_ms, ROW_NUMBER() OVER (PARTITION BY ms.match_id ORDER BY ps.score DESC) AS score_rank FROM match_sessions ms JOIN player_stats ps ON ms.match_id = ps.match_id WHERE ms.game_mode = 'Ranked' AND ms.started_at > '2022-01-0...
{"Plan": {"Node Type": "Nested Loop", "Join Type": "Inner", "Detail": " -> Nested Loop (cost=2345.67..3456.78 rows=1234 width=234)"}, "Plans": [{"Node Type": "CTE Scan", "Detail": " -> CTE Scan on ranked_match_stats (cost=1234.56..2345.67 rows=1234 width=234)"}, {"Node Type": "Index Scan", "Detail": " -> Index S...
The query planner chose this sub-optimal route because it failed to push the predicate filters down into the partitioned match_sessions table, due to the presence of the Materialized CTE (WITH clause). As a result, the entire match_sessions table is being scanned, leading to a significant increase in query execution ti...
CREATE INDEX idx_match_sessions_game_mode ON match_sessions (game_mode); CREATE INDEX idx_match_sessions_started_at ON match_sessions (started_at); CREATE INDEX idx_match_sessions_ended_at ON match_sessions (ended_at); ALTER TABLE match_sessions SET (parallel_workers = 4); VACUUM ANALYZE match_sessions;
WITH ranked_match_stats AS (SELECT ms.match_id, ms.region, ps.player_id, ps.kills, ps.score, ps.ping_ms, ROW_NUMBER() OVER (PARTITION BY ms.match_id ORDER BY ps.score DESC) AS score_rank FROM match_sessions ms JOIN player_stats ps ON ms.match_id = ps.match_id WHERE ms.game_mode = 'Ranked' AND ms.started_at > '2022-01-0...
ClickHouse 24.3
SELECT oi.item_id, oi.order_id, oi.sku_id, oi.quantity, oi.unit_price, oi.warehouse_id FROM order_items oi INNER JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE toYear(ist.updated_at) = 2022 AND toMonth(ist.updated_at) = 12 ...
{"type":"Aggregate","inputs":[{"type":"Filter","inputs":[{"type":"Join","inputs":[{"type":"Scan","arguments":{"table":"order_items","columns":["item_id","order_id","sku_id","quantity","unit_price","warehouse_id"]}},{"type":"Scan","arguments":{"table":"inventory_stock","columns":["sku_id","warehouse_id","available_qty",...
The query planner chose this sub-optimal route because the non-SARGable function toYear() and toMonth() wrapping the date column updated_at in the WHERE clause prevented the optimizer from using an index range scan. As a result, the planner had to perform a full table scan on the inventory_stock table, leading to poor ...
CREATE INDEX idx_inventory_stock_updated_at ON inventory_stock (updated_at);
SELECT oi.item_id, oi.order_id, oi.sku_id, oi.quantity, oi.unit_price, oi.warehouse_id FROM order_items oi INNER JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE ist.updated_at >= toDateTime('2022-12-01 00:00:00') AND ist.upd...
PostgreSQL 16.2
SELECT oi.item_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 19.99 AND p.valid_from < '2024-09-16' AND p.valid_until > '2024-09-16' AND i.available_qty...
EXPLAIN (ANALYZE, BUFFERS) SELECT oi.item_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 19.99 AND p.valid_from < '2024-09-16' AND p.valid_until > '2024...
The query planner chose this sub-optimal route because the current index on order_items does not cover the join and filter columns used in the query, resulting in excessive heap fetches on the wide table. The existing index only includes the sku_id column, which is not sufficient to satisfy the query. Furthermore, the ...
CREATE INDEX idx_order_items_sku_warehouse_unit_price ON order_items (sku_id, warehouse_id, unit_price) INCLUDE (item_id, quantity); CREATE INDEX idx_inventory_stock_sku_warehouse_available_qty ON inventory_stock (sku_id, warehouse_id, available_qty); CREATE INDEX idx_promotions_sku_valid_from_valid_until ON promotions...
SELECT oi.item_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 19.99 AND p.valid_from < '2024-09-16' AND p.valid_until > '2024-09-16' AND i.available_qty...
CockroachDB v23.2
SELECT oi.item_id, i.available_qty, p.discount_pct FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 19.99 AND i.available_qty > 50 AND p.valid_from < '2024-03-15' AND p.valid_until > '2024-03-20'
{"plan": {"nodes": [{"type": "BitmapHeapScan", "args": [{"type": "IndexCond", "args": ["oi_unit_price_idx", "(oi.unit_price > 19.99)"]}, {"type": "IndexCond", "args": ["i_available_qty_idx", "(i.available_qty > 50)"]}]}, {"type": "HashJoin", "args": [{"type": "Hash", "args": [{"type": "SeqScan", "args": ["promotions"]}...
The query planner chose this sub-optimal route because the join order was determined by the availability of indexes on the join columns, and the optimizer overestimated the selectivity of the filters on the order_items table, leading to a large number of rows being joined and then filtered, resulting in a lossy page mo...
CREATE INDEX idx_order_items_sku_id_warehouse_id ON order_items (sku_id, warehouse_id); CREATE INDEX idx_inventory_stock_sku_id_warehouse_id ON inventory_stock (sku_id, warehouse_id); VACUUM ANALYZE order_items; VACUUM ANALYZE inventory_stock;
WITH ranked_orders AS (SELECT oi.item_id, i.available_qty, p.discount_pct, ROW_NUMBER() OVER (PARTITION BY oi.sku_id ORDER BY oi.unit_price DESC) AS row_num FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_pri...
SQLite 3.45
SELECT t1.sku_id, t2.available_qty, t1.unit_price * (1 - t3.discount_pct) AS discounted_price FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id INNER JOIN promotions t3 ON t1.sku_id = t3.sku_id WHERE t2.available_qty > 50 AND t3.valid_from < '2022-01-01' AN...
EXPLAIN QUERY PLAN SELECT t1.sku_id, t2.available_qty, t1.unit_price * (1 - t3.discount_pct) AS discounted_price FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id INNER JOIN promotions t3 ON t1.sku_id = t3.sku_id WHERE t2.available_qty > 50 AND t3.valid_fro...
The query planner chose this sub-optimal route because there are no indexes on the join and filter columns, leading to a full table scan on all three tables. Additionally, the calculation of the discounted price in the SELECT clause may also be contributing to the slow performance. The planner is unable to effectively ...
CREATE INDEX idx_order_items_sku_id ON order_items (sku_id); CREATE INDEX idx_order_items_warehouse_id ON order_items (warehouse_id); CREATE INDEX idx_inventory_stock_sku_id ON inventory_stock (sku_id); CREATE INDEX idx_inventory_stock_warehouse_id ON inventory_stock (warehouse_id); CREATE INDEX idx_promotions_sku_id O...
SELECT t1.sku_id, t2.available_qty, t1.unit_price * (1 - t3.discount_pct) AS discounted_price FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id INNER JOIN promotions t3 ON t1.sku_id = t3.sku_id WHERE t2.available_qty > 50 AND t3.valid_from < '2022-01-01' AN...
ClickHouse 24.3
SELECT oi.item_id, oi.order_id, i.available_qty FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE DATE(i.updated_at) = '2022-09-15' AND oi.unit_price > 19.99
{"trees":{"0":{"type":"Aggregate","inputs":[{"type":"Filter","inputs":[{"type":"Join","inputs":[{"type":"TableScan","arguments":{"table":"order_items","filter":""}},{"type":"TableScan","arguments":{"table":"inventory_stock","filter":""}}],"join_type":"Inner","join_on":"oi.sku_id = i.sku_id AND oi.warehouse_id = i.wareh...
The query planner chose this sub-optimal route because the DATE function wrapping the updated_at column in the WHERE clause prevents the optimizer from effectively utilizing the index on the updated_at column, leading to a full table scan. This is a classic example of a non-SARGable function preventing an index range s...
CREATE INDEX idx_updated_at ON inventory_stock (updated_at);
SELECT oi.item_id, oi.order_id, i.available_qty FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE i.updated_at >= '2022-09-15 00:00:00' AND i.updated_at < '2022-09-16 00:00:00' AND oi.unit_price > 19.99
SQLite 3.45
SELECT dt.device_id, AVG(dt.val) AS avg_val, MAX(ge.lat) AS max_lat FROM device_telematics dt JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01' AND ge.logged_at < '2022-12-31' GROUP BY dt.device_id, ge.id
EXPLAIN QUERY PLAN SELECT dt.device_id, AVG(dt.val) AS avg_val, MAX(ge.lat) AS max_lat FROM device_telematics dt JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01' AND ge.logged_at < '2022-12-31' GROUP BY dt.device_id, ge.id; -- The plan shows a...
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be joined between device_telematics and geofence_events, resulting in a large intermediate result set that exceeded the available work_mem, causing the query to spill to disk. Additionally, the lack of indexes ...
CREATE INDEX idx_device_telematics_device_id ON device_telematics (device_id); CREATE INDEX idx_geofence_events_device_id ON geofence_events (device_id); CREATE INDEX idx_device_telematics_metric_type_recorded_at ON device_telematics (metric_type, recorded_at); CREATE INDEX idx_geofence_events_logged_at ON geofence_eve...
SELECT dt.device_id, AVG(dt.val) AS avg_val, MAX(ge.lat) AS max_lat FROM device_telematics dt JOIN geofence_events ge ON dt.device_id = ge.device_id AND ge.id IN (SELECT id FROM geofence_events WHERE logged_at < '2022-12-31') WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01' GROUP BY dt.device_id
SQLite 3.45
SELECT t2.sku_id, SUM(t1.quantity * t1.unit_price) AS total_revenue FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id WHERE t2.available_qty > 50 AND t1.unit_price > 19.99 AND t1.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 12345) GROUP BY t...
EXPLAIN QUERY PLAN SELECT t2.sku_id, SUM(t1.quantity * t1.unit_price) AS total_revenue FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id WHERE t2.available_qty > 50 AND t1.unit_price > 19.99 AND t1.order_id IN (SELECT order_id FROM order_items WHERE sku_id ...
The query planner chose a sub-optimal route because the join condition on warehouse_id is not supported by an index, causing a full table scan on both order_items and inventory_stock tables. Furthermore, the correlated subquery in the WHERE clause adds to the computational cost, and the lack of an index on the sku_id c...
CREATE INDEX idx_order_items_sku_id ON order_items (sku_id); CREATE INDEX idx_order_items_warehouse_id ON order_items (warehouse_id); CREATE INDEX idx_inventory_stock_sku_id ON inventory_stock (sku_id); CREATE INDEX idx_inventory_stock_warehouse_id ON inventory_stock (warehouse_id);
SELECT t2.sku_id, SUM(t1.quantity * t1.unit_price) AS total_revenue FROM order_items t1 INNER JOIN inventory_stock t2 ON t1.sku_id = t2.sku_id AND t1.warehouse_id = t2.warehouse_id WHERE t2.available_qty > 50 AND t1.unit_price > 19.99 AND EXISTS (SELECT 1 FROM order_items t3 WHERE t3.order_id = t1.order_id AND t3.sku_i...
SQLite 3.45
SELECT * FROM ledger_entries le WHERE le.account_id IN (SELECT fa.account_id FROM fraud_alerts fa WHERE fa.score > 0.8 AND fa.created_at > '2022-01-01') AND le.amount > 1000 AND le.posting_date < '2023-01-01'
EXPLAIN QUERY PLAN for SELECT * FROM ledger_entries le WHERE le.account_id IN (SELECT fa.account_id FROM fraud_alerts fa WHERE fa.score > 0.8 AND fa.created_at > '2022-01-01') AND le.amount > 1000 AND le.posting_date < '2023-01-01';
The query planner chose a sub-optimal route because the correlated subquery in the WHERE clause is evaluating per-row sequential scans. This is due to the lack of an index on the account_id column in the ledger_entries table, and the score and created_at columns in the fraud_alerts table. As a result, the query planner...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_fraud_alerts_account_id_score_created_at ON fraud_alerts (account_id, score, created_at);
SELECT * FROM ledger_entries le JOIN fraud_alerts fa ON le.account_id = fa.account_id WHERE fa.score > 0.8 AND fa.created_at > '2022-01-01' AND le.amount > 1000 AND le.posting_date < '2023-01-01'
MySQL 8.0
SELECT i.imp_id, c.campaign_id, JSON_EXTRACT(i.metadata, '$.targeting.user_segment') AS user_segment FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE JSON_EXTRACT(i.metadata, '$.targeting.user_segment') = 'tech_enthusiasts' AND c.daily_budget > 500.00 AND i.served_at > '2022-01-01 00:00:00'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "3432.10"}, "table": {"table_name": "i", "access_type": "ALL", "possible_keys": ["campaign_id"], "key": null, "used_key_parts": null, "key_length": null, "ref": null, "rows": 431210, "filtered": 10.00, "extra": "Using where; Using filesort"}}}
The optimizer chose a full table scan on the ad_impressions table because the JSON_EXTRACT function in the WHERE clause cannot utilize a regular B-tree index, and there is no specialized index on the metadata column to support JSON path expressions. Furthermore, the join operation with the campaigns table introduces ad...
CREATE INDEX idx_ad_impressions_json ON ad_impressions ((JSON_EXTRACT(metadata, '$.targeting.user_segment'))); CREATE INDEX idx_campaigns_daily_budget ON campaigns (daily_budget); CREATE INDEX idx_ad_impressions_campaign_id ON ad_impressions (campaign_id);
SELECT i.imp_id, c.campaign_id, JSON_EXTRACT(i.metadata, '$.targeting.user_segment') AS user_segment FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE JSON_EXTRACT(i.metadata, '$.targeting.user_segment') = 'tech_enthusiasts' AND c.daily_budget > 500.00 AND i.served_at > '2022-01-01 00:00:00'...
MariaDB 11.2
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id JOIN billing_codes bc ON pa.admission_id = bc.admission_id WHERE lo.test_code ILIKE '%val%' AND pa.admitted_at > '2022-01-01' AND bc.charge_cents > 1000
{"query_block": {"select_id": 1, "table": {"table_name": "pa", "access_type": "ALL", "rows": 100000, "filtered": 10}, "table": {"table_name": "lo", "access_type": "ALL", "rows": 500000, "filtered": 5}, "table": {"table_name": "bc", "access_type": "ALL", "rows": 200000, "filtered": 20}}}
The query planner chose a sub-optimal route because the leading wildcard search in the ILIKE operator disabled the B-Tree index usage on the test_code column, resulting in a full table scan of the lab_orders table, which has a large number of rows. Additionally, the joins with patient_admissions and billing_codes table...
CREATE INDEX idx_test_code ON lab_orders (test_code); CREATE INDEX idx_admission_id ON patient_admissions (admission_id); CREATE INDEX idx_admission_id ON billing_codes (admission_id);
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id JOIN billing_codes bc ON pa.admission_id = bc.admission_id WHERE lo.test_code LIKE '%val%' AND pa.admitted_at > '2022-01-01' AND bc.charge_cents > 1000 AND lo.test_code > ''
PostgreSQL 16.2
SELECT * FROM ledger_entries le JOIN accounts a ON le.account_id::text = a.id::text WHERE le.posting_date > '2022-01-01' AND a.risk_tier = 'high' AND le.amount > 1000.0 AND a.balance < 10000.0
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM ledger_entries le JOIN accounts a ON le.account_id::text = a.id::text WHERE le.posting_date > '2022-01-01' AND a.risk_tier = 'high' AND le.amount > 1000.0 AND a.balance < 10000.0; => Hash Join on le.account_id::text = a.id::text (cost=2345.67..4567.89 rows=1234 width=234) ...
The query planner chose this sub-optimal route because the join condition between ledger_entries and accounts involves implicit type coercion between the account_id column of type uuid and the id column of type text, preventing the use of a B-Tree index scan on the account_id column. This forces the planner to use a se...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_accounts_id ON accounts (id); CREATE INDEX idx_ledger_entries_posting_date ON ledger_entries (posting_date); CREATE INDEX idx_accounts_risk_tier ON accounts (risk_tier); VACUUM ANALYZE ledger_entries; VACUUM ANALYZE accounts;
SELECT * FROM ledger_entries le JOIN accounts a ON le.account_id = a.id WHERE le.posting_date > '2022-01-01'::date AND a.risk_tier = 'high' AND le.amount > 1000.0 AND a.balance < 10000.0
SQLite 3.45
SELECT DISTINCT d.device_id, d.region, AVG(t.val) AS avg_val FROM devices d INNER JOIN device_telematics t ON d.device_id = t.device_id WHERE t.firmware_v = '2.1.4' AND t.metric_type = 'temperature' AND t.recorded_at BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY d.device_id, d.region ORDER BY avg_val DESC LIMIT 10;
EXPLAIN QUERY PLAN SELECT DISTINCT d.device_id, d.region, AVG(t.val) AS avg_val FROM devices d INNER JOIN device_telematics t ON d.device_id = t.device_id WHERE t.firmware_v = '2.1.4' AND t.metric_type = 'temperature' AND t.recorded_at BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY d.device_id, d.region ORDER BY avg_va...
The query planner chose this sub-optimal route because the existing indexes on device_telematics are not selective enough to satisfy the filter conditions. The query requires a composite index on (firmware_v, metric_type, recorded_at) to efficiently filter the rows. However, the current index granularity is too broad, ...
CREATE INDEX idx_device_telematics_firmware_metric_recorded ON device_telematics (firmware_v, metric_type, recorded_at);
SELECT DISTINCT d.device_id, d.region, AVG(t.val) AS avg_val FROM devices d INNER JOIN device_telematics t ON d.device_id = t.device_id WHERE t.firmware_v = '2.1.4' AND t.metric_type = 'temperature' AND t.recorded_at BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY d.device_id, d.region ORDER BY avg_val DESC LIMIT 10; --...
MySQL 8.0
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipment_details s JOIN carrier_rate_charges cr ON s.carrier_id = cr.carrier_id JOIN parcel_event_logs pe ON s.tracking_num = pe.tracking_num WHERE s.departed_at > '2022-01-01' AND cr.zone_id = 5 AND pe.checkpoint = 'Departure Scan' ORDER BY s.departed_at LIMIT 100...
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "s", "access_type": "ALL", "possible_keys": ["PRIMARY"], "key": null, "used_key_parts": null, "key_length": null, "rows": 50000, "filtered": 20, "extra": "Using filesort"}}, "table": {"table_name": "cr", "access_type": "re...
The query planner chose this sub-optimal route because the departure timestamp column is not indexed, forcing the database to perform a full table scan on the shipment_details table, and then using a filesort operation to sort the results. Additionally, the join operation with the parcel_event_logs table is using a blo...
CREATE INDEX idx_shipment_departed_at ON shipment_details (departed_at); CREATE INDEX idx_parcel_event_checkpoint ON parcel_event_logs (checkpoint); CREATE INDEX idx_carrier_rate_zone_id ON carrier_rate_charges (zone_id);
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipment_details s JOIN carrier_rate_charges cr ON s.carrier_id = cr.carrier_id JOIN parcel_event_logs pe ON s.tracking_num = pe.tracking_num WHERE s.departed_at > '2022-01-01' AND cr.zone_id = 5 AND pe.checkpoint = 'Departure Scan' ORDER BY s.departed_at LIMIT 100...
SQLite 3.45
SELECT * FROM ad_impressions ai JOIN click_events ce ON ai.imp_id = ce.imp_id WHERE ai.bid_cpm > 5.25 AND ai.served_at > '2022-01-01' AND ai.publisher_id IN (123, 456, 789) ORDER BY ROW_NUMBER() OVER (PARTITION BY ai.campaign_id ORDER BY ai.served_at DESC);
The execution plan shows a full table scan of ad_impressions, followed by a nested loop join with click_events, and then a sort operation to compute the ROW_NUMBER() window function, resulting in a total of 134,219,481 rows being sorted on disk, with a total execution time of 12,456.12 milliseconds.
The query planner chose this sub-optimal route because the window function ROW_NUMBER() OVER (PARTITION BY ai.campaign_id ORDER BY ai.served_at DESC) requires a sort operation, and since there is no matching composite index on (campaign_id, served_at), the planner decided to sort the entire table on disk, leading to a ...
CREATE INDEX idx_ad_impressions_campaign_id_served_at ON ad_impressions (campaign_id, served_at DESC); CREATE INDEX idx_click_events_imp_id ON click_events (imp_id); VACUUM ANALYZE;
WITH ranked_impressions AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY campaign_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND served_at > '2022-01-01' AND publisher_id IN (123, 456, 789)) SELECT * FROM ranked_impressions ri JOIN click_events ce ON ri.imp_id = ce.imp_id;
SQLite 3.45
SELECT T1.id, T2.user_id, T2.workspace_id FROM audit_logs AS T1 INNER JOIN workspace_users AS T2 ON T1.workspace_id = T2.workspace_id WHERE T1.event_time > '2022-01-01' AND T2.role = 'admin' AND T1.action = 'login'
EXPLAIN QUERY PLAN SELECT T1.id, T2.user_id, T2.workspace_id FROM audit_logs AS T1 INNER JOIN workspace_users AS T2 ON T1.workspace_id = T2.workspace_id WHERE T1.event_time > '2022-01-01' AND T2.role = 'admin' AND T1.action = 'login';
The query planner chose a sub-optimal Hash Join between the audit_logs table and the workspace_users table because the join condition is based on the workspace_id column, which has a high cardinality in the audit_logs table, but a low cardinality in the workspace_users table. Additionally, the query has multiple filter...
CREATE INDEX idx_audit_logs_workspace_id ON audit_logs (workspace_id); CREATE INDEX idx_workspace_users_workspace_id ON workspace_users (workspace_id); CREATE INDEX idx_audit_logs_event_time ON audit_logs (event_time); CREATE INDEX idx_workspace_users_role ON workspace_users (role);
SELECT T1.id, T2.user_id, T2.workspace_id FROM audit_logs AS T1 INNER JOIN workspace_users AS T2 ON T1.workspace_id = T2.workspace_id WHERE T1.event_time > '2022-01-01' AND T2.role = 'admin' AND T1.action = 'login' ORDER BY T1.event_time;
MariaDB 11.2
SELECT p.admission_id, l.test_code, b.icd10 FROM patient_admissions p INNER JOIN lab_orders l ON p.admission_id = l.admission_id INNER JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.flagged = 1 AND b.charge_cents > 5000
EXPLAIN (ANALYZE, BUFFERS) SELECT p.admission_id, l.test_code, b.icd10 FROM patient_admissions p INNER JOIN lab_orders l ON p.admission_id = l.admission_id INNER JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.flagged = 1 AND b.charge_cents > 5000
The query planner chose this sub-optimal route because the table statistics are outdated, causing it to severely underestimate the intermediate row counts. The join order was determined based on these outdated statistics, leading to a nested loop join with a high number of rows being scanned. Additionally, the lack of ...
CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id); CREATE INDEX idx_lab_orders_admission_id ON lab_orders (admission_id); CREATE INDEX idx_billing_codes_admission_id ON billing_codes (admission_id); CREATE INDEX idx_billing_codes_charge_cents ON billing_codes (charge_cents); ANALYZE TABLE ...
SELECT /*+ MERGE(p) */ p.admission_id, l.test_code, b.icd10 FROM patient_admissions p INNER JOIN lab_orders l ON p.admission_id = l.admission_id INNER JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.flagged = 1 AND b.charge_cents > 5000
MySQL 8.0
SELECT s.tracking_num, c.base_rate, pe.scan_time FROM shipments s INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.departed_at > '2022-01-01' AND c.zone_id = 5 AND pe.checkpoint = 'Arrival Scan' ORDER BY s.departed_at LIMIT 10000;
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 12345.67}, "table": {"table_name": "s", "access_type": "ALL", "rows": 50000, "filtered": 20, "index_condition": null}, "table": {"table_name": "c", "access_type": "ALL", "rows": 10000, "filtered": 50, "index_condition": null}, "table": {"table_name": "pe", "a...
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned by the subquery, leading to an inefficient merge join operation. The lack of an index on the departed_at column in the shipments table forced the database to perform a full table scan, resulting in ...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_carrier_rates_zone_id ON carrier_rates (zone_id); CREATE INDEX idx_parcel_events_checkpoint ON parcel_events (checkpoint);
SELECT s.tracking_num, c.base_rate, pe.scan_time FROM shipments s INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.zone_id = 5 INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.checkpoint = 'Arrival Scan' WHERE s.departed_at > '2022-01-01' ORDER BY s.departed_at LIMIT 10000;
MariaDB 11.2
SELECT t1.account_id, SUM(t1.amount) AS total_amount FROM ledger_entries t1 INNER JOIN accounts t2 ON t1.account_id = t2.id WHERE t1.currency = 'USD' AND t2.risk_tier = 'high' AND t1.posting_date > '2022-01-01' AND t2.user_id = '123e4567-e89b-12d3-a456-426655440000'
{"query_block": {"select_id": 1, "table": {"table_name": "t1", "access_type": "ALL", "key": null, "key_len": null, "ref": null, "rows": 102400, "filtered": 10, "Extra": "Using filesort"}, "table": {"table_name": "t2", "access_type": "ALL", "key": null, "key_len": null, "ref": null, "rows": 51200, "filtered": 10, "Extra...
The query planner chose this sub-optimal route because the join condition between ledger_entries and accounts is on a string column (account_id) that is implicitly converted to a uuid, preventing the use of the B-Tree index on the account_id column. This implicit type coercion leads to a full table scan, resulting in p...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_accounts_id ON accounts (id); ALTER TABLE ledger_entries MODIFY COLUMN account_id VARCHAR(36) CHARACTER SET ascii COLLATE ascii_general_ci; ALTER TABLE accounts MODIFY COLUMN id VARCHAR(36) CHARACTER SET ascii COLLATE ascii_gene...
SELECT t1.account_id, SUM(t1.amount) AS total_amount FROM ledger_entries t1 INNER JOIN accounts t2 ON CAST(t1.account_id AS BINARY(16)) = CAST(t2.id AS BINARY(16)) WHERE t1.currency = 'USD' AND t2.risk_tier = 'high' AND t1.posting_date > '2022-01-01' AND t2.user_id = UNHEX(REPLACE('123e4567-e89b-12d3-a456-426655440000'...
MariaDB 11.2
SELECT t1.tracking_num, AVG(t2.base_rate) AS avg_base_rate FROM shipments t1 JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id WHERE t1.status = 'IN_TRANSIT' AND t2.weight_kg > 50 AND t1.departed_at > '2022-01-01' GROUP BY t1.tracking_num HAVING COUNT(t1.tracking_num) > 10
{"query_block": {"select_id": 1, "cost": 23456.23, "rows": 1234, "filtered": 56.78, "table": {"id": 1, "join_type": "inner", "table": "shipments", "access_type": "ALL", "possible_keys": ["PRIMARY", "carrier_id"], "key": null, "key_len": null, "ref": null, "rows": 12345, "filtered": 100.0, "extra": "Using filesort"}, "t...
The query planner chose this sub-optimal route because it underestimated the number of rows that would be returned by the join operation, resulting in a large amount of data being spilled to temporary disk files during the Hash Aggregate operation. This was further exacerbated by the lack of efficient indexing on the j...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id); ALTER TABLE shipments ADD COLUMN departed_at_date DATE; UPDATE shipments SET departed_at_date = DATE(departed_at); CREATE INDEX idx_shipments_departed_at_date ON shipments (departed_...
WITH shipments_filtered AS (SELECT tracking_num, carrier_id, departed_at_date FROM shipments WHERE status = 'IN_TRANSIT' AND departed_at_date > '2022-01-01') SELECT sf.tracking_num, AVG(cr.base_rate) AS avg_base_rate FROM shipments_filtered sf JOIN carrier_rates cr ON sf.carrier_id = cr.carrier_id WHERE cr.weight_kg > ...
CockroachDB v23.2
SELECT le.id, le.account_id, le.amount, ac.user_id FROM ledger_entries le JOIN accounts ac ON le.account_id::text = ac.id::text WHERE le.posting_date > '2022-01-01' AND le.status = 'pending' AND ac.risk_tier = 3
{"planning_time": 12.456, "execution_time": 2345.123, "rows": 10000, "stages": [{"stage": "Gather", "rows": 10000, "bytes": 1024000, "filter": "le.posting_date > '2022-01-01' AND le.status = 'pending' AND ac.risk_tier = 3"}, {"stage": "Shuffle", "rows": 10000, "bytes": 1024000, "filter": "le.account_id::text = ac.id::t...
The query planner chose this sub-optimal route because the join condition is performing an implicit type coercion between the text representation of the account_id column in the ledger_entries table and the id column in the accounts table, which is of type uuid. This prevents the planner from using a B-Tree index scan ...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_accounts_id ON accounts (id); CREATE INDEX idx_ledger_entries_posting_date ON ledger_entries (posting_date); VACUUM ANALYZE;
SELECT le.id, le.account_id, le.amount, ac.user_id FROM ledger_entries le JOIN accounts ac ON le.account_id = ac.id WHERE le.posting_date > '2022-01-01' AND le.status = 'pending' AND ac.risk_tier = 3
PostgreSQL 16.2
SELECT oi.order_id, oi.sku_id, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id WHERE ist.available_qty > 500 AND oi.unit_price > 19.99 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 12345...
EXPLAIN (ANALYZE, BUFFERS) SELECT... -> Bitmap Heap Scan on order_items oi (cost=2345.67..4567.89 rows=1234 width=45) (actual time=123.45..234.56 rows=100 loops=1) Heap Blocks: exact=4567; -> BitmapAnd (cost=123.45..234.56 rows=1234 width=0) (actual time=12.34..23.45 rows=100 loops=1) -> Bitmap Index Scan on or...
The PostgreSQL query planner chose this sub-optimal route because it was attempting to utilize the available indexes on the order_items and inventory_stock tables, but the lack of a covering index on the order_items table resulted in excessive heap fetches, leading to slower query performance. Additionally, the join op...
CREATE INDEX order_items_covering_idx ON order_items (sku_id, warehouse_id, unit_price, order_id) INCLUDE (quantity); ALTER TABLE order_items SET (parallel_workers = 4); VACUUM ANALYZE order_items; CREATE INDEX inventory_stock_covering_idx ON inventory_stock (sku_id, warehouse_id, available_qty) INCLUDE (updated_at);
SELECT oi.order_id, oi.sku_id, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id WHERE ist.available_qty > 500 AND oi.unit_price > 19.99 AND EXISTS (SELECT 1 FROM order_items WHERE order_id = oi.order_id AND sk...
CockroachDB v23.2
SELECT le.id, le.account_id, le.amount FROM ledger_entries le WHERE le.posting_date > '2022-01-01' AND le.status = 'pending' AND le.account_id IN (SELECT fra.account_id FROM fraud_alerts fra WHERE fra.score > 0.8 AND fra.created_at > '2022-06-01' AND fra.account_id = le.account_id)
EXPLAIN (ANALYZE, BUFFERS) SELECT le.id, le.account_id, le.amount FROM ledger_entries le WHERE le.posting_date > '2022-01-01' AND le.status = 'pending' AND le.account_id IN (SELECT fra.account_id FROM fraud_alerts fra WHERE fra.score > 0.8 AND fra.created_at > '2022-06-01' AND fra.account_id = le.account_id) -- plannin...
The query planner chose this sub-optimal route because it was misled by the correlated subquery in the WHERE clause, which evaluates per-row sequential scans. This led to a Nested Loop Left Join, where the inner loop iterates over the entire fraud_alerts table for each row in the ledger_entries table, resulting in a la...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_fraud_alerts_account_id ON fraud_alerts (account_id); VACUUM ANALYZE ledger_entries; VACUUM ANALYZE fraud_alerts;
WITH fra AS (SELECT DISTINCT account_id FROM fraud_alerts WHERE score > 0.8 AND created_at > '2022-06-01') SELECT le.id, le.account_id, le.amount FROM ledger_entries le JOIN fra ON le.account_id = fra.account_id WHERE le.posting_date > '2022-01-01' AND le.status = 'pending'
CockroachDB v23.2
SELECT pa.admission_id, pa.patient_id, lo.test_code FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE lo.test_code ILIKE '%oxytoc%' AND pa.admitted_at > '2022-01-01' AND pa.clinic_id = 123
{"plan":"RecursiveCTE { ReturnResults: true, CTEs: [{ Name: "CTE_1", Def: { Plan: { Filter: { Input: { TableReader { Table: { patient_admissions:1 } }, Columns: ["admission_id", "patient_id", "admitted_at", "clinic_id"] }, Conditions: [(admitted_at > '2022-01-01'), (clinic_id = 123)] } }, Name: "CTE_1" }], Result: { Fi...
The query planner chose this sub-optimal route because the leading wildcard search in the ILIKE clause disabled the use of the B-Tree index on the test_code column. As a result, the planner opted for a full table scan of lab_orders, which led to increased memory usage and a prolonged execution time. Furthermore, the ab...
CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code); CREATE INDEX idx_patient_admissions_admitted_at_clinic_id ON patient_admissions (admitted_at, clinic_id); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders;
SELECT pa.admission_id, pa.patient_id, lo.test_code FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE lo.test_code ILIKE 'oxytoc%' AND pa.admitted_at > '2022-01-01' AND pa.clinic_id = 123
ClickHouse 24.3
SELECT device_id, AVG(val) AS avg_val, MAX(val) AS max_val, MIN(val) AS min_val FROM device_telematics WHERE recorded_at > '2022-01-01' AND firmware_v = '1.2.3' AND metric_type IN ('temperature', 'humidity', 'pressure') GROUP BY device_id, metric_type ORDER BY avg_val DESC LIMIT 100;
{"rows": 100, "bytes": 8192, "filtered": 0.01, "nodes": [{"name": "Aggregating", "rows": 100, "bytes": 8192, "filtered": 0.01, "subnodes": [{"name": "Sorting", "rows": 100, "bytes": 8192, "filtered": 0.01, "subnodes": [{"name": "Grouping", "rows": 100, "bytes": 8192, "filtered": 0.01, "subnodes": [{"name": "Filter", "r...
The query planner chose this sub-optimal route because the high-cardinality GROUP BY clause on the device_id and metric_type columns is exhausting the available work_mem, causing the query to spill to disk. This is further exacerbated by the fact that the metric_type column has a large number of unique values, resultin...
CREATE INDEX device_telematics_idx ON device_telematics (device_id, metric_type);
SELECT device_id, AVG(val) AS avg_val, MAX(val) AS max_val, MIN(val) AS min_val FROM device_telematics WHERE recorded_at > '2022-01-01' AND firmware_v = '1.2.3' AND metric_type IN ('temperature', 'humidity', 'pressure') GROUP BY device_id, metric_type ORDER BY avg_val DESC LIMIT 100;
CockroachDB v23.2
SELECT ps.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms FROM player_stats ps WHERE ps.kills > 15 OR ps.score > 1000 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'US-East' AND ms.game_mode = 'Ranked');
EXPLAIN (ANALYZE, BUFFERS) SELECT ps.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms FROM player_stats ps WHERE ps.kills > 15 OR ps.score > 1000 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'US-East' AND ms.game_mode = 'Ranked'); -> Full scan of player_stats ps (actual time=12...
The query planner chose a full table scan on the player_stats table because the WHERE clause contains an OR condition across unindexed columns (kills and score), which prevents the optimizer from using any existing indexes. Furthermore, the subquery in the IN clause adds an additional layer of complexity, causing the o...
CREATE INDEX idx_player_stats_kills ON player_stats (kills); CREATE INDEX idx_player_stats_score ON player_stats (score); CREATE INDEX idx_match_sessions_region_game_mode ON match_sessions (region, game_mode); VACUUM ANALYZE player_stats; VACUUM ANALYZE match_sessions;
SELECT ps.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms FROM player_stats ps WHERE ps.kills > 15 OR ps.score > 1000 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'US-East' AND ms.game_mode = 'Ranked' AND ms.match_id = ps.match_id);
ClickHouse 24.3
SELECT oi.item_id, oi.sku_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE oi.unit_price > 19.99 AND i.available_qty > 50 AND oi.order_id IN (SELECT order_id FROM promotions WHERE discount_pct > 0.1 AND valid_from < '2022-07-15')
{"plans": [{"nodes": [{"type": "NestedLoopJoin", "rows": 123456, "bytes": 987654321}, {"type": "Filter", "rows": 123456, "bytes": 987654321}, {"type": "TableScan", "rows": 123456, "bytes": 987654321}], "bytes": 987654321, "rows": 123456}]}
The query planner chose this sub-optimal route because it failed to utilize an efficient index on the join and filter columns, resulting in excessive heap fetches on the wide order_items table. This is due to the missing covering index on the sku_id and warehouse_id columns. Furthermore, the lack of an index on the uni...
CREATE INDEX idx_order_items_sku_warehouse ON order_items (sku_id, warehouse_id) INCLUDE (item_id, unit_price, order_id); CREATE INDEX idx_inventory_stock_sku_warehouse ON inventory_stock (sku_id, warehouse_id) INCLUDE (available_qty);
SELECT oi.item_id, oi.sku_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE oi.unit_price > 19.99 AND i.available_qty > 50 AND EXISTS (SELECT 1 FROM promotions p WHERE p.order_id = oi.order_id AND p.discount_pct > 0.1 AND p.valid_from < '20...
PostgreSQL 16.2
SELECT d.device_id, d.firmware_v, dt.val, dt.recorded_at FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND d.region = 'North America' AND dt.recorded_at > '2022-01-01'::date
EXPLAIN (ANALYZE, BUFFERS) SELECT d.device_id, d.firmware_v, dt.val, dt.recorded_at FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND d.region = 'North America' AND dt.recorded_at > '2022-01-01'::date; Result: -> Nested Loop Left Join on devi...
The query planner chose this sub-optimal route because the existing index on the device_id column in the devices table is not being utilized effectively due to the broad granularity of the skip index, resulting in excessive granule loading. The planner opted for a nested loop left join, which led to a sequential scan o...
CREATE INDEX device_telematics_metric_type_val_recorded_at_idx ON device_telematics (metric_type, val, recorded_at); CREATE INDEX devices_region_device_id_idx ON devices (region, device_id); VACUUM ANALYZE device_telematics; VACUUM ANALYZE devices;
SELECT d.device_id, d.firmware_v, dt.val, dt.recorded_at FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id AND d.region = 'North America' WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND dt.recorded_at > '2022-01-01'::date
ClickHouse 24.3
SELECT pa.admission_id, AVG(bo.numeric_result) AS avg_lab_result FROM patient_admissions pa JOIN lab_orders bo ON pa.admission_id = bo.admission_id WHERE pa.clinic_id = 817 AND bo.test_code = 'HB1' AND bo.result_time > '2022-01-01' GROUP BY pa.admission_id
{"stages": [{"frames": 1, "rows": 100000, "bytes": 10485760, "filtered_rows": 87750, "stage": "Aggregating", "before": {"stages": [{"stage": "MergingJoin", "rows": 87750, "bytes": 10485760, "before": {"stages": [{"stage": "Reading", "rows": 100000, "bytes": 10485760, "table": "lab_orders"}, {"stage": "Reading", "rows":...
The query planner chose this sub-optimal route because the outdated table statistics led to a severe underestimation of the intermediate row counts, resulting in a full table scan on the large lab_orders table. Furthermore, the join operation between patient_admissions and lab_orders was not properly optimized due to t...
ALTER TABLE lab_orders UPDATE STATISTICS; CREATE INDEX idx_lab_orders_admission_id ON lab_orders (admission_id); CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id);
SELECT pa.admission_id, AVG(bo.numeric_result) AS avg_lab_result FROM patient_admissions pa JOIN lab_orders bo ON pa.admission_id = bo.admission_id AND bo.test_code = 'HB1' WHERE pa.clinic_id = 817 AND bo.result_time > '2022-01-01' GROUP BY pa.admission_id
CockroachDB v23.2
SELECT oi.item_id, oi.sku_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE oi.unit_price > 19.99 AND i.available_qty < 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE quantity > 10) AND EXISTS (SELECT 1 FROM promotions p WHER...
EXPLAIN (ANALYZE, BUFFERS) SELECT oi.item_id, oi.sku_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE oi.unit_price > 19.99 AND i.available_qty < 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE quantity > 10) AND EXISTS (SELE...
The query planner chose this sub-optimal route because it failed to utilize an efficient index on the join columns, resulting in excessive heap fetches on the wide table, specifically the inventory_stock table. The absence of a covering index that includes the available_qty column forced the planner to perform a full t...
CREATE INDEX idx_inventory_stock_sku_warehouse_id ON inventory_stock (sku_id, warehouse_id) INCLUDE (available_qty);
SELECT oi.item_id, oi.sku_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id WHERE oi.unit_price > 19.99 AND i.available_qty < 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE quantity > 10) AND EXISTS (SELECT 1 FROM promotions p WHER...
ClickHouse 24.3
SELECT dt.device_id, dt.metric_type, dt.val, d.region FROM device_telematics AS dt INNER JOIN devices AS d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.firmware_v = '1.2.3' AND d.status = 'active' AND dt.metric_type IN ('temperature', 'humidity', 'pressure') ORDER BY dt.recorded_at ...
{"explain": "EXPLAIN (ANALYZE, BUFFERS) SELECT dt.device_id, dt.metric_type, dt.val, d.region FROM device_telematics AS dt INNER JOIN devices AS d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.firmware_v = '1.2.3' AND d.status = 'active' AND dt.metric_type IN ('temperature', 'humidit...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is defined as (device_id, recorded_at), but the query is filtering on recorded_at first, causing the query to scan the entire partition. Additionally, the join with the devices table is done on the device_id column, wh...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at, device_id); ALTER TABLE device_telematics ADD COLUMN firmware_v_int Int32; ALTER TABLE device_telematics ADD COLUMN metric_type_int Int32;
SELECT dt.device_id, dt.metric_type, dt.val, d.region FROM device_telematics AS dt INNER JOIN devices AS d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.firmware_v_int = 123AND d.status = 'active' AND dt.metric_type_int IN (1, 2, 3) ORDER BY dt.recorded_at DESC LIMIT 1000;
SQLite 3.45
SELECT SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi INNER JOIN inventory_stock isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE isk.available_qty > 50 AND p.valid_from < '2022-01-01' AND p.valid_until > '2022-12-31' AND o...
EXPLAIN QUERY PLAN SELECT SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi INNER JOIN inventory_stock isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE isk.available_qty > 50 AND p.valid_from < '2022-01-01' AND p.valid_until >...
The query planner chose this sub-optimal route because there are no suitable indexes on the join columns (sku_id and warehouse_id) of the order_items and inventory_stock tables, and also on the filter columns (available_qty, valid_from, valid_until, and unit_price) of the inventory_stock, promotions, and order_items ta...
CREATE INDEX idx_order_items_sku_id ON order_items (sku_id); CREATE INDEX idx_inventory_stock_sku_id_warehouse_id ON inventory_stock (sku_id, warehouse_id); CREATE INDEX idx_promotions_sku_id ON promotions (sku_id); CREATE INDEX idx_order_items_unit_price ON order_items (unit_price); CREATE INDEX idx_inventory_stock_av...
SELECT SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi INNER JOIN inventory_stock isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE isk.available_qty > 50 AND p.valid_from < '2022-01-01' AND p.valid_until > '2022-12-31' AND o...
ClickHouse 24.3
SELECT * FROM audit_logs AS al WHERE al.workspace_id = 8542 AND al.event_time >= '2022-01-01' AND al.event_time < '2022-02-01' ORDER BY al.id LIMIT 100 OFFSET 500000
{"trees":{"0":{"type":"AggregatingMergeTree","rows":"1234567","bytes":"987654321"},"1":{"type":"Sorting","rows":"1234567","bytes":"987654321"},"2":{"type":"Filter","rows":"1234567","bytes":"987654321"},"3":{"type":"ReadFromMergeTree","rows":"1234567","bytes":"987654321"}}}
The query planner chose this sub-optimal route because it prioritized satisfying the filter conditions over optimizing the offset pagination, resulting in a full table scan and sequential traversal of millions of historical audit records, which led to a significant increase in execution time and resource utilization. T...
CREATE INDEX idx_workspace_id_event_time ON audit_logs (workspace_id, event_time) TYPE set(0); ALTER TABLE audit_logs ADD COLUMN id_int Int32; ALTER TABLE audit_logs UPDATE id_int = id;
SELECT * FROM audit_logs AS al WHERE al.workspace_id = 8542 AND al.event_time >= '2022-01-01' AND al.event_time < '2022-02-01' ORDER BY al.id_int LIMIT 100 OFFSET 500000
SQLite 3.45
SELECT * FROM ad_impressions ai INNER JOIN click_events ce ON ai.imp_id = ce.imp_id WHERE ai.campaign_id = 123 AND ai.publisher_id = 456 AND JSON_EXTRACT(ai.user_segment, '$.age') > 25 AND JSON_EXTRACT(ai.user_segment, '$.interests') LIKE '%sports%'
EXPLAIN QUERY PLAN SELECT * FROM ad_impressions ai INNER JOIN click_events ce ON ai.imp_id = ce.imp_id WHERE ai.campaign_id = 123 AND ai.publisher_id = 456 AND JSON_EXTRACT(ai.user_segment, '$.age') > 25 AND JSON_EXTRACT(ai.user_segment, '$.interests') LIKE '%sports%'; -- The query plan shows a full table scan on ad_im...
The query planner chose this sub-optimal route because it lacks a suitable index on the JSONB payload extraction inside the WHERE filter, specifically on the user_segment column. The JSON_EXTRACT function is not indexed, leading to a full table scan. Furthermore, the LIKE operator with a wildcard at the beginning of th...
CREATE INDEX idx_ad_impressions_campaign_id ON ad_impressions (campaign_id); CREATE INDEX idx_ad_impressions_publisher_id ON ad_impressions (publisher_id); CREATE INDEX idx_ad_impressions_user_segment ON ad_impressions (user_segment); VACUUM ANALYZE ad_impressions; VACUUM ANALYZE click_events;
SELECT * FROM ad_impressions ai INNER JOIN click_events ce ON ai.imp_id = ce.imp_id WHERE ai.campaign_id = 123 AND ai.publisher_id = 456 AND ai.user_segment LIKE '%"age":{"value":26}%"' AND ai.user_segment LIKE '%"interests":"sports"%'
MySQL 8.0
SELECT * FROM audit_logs a JOIN workspace_users wu ON a.workspace_id = wu.workspace_id WHERE wu.role = 'admin' AND a.event_time > '2022-01-01' ORDER BY a.event_time DESC LIMIT 10 OFFSET 1000000;
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 234567.89}, "table": {"table_name": "a", "access_type": "ALL", "rows": 1234567, "filtered": 12.34, "cost": 12345.67}, "extra": ["Using filesort"]}}
The query planner chose this sub-optimal route because the large OFFSET value of 1000000 requires the database to sequentially traverse the entire audit_logs table, resulting in a full table scan and filesort operation, which leads to a significant increase in query execution time. Furthermore, the join operation with ...
CREATE INDEX idx_audit_logs_event_time ON audit_logs (event_time); CREATE INDEX idx_workspace_users_role ON workspace_users (role); ALTER TABLE audit_logs ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY; VACUUM ANALYZE;
SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY event_time DESC) AS row_num FROM audit_logs a JOIN workspace_users wu ON a.workspace_id = wu.workspace_id WHERE wu.role = 'admin' AND a.event_time > '2022-01-01') AS subquery WHERE row_num BETWEEN 1000001 AND 1000010;
MySQL 8.0
SELECT d.device_id, AVG(t.val) AS avg_val FROM devices d JOIN device_telematics t ON d.device_id = t.device_id WHERE t.metric_type = 'temperature' AND t.recorded_at > '2022-01-01' AND d.region = 'North America' GROUP BY d.device_id ORDER BY avg_val DESC LIMIT 100;
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "t", "access_type": "ALL", "rows": 1000000, "filtered": 1, "index_condition": "NULL"}}, "warning": "Using filesort"}
The query planner chose this sub-optimal route because the join order was not optimal, resulting in a large number of rows being joined and then filtered, leading to excessive granule loading. The lack of a suitable index on the device_telematics table for the metric_type and recorded_at columns caused the planner to c...
CREATE INDEX idx_device_telematics_metric_type_recorded_at ON device_telematics (metric_type, recorded_at); CREATE INDEX idx_devices_region ON devices (region); ANALYZE TABLE device_telematics; ANALYZE TABLE devices;
SELECT d.device_id, AVG(t.val) AS avg_val FROM devices d JOIN device_telematics t ON d.device_id = t.device_id AND t.metric_type = 'temperature' AND t.recorded_at > '2022-01-01' WHERE d.region = 'North America' GROUP BY d.device_id ORDER BY avg_val DESC LIMIT 100;
MySQL 8.0
SELECT t1.tracking_num, t2.base_rate FROM shipments t1 JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id AND t1.departed_at > '2022-01-01' WHERE t2.zone_id = 5 AND t1.status = 'in_transit' AND t1.weight_kg > 10
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 23456.22}, "table": {"table_name": "t1", "access_type": "ALL", "rows": 10000, "filtered": 20.0, "cost": 123.45}, "table": {"table_name": "t2", "access_type": "ALL", "rows": 5000, "filtered": 10.0, "cost": 67.89}, "nested_loop": [ {"table": {"table_name": "t1"...
The query planner chose this sub-optimal route because it was unable to find a suitable index to support the join operation between the shipments and carrier_rates tables. As a result, it resorted to a nested loop join, which involves scanning the entire carrier_rates table for each row in the shipments table, resultin...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id, departed_at); CREATE INDEX idx_carrier_rates_carrier_id_zone_id ON carrier_rates (carrier_id, zone_id); ALTER TABLE shipments ADD COLUMN weight_kg INT; ALTER TABLE carrier_rates ADD COLUMN zone_id INT; ALTER TABLE shipments ADD INDEX idx_shipments_status (...
SELECT t1.tracking_num, t2.base_rate FROM shipments t1 JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id AND t1.departed_at > '2022-01-01' AND t2.zone_id = 5 AND t1.status = 'in_transit' AND t1.weight_kg > 10 USE INDEX (idx_shipments_carrier_id, idx_carrier_rates_carrier_id_zone_id)
PostgreSQL 16.2
SELECT T1.season_id, T1.player_id, T1.mmr_rating + 10 AS new_mmr_rating FROM leaderboards AS T1 INNER JOIN player_stats AS T2 ON T1.player_id = T2.player_id WHERE T2.kills > 15 AND T2.score > 500 AND T1.season_id = 23 AND T1.rank_tier = 'Gold' ORDER BY T1.mmr_rating DESC LIMIT 100 OFFSET 50
EXPLAIN (ANALYZE, BUFFERS) SELECT T1.season_id, T1.player_id, T1.mmr_rating + 10 AS new_mmr_rating FROM leaderboards AS T1 INNER JOIN player_stats AS T2 ON T1.player_id = T2.player_id WHERE T2.kills > 15 AND T2.score > 500 AND T1.season_id = 23 AND T1.rank_tier = 'Gold' ORDER BY T1.mmr_rating DESC LIMIT 100 OFFSET 50; ...
The PostgreSQL query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned by the join operation, leading to a high start-up cost and total cost. Additionally, the planner chose to use a Merge Join instead of a Hash Join or Nested Loop Join, which would have bee...
CREATE INDEX idx_player_stats_player_id ON player_stats (player_id); CREATE INDEX idx_leaderboards_season_id ON leaderboards (season_id); CREATE INDEX idx_leaderboards_mmr_rating ON leaderboards (mmr_rating DESC); VACUUM ANALYZE leaderboards; VACUUM ANALYZE player_stats;
WITH ranked_leaderboards AS (SELECT season_id, player_id, mmr_rating, ROW_NUMBER() OVER (ORDER BY mmr_rating DESC) AS row_num FROM leaderboards WHERE season_id = 23 AND rank_tier = 'Gold') SELECT T1.season_id, T1.player_id, T1.mmr_rating + 10 AS new_mmr_rating FROM ranked_leaderboards AS T1 INNER JOIN player_stats AS T...
SQLite 3.45
SELECT s.tracking_num, pe.checkpoint, cr.base_rate FROM shipments s INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE pe.scan_time > '2022-01-01' AND s.status = 'in_transit' AND cr.zone_id = 5 AND s.weight_kg > 10
EXPLAIN QUERY PLAN SELECT s.tracking_num, pe.checkpoint, cr.base_rate FROM shipments s INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE pe.scan_time > '2022-01-01' AND s.status = 'in_transit' AND cr.zone_id = 5 AND s.weight_kg > 10
The query planner chose a sub-optimal route because it did not utilize a composite index on the join keys, resulting in a Cartesian product. This is evident from the lack of an index on the carrier_id and tracking_num columns in the shipments table, as well as the zone_id and carrier_id columns in the carrier_rates tab...
CREATE INDEX idx_shipments_carrier_id_tracking_num ON shipments (carrier_id, tracking_num); CREATE INDEX idx_carrier_rates_carrier_id_zone_id ON carrier_rates (carrier_id, zone_id); CREATE INDEX idx_parcel_events_tracking_num_scan_time ON parcel_events (tracking_num, scan_time);
SELECT s.tracking_num, pe.checkpoint, cr.base_rate FROM shipments s INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.scan_time > '2022-01-01' INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 WHERE s.status = 'in_transit' AND s.weight_kg > 10
ClickHouse 24.3
SELECT d.device_id, dt.val, dt.recorded_at FROM devices AS d INNER JOIN device_telematics AS dt ON d.device_id = dt.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01 00:00:00' AND d.region = 'North America' AND dt.firmware_v = '2.1.4'
{"tti": 12345, "roots": [{"id": 1, "type": "Aggregate", "rows": 1000000, "bytes": 100000000, "filters": [{"column": "dt.metric_type", "value": "temperature"}], "children": [{"id": 2, "type": "NestedLoopJoin", "rows": 10000000, "bytes": 1000000000, "join_type": "Inner", "join_condition": "d.device_id = dt.device_id", "c...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is defined as (device_id, metric_type, recorded_at), but the query is filtering on recorded_at, which is not the leading column of the primary key. This forces ClickHouse to perform a full partition decompression, lead...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at, device_id, metric_type); ALTER TABLE device_telematics ADD COLUMN firmware_v_int Int32; ALTER TABLE device_telematics ADD COLUMN region String;
SELECT d.device_id, dt.val, dt.recorded_at FROM devices AS d INNER JOIN device_telematics AS dt ON d.device_id = dt.device_id AND d.region = dt.region WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01 00:00:00' AND dt.firmware_v_int = 214
ClickHouse 24.3
SELECT p_adm.admission_id, l_ord.test_code, b_cod.charge_cents FROM patient_admissions AS p_adm INNER JOIN lab_orders AS l_ord ON p_adm.admission_id = l_ord.admission_id INNER JOIN billing_codes AS b_cod ON p_adm.admission_id = b_cod.admission_id WHERE p_adm.clinic_id = 145 AND l_ord.result_time > '2022-01-01' AND b_co...
{"stages":{"1":{"rows_read":"1212144","bytes_read":"96314640","filter":"(equals(p_adm.admission_id, l_ord.admission_id) AND equals(p_adm.admission_id, b_cod.admission_id) AND equals(p_adm.clinic_id, 145) AND greater(l_ord.result_time, 1640995200) AND equals(b_cod.icd10, 'M16.1'))","type":"NestedLoopJoin","input":"2"},"...
The query planner chose this sub-optimal route because it couldn't effectively utilize any indexes on the admission_id columns in the lab_orders and billing_codes tables due to the lack of indexes, leading to a full table scan for each join iteration. This decision is further exacerbated by the additional filter condit...
CREATE INDEX idx_lab_orders_admission_id ON lab_orders (admission_id); CREATE INDEX idx_billing_codes_admission_id ON billing_codes (admission_id); CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id);
SELECT p_adm.admission_id, l_ord.test_code, b_cod.charge_cents FROM patient_admissions AS p_adm INNER JOIN lab_orders AS l_ord ON p_adm.admission_id = l_ord.admission_id INNER JOIN billing_codes AS b_cod ON p_adm.admission_id = b_cod.admission_id WHERE p_adm.clinic_id = 145 AND l_ord.result_time > '2022-01-01' AND b_co...
CockroachDB v23.2
SELECT i.imp_id, c.campaign_id, ce.conversion_val FROM ad_impressions i JOIN click_events ce ON i.imp_id = ce.imp_id AND i.served_at > '2022-01-01' WHERE ce.clicked_at > '2022-01-15' AND i.campaign_id IN (SELECT campaign_id FROM campaigns WHERE daily_budget > 1000 AND status = 'active')
EXPLAIN (ANALYZE, BUFFERS) SELECT i.imp_id, c.campaign_id, ce.conversion_val FROM ad_impressions i JOIN click_events ce ON i.imp_id = ce.imp_id AND i.served_at > '2022-01-01' WHERE ce.clicked_at > '2022-01-15' AND i.campaign_id IN (SELECT campaign_id FROM campaigns WHERE daily_budget > 1000 AND status = 'active') -> Ne...
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned by the subquery, leading to a full table scan of the ad_impressions table, which has a large number of rows. Additionally, the join between ad_impressions and click_events is not indexed, resulting ...
CREATE INDEX idx_ad_impressions_imp_id ON ad_impressions (imp_id); CREATE INDEX idx_click_events_imp_id ON click_events (imp_id); CREATE INDEX idx_campaigns_campaign_id ON campaigns (campaign_id); VACUUM ANALYZE ad_impressions; VACUUM ANALYZE click_events; VACUUM ANALYZE campaigns;
SELECT i.imp_id, c.campaign_id, ce.conversion_val FROM ad_impressions i JOIN click_events ce ON i.imp_id = ce.imp_id AND i.served_at > '2022-01-01' WHERE ce.clicked_at > '2022-01-15' AND EXISTS (SELECT 1 FROM campaigns cm WHERE cm.campaign_id = i.campaign_id AND cm.daily_budget > 1000 AND cm.status = 'active')
PostgreSQL 16.2
SELECT dt.metric_type, dt.val, d.region FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.firmware_v = '2.1.4' AND d.status = 'active' AND dt.metric_type IN ('temperature', 'humidity', 'pressure') ORDER BY dt.recorded_at DESC LIMIT 10000 OFFSET 5000;
EXPLAIN (ANALYZE, BUFFERS) SELECT dt.metric_type, dt.val, d.region FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.firmware_v = '2.1.4' AND d.status = 'active' AND dt.metric_type IN ('temperature', 'humidity', 'pressure') ORDER BY dt.recorded_at DESC LIM...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is on the device_id column, but the query is filtering on the recorded_at column, which is not part of the primary key, resulting in a full partition decompression, and the firmware_v and metric_type columns are also n...
CREATE INDEX device_telematics_recorded_at_idx ON device_telematics (recorded_at); CREATE INDEX device_telematics_firmware_v_idx ON device_telematics (firmware_v); CREATE INDEX device_telematics_metric_type_idx ON device_telematics (metric_type); VACUUM ANALYZE device_telematics; ALTER TABLE device_telematics SET (para...
SELECT dt.metric_type, dt.val, d.region FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.firmware_v = '2.1.4' AND d.status = 'active' AND dt.metric_type IN ('temperature', 'humidity', 'pressure') ORDER BY dt.recorded_at DESC LIMIT 10000 OFFSET 0;
CockroachDB v23.2
SELECT l.order_id, p.admitted_at, b.charge_cents FROM lab_orders l JOIN patient_admissions p ON l.admission_id = p.admission_id JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.test_code = 'HB001' AND b.icd10 = 'R07.1' AND l.result_time > '2022-01-01 00:00:00' AND l.flagged = TRUE
EXPLAIN (ANALYZE, BUFFERS) SELECT l.order_id, p.admitted_at, b.charge_cents FROM lab_orders l JOIN patient_admissions p ON l.admission_id = p.admission_id JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.test_code = 'HB001' AND b.icd10 = 'R07.1' AND l.result_time > '2022-01-01 00:00...
The query planner chose this sub-optimal route because the table statistics for lab_orders, patient_admissions, and billing_codes are outdated, causing the planner to severely underestimate the intermediate row counts. This led to the selection of a hash join instead of a more efficient merge join or nested loop join. ...
CREATE INDEX idx_lab_orders_admission_id ON lab_orders (admission_id); CREATE INDEX idx_patient_admissions_admission_id ON patient_admissions (admission_id); CREATE INDEX idx_billing_codes_admission_id ON billing_codes (admission_id); CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code); CREATE INDEX idx_bil...
SELECT l.order_id, p.admitted_at, b.charge_cents FROM lab_orders l JOIN patient_admissions p ON l.admission_id = p.admission_id JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.clinic_id = 145 AND l.test_code = 'HB001' AND b.icd10 = 'R07.1' AND l.result_time > '2022-01-01 00:00:00' AND l.flagged = TRUE A...
SQLite 3.45
SELECT * FROM ad_impressions AS ai INNER JOIN click_events AS ce ON ai.imp_id = ce.imp_id WHERE ai.campaign_id = 12345 AND ce.conversion_val > 10 AND ai.user_segment LIKE '%{"age":25,"gender":"male"}%'
The execution plan for this query involves a full table scan of ad_impressions and click_events, resulting in a large number of rows being scanned. The WHERE clause filter on ai.campaign_id and ce.conversion_val is applied after the join, leading to a significant reduction in the number of rows. However, the LIKE opera...
The query planner chose this sub-optimal route because it prioritized the join operation between ad_impressions and click_events, which resulted in a large intermediate result set. The subsequent application of the WHERE clause filters reduced the number of rows, but the lack of an index on the JSONB payload extraction...
CREATE INDEX idx_ad_impressions_campaign_id ON ad_impressions (campaign_id); CREATE INDEX idx_click_events_conversion_val ON click_events (conversion_val); CREATE INDEX idx_ad_impressions_user_segment ON ad_impressions (user_segment);
SELECT * FROM ad_impressions AS ai INNER JOIN click_events AS ce ON ai.imp_id = ce.imp_id WHERE ai.campaign_id = 12345 AND ce.conversion_val > 10 AND json_extract(ai.user_segment, '$.age') = 25 AND json_extract(ai.user_segment, '$.gender') = 'male'
SQLite 3.45
SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id WHERE STRFTIME('%Y-%m-%d', isk.updated_at) > '2022-06-15' AND oi.unit_price > 19.99 AND isk.available_qty > 50
EXPLAIN QUERY PLAN SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id WHERE STRFTIME('%Y-%m-%d', isk.updated_at) > '2022-06-15' AND oi.unit_price > 19.99 AND isk.available_qty > 50
The query planner chose a sub-optimal route because the STRFTIME function wrapping the updated_at column in the WHERE clause prevents the optimizer from using an index range scan, resulting in a full table scan. This is due to the non-SARGable nature of the STRFTIME function, which prevents the optimizer from effective...
CREATE INDEX idx_updated_at ON inventory_stock (updated_at);
SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id WHERE isk.updated_at > '2022-06-15' AND oi.unit_price > 19.99 AND isk.available_qty > 50
SQLite 3.45
SELECT t1.device_id, t1.recorded_at, t2.region FROM device_telematics t1 INNER JOIN devices t2 ON t1.device_id = t2.device_id WHERE t1.recorded_at > '2022-07-15 14:30:00' AND t1.metric_type = 'temperature' AND t2.status = 'active' ORDER BY t1.recorded_at DESC LIMIT 1000;
EXPLAIN QUERY PLAN SELECT t1.device_id, t1.recorded_at, t2.region FROM device_telematics t1 INNER JOIN devices t2 ON t1.device_id = t2.device_id WHERE t1.recorded_at > '2022-07-15 14:30:00' AND t1.metric_type = 'temperature' AND t2.status = 'active' ORDER BY t1.recorded_at DESC LIMIT 1000; -- Output: SCAN TABLE device_...
The query planner chose a sub-optimal route because the recorded_at column in the device_telematics table is not indexed, resulting in a full table scan. Additionally, the join with the devices table is done using the integer primary key, but the status column is not indexed, leading to a search operation. The ORDER BY...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_devices_status ON devices (status); VACUUM ANALYZE;
SELECT t1.device_id, t1.recorded_at, t2.region FROM device_telematics t1 INNER JOIN devices t2 ON t1.device_id = t2.device_id AND t2.status = 'active' WHERE t1.recorded_at > '2022-07-15 14:30:00' AND t1.metric_type = 'temperature' ORDER BY t1.recorded_at DESC LIMIT 1000;
MySQL 8.0
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.status = 'in_transit' AND c.base_rate > 50 AND pe.scan_time > '2022-01-01'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "s", "access_type": "ALL", "rows": 10000, "filtered": 10, "table_scan": {"rows": 10000, "cost": 1000}}, "nested_loop": [ {"table": {"table_name": "pe", "access_type": "ALL", "rows": 50000, "filtered": 5, "using_join_buffer...
The query planner chose this sub-optimal route because it was unable to effectively utilize indexes due to the lack of a composite join key, resulting in a Cartesian product row multiplication and full table scans for all three tables, leading to an extremely high query cost and row count, thus causing the query to per...
CREATE INDEX idx_shipments_status ON shipments (status); CREATE INDEX idx_carrier_rates_base_rate ON carrier_rates (base_rate); CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num);
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.scan_time > '2022-01-01' INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.base_rate > 50 WHERE s.status = 'in_transit'