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
SQLite 3.45
SELECT ROW_NUMBER() OVER (PARTITION BY c.advertiser_id ORDER BY i.served_at DESC) AS row_num, c.campaign_id, i.imp_id, i.bid_cpm FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE c.daily_budget > 1000 AND i.user_segment = 'mobile' AND i.served_at > '2022-01-01'
EXPLAIN QUERY PLAN SELECT ROW_NUMBER() OVER (PARTITION BY c.advertiser_id ORDER BY i.served_at DESC) AS row_num, c.campaign_id, i.imp_id, i.bid_cpm FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE c.daily_budget > 1000 AND i.user_segment = 'mobile' AND i.served_at > '2022-01-01'; -- The pla...
The query planner chose this sub-optimal route because it prefers to perform a full table scan on ad_impressions and campaigns, rather than using an index, due to the lack of a suitable composite index on campaign_id and served_at. Additionally, the ROW_NUMBER() function requires a sort operation, which further exacerb...
CREATE INDEX idx_ad_impressions_campaign_id_served_at ON ad_impressions (campaign_id, served_at); CREATE INDEX idx_campaigns_daily_budget ON campaigns (daily_budget); VACUUM ANALYZE;
SELECT ROW_NUMBER() OVER (PARTITION BY c.advertiser_id ORDER BY i.served_at DESC) AS row_num, c.campaign_id, i.imp_id, i.bid_cpm FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE c.daily_budget > 1000 AND i.user_segment = 'mobile' AND i.served_at > '2022-01-01' AND i.campaign_id IN (SELECT c...
ClickHouse 24.3
SELECT pa.admission_id, l.lab_result, bc.charge_cents FROM patient_admissions pa INNER JOIN lab_orders l ON pa.admission_id = l.order_id INNER JOIN billing_codes bc ON pa.admission_id = bc.code_id WHERE pa.admitted_at > '2022-01-01' AND l.numeric_result > 10 AND bc.charge_cents > 500
EXPLAIN ANALYZE SELECT pa.admission_id, l.lab_result, bc.charge_cents FROM patient_admissions pa INNER JOIN lab_orders l ON pa.admission_id = l.order_id INNER JOIN billing_codes bc ON pa.admission_id = bc.code_id WHERE pa.admitted_at > '2022-01-01' AND l.numeric_result > 10 AND bc.charge_cents > 500; Result rows: 100 ...
The query planner chose the nested loop join algorithm because the join conditions are based on the admission_id column, which is not indexed in any of the tables. This results in a sequential scan of the lab_orders and billing_codes tables for each row in the patient_admissions table, leading to a high number of row c...
CREATE INDEX idx_patient_admissions_admission_id ON patient_admissions (admission_id); CREATE INDEX idx_lab_orders_order_id ON lab_orders (order_id); CREATE INDEX idx_billing_codes_code_id ON billing_codes (code_id);
SELECT pa.admission_id, l.lab_result, bc.charge_cents FROM patient_admissions pa INNER JOIN lab_orders l ON pa.admission_id = l.order_id INNER JOIN billing_codes bc ON pa.admission_id = bc.code_id WHERE pa.admitted_at > '2022-01-01' AND l.numeric_result > 10 AND bc.charge_cents > 500 AND pa.admission_id IN (SELECT admi...
ClickHouse 24.3
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s MERGE JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id MERGE JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.departed_at > '2022-01-01' AND s.status = 'in_transit' AND cr.zone_id = 5 AND pe.checkpoint = 'warehouse_scan'
{"trees":{"0":{"type":"MergeJoin","nodes":[{"type":"MergeJoin","nodes":[{"type":"MergeJoin","nodes":[{"type":"Filter","nodes":[{"type":"TableScan","nodes":[],"table":"shipments","filter":"departed_at > \u00272022-01-01\u0027 AND status = \u0027in_transit\u0027"}],"filter":"departed_at > \u00272022-01-01\u0027 AND statu...
The query planner chose this sub-optimal route because it attempted to perform a merge join operation without a suitable index on the departed_at column of the shipments table, resulting in an expensive memory sort operation to reorder the rows before joining with the other tables. Additionally, the lack of indexes on ...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id);
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.departed_at > '2022-01-01' AND s.status = 'in_transit' AND cr.zone_id = 5 AND pe.checkpoint = 'warehouse_scan' ORDER BY s...
SQLite 3.45
SELECT * FROM ad_impressions ai WHERE ai.campaign_id IN (SELECT campaign_id FROM campaigns c WHERE c.daily_budget > 500.0 AND c.status = 'active') AND ai.bid_cpm > 2.5 ORDER BY ROW_NUMBER() OVER (PARTITION BY ai.publisher_id ORDER BY ai.served_at DESC) LIMIT 100000;
EXPLAIN QUERY PLAN SELECT * FROM ad_impressions ai WHERE ai.campaign_id IN (SELECT campaign_id FROM campaigns c WHERE c.daily_budget > 500.0 AND c.status = 'active') AND ai.bid_cpm > 2.5 ORDER BY ROW_NUMBER() OVER (PARTITION BY ai.publisher_id ORDER BY ai.served_at DESC) LIMIT 100000; -- Returns a plan with a full tabl...
The query planner chose this sub-optimal route because it had to perform a full table scan of the ad_impressions table due to the absence of a matching composite index on (publisher_id, served_at) that could facilitate the efficient evaluation of the ROW_NUMBER() window function. Furthermore, the IN operator with a sub...
CREATE INDEX idx_ad_impressions_publisher_id_served_at ON ad_impressions (publisher_id, served_at); CREATE INDEX idx_campaigns_daily_budget_status ON campaigns (daily_budget, status); VACUUM;
WITH eligible_campaigns AS (SELECT campaign_id FROM campaigns c WHERE c.daily_budget > 500.0 AND c.status = 'active') SELECT * FROM ad_impressions ai WHERE ai.campaign_id IN (SELECT campaign_id FROM eligible_campaigns) AND ai.bid_cpm > 2.5 ORDER BY ROW_NUMBER() OVER (PARTITION BY ai.publisher_id ORDER BY ai.served_at D...
SQLite 3.45
SELECT T1.admission_id, T2.test_code, T3.charge_cents FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id WHERE T1.clinic_id = 42 AND T2.numeric_result > 10.5 AND T3.icd10 = 'R07.9' AND T1.admitted_at > '2022-01-01'
EXPLAIN QUERY PLAN SELECT T1.admission_id, T2.test_code, T3.charge_cents FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id WHERE T1.clinic_id = 42 AND T2.numeric_result > 10.5 AND T3.icd10 = 'R07.9' AND T1.admitted_a...
The query planner chose a sub-optimal route because the admission_id foreign key columns in the lab_orders and billing_codes tables are not indexed, resulting in a nested loop join with sequential scans, which leads to a significant performance degradation. The planner also failed to utilize any existing indexes on the...
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); CREATE INDEX idx_patient_admissions_admitted_at ON patient_admissions (admitted_at);
SELECT T1.admission_id, T2.test_code, T3.charge_cents FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id WHERE T1.clinic_id = 42 AND T2.numeric_result > 10.5 AND T3.icd10 = 'R07.9' AND T1.admitted_at > '2022-01-01' OR...
MariaDB 11.2
WITH ranked_matches AS (SELECT m.match_id, m.region, ROW_NUMBER() OVER (PARTITION BY m.region ORDER BY m.started_at DESC) AS row_num FROM match_sessions m JOIN player_stats ps ON m.match_id = ps.match_id WHERE ps.kills > 10 AND ps.score > 500) SELECT rm.match_id, rm.region, COUNT(DISTINCT ps.player_id) AS player_count ...
{"query_block": {"select_id": 1, "table": {"table_name": "derived_table", "access_type": "ALL", "rows": 10000, "filtered": 10, "table_filter": "100.00"}, "filter": "(row_num <= 10)", "nested_loop": [ {"table": {"table_name": "player_stats", "access_type": "ALL", "rows": 50000, "filtered": 50, "table_filter": "50.00"}, ...
The query planner chose this sub-optimal route because the materialized CTE (WITH clause) is preventing predicate pushdown into the partitioned match_sessions table. The CTE is being evaluated first, resulting in a derived table that is then joined with the player_stats table. This leads to a full table scan of the der...
CREATE INDEX idx_match_sessions_region ON match_sessions (region); CREATE INDEX idx_player_stats_match_id ON player_stats (match_id); CREATE INDEX idx_player_stats_ping_ms ON player_stats (ping_ms); ALTER TABLE match_sessions PARTITION BY LIST (region) (PARTITION p_region_1 VALUES IN ('US'), PARTITION p_region_2 VALUES...
SELECT m.match_id, m.region, COUNT(DISTINCT ps.player_id) AS player_count FROM match_sessions m JOIN player_stats ps ON m.match_id = ps.match_id WHERE ps.kills > 10 AND ps.score > 500 AND ps.ping_ms < 100 AND m.region IN ('US', 'EU', 'ASIA') GROUP BY m.match_id, m.region ORDER BY m.started_at DESC LIMIT 10;
ClickHouse 24.3
SELECT oi.item_id, oi.order_id, 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 WHERE DATE(isk.updated_at) > '2022-07-15' AND oi.quantity > 5 GROUP BY oi.item_id, oi.order_id ORDER BY total_revenue DESC...
{"trees":{"0":{"name":"Aggregate","keys":["item_id","order_id"],"funcs":[{"name":"sum","args":[{"name":"quantity"},{"name":"unit_price"}]}],"inputs":[{"name":"Merge","inputs":[{"name":"Filter","args":[{"name":"greater","args":[{"name":"updated_at"},"2022-07-15"]}],"inputs":[{"name":"Join","args":[],"inputs":[{"name":"T...
The query planner chose this sub-optimal route because the DATE function wrapping the updated_at column in the WHERE clause prevents the use of an index range scan, resulting in a full table scan of the inventory_stock table, which has a large number of rows. Additionally, the JOIN operation with the order_items table ...
CREATE INDEX idx_updated_at ON inventory_stock (updated_at);
SELECT oi.item_id, oi.order_id, 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 WHERE isk.updated_at > '2022-07-15 00:00:00' AND oi.quantity > 5 GROUP BY oi.item_id, oi.order_id ORDER BY total_revenue D...
MySQL 8.0
SELECT dt.device_id, AVG(dt.val) AS average_val FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01 00:00:00' AND d.region = 'North America' AND d.status = 'active'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 2345.67}, "table": {"table_name": "dt", "access_type": "range", "possible_keys": ["idx_device_id"], "key": "idx_device_id", "used_key_parts": ["device_id"], "key_length": "5", "rows": 12345, "filtered": 50.0, "index_cond": "dt.device_id = d.device_id", "attac...
The query planner chose this sub-optimal route because the skip index granularity on the device_telematics table is too broad, resulting in excessive granule loading. The metric_type column has a low cardinality, which means that the index on this column is not very selective, leading to a large number of rows being sc...
CREATE INDEX idx_device_id_recorded_at ON device_telematics (device_id, recorded_at); CREATE INDEX idx_devices_region_status ON devices (region, status); ALTER TABLE device_telematics ADD COLUMN metric_type_category INT; UPDATE device_telematics SET metric_type_category = CASE WHEN metric_type = 'temperature' THEN 1 WH...
SELECT dt.device_id, AVG(dt.val) AS average_val FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id AND d.region = 'North America' AND d.status = 'active' WHERE dt.metric_type_category = 1 AND dt.recorded_at > '2022-01-01 00:00:00'
SQLite 3.45
SELECT T1.season_id, T2.player_id, T2.mmr_rating FROM leaderboards AS T1 INNER JOIN (SELECT player_id, mmr_rating, ROW_NUMBER() OVER (ORDER BY mmr_rating DESC) AS row_num FROM leaderboards WHERE season_id = 15 AND mmr_rating > 1200) AS T2 ON T1.player_id = T2.player_id WHERE T1.season_id =15AND T2.row_num <= 100
EXPLAIN QUERY PLAN SELECT T1.season_id, T2.player_id, T2.mmr_rating FROM leaderboards AS T1 INNER JOIN (SELECT player_id, mmr_rating, ROW_NUMBER() OVER (ORDER BY mmr_rating DESC) AS row_num FROM leaderboards WHERE season_id = 15 AND mmr_rating > 1200) AS T2 ON T1.player_id = T2.player_id WHERE T1.season_id =15AND T2.ro...
The query planner chose this sub-optimal route because it attempted to satisfy the conditions in the WHERE clause first, which led to a full table scan on the leaderboards table. Additionally, the subquery with the ROW_NUMBER() function was not indexed, resulting in a high number of rows being scanned and sorted. This ...
CREATE INDEX idx_leaderboards_season_id ON leaderboards (season_id); CREATE INDEX idx_leaderboards_mmr_rating ON leaderboards (mmr_rating); VACUUM ANALYZE;
WITH ranked_leaderboards AS (SELECT player_id, mmr_rating, ROW_NUMBER() OVER (ORDER BY mmr_rating DESC) AS row_num FROM leaderboards WHERE season_id = 15 AND mmr_rating > 1200) SELECT T1.season_id, T2.player_id, T2.mmr_rating FROM leaderboards AS T1 INNER JOIN ranked_leaderboards AS T2 ON T1.player_id = T2.player_id WH...
ClickHouse 24.3
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.source_hub = 'NYC001' AND cr.zone_id = 5 AND pe.checkpoint = 'Arrival Scan'
{"plans": [{"nodes": [{"type": "Join", "est_rows": 1000000, "est_cost": 1000000.0, "rows": 1000000, "cost": 1000000.0, "node_id": 0, "node_type": "Join", "join_type": "Cartesian", "table_id": 0, "table_name": "shipments", "on_condition": "s.carrier_id = cr.carrier_id", "other_join_predicate": "s.tracking_num = pe.track...
The query planner chose this sub-optimal route because it failed to utilize a composite index on the join keys, resulting in a Cartesian product of rows from the shipments, carrier_rates, and parcel_events tables. This led to an exponential increase in the number of rows being joined, causing a significant performance ...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num);
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND s.source_hub = 'NYC001' INNER JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.checkpoint = 'Arrival Scan' WHERE cr.zone_id = 5
SQLite 3.45
SELECT T1.account_id, T1.amount, T2.user_id FROM ledger_entries AS T1 INNER JOIN accounts AS T2 ON T1.account_id = T2.id WHERE T1.currency = 'USD' AND T1.posting_date > '2022-01-01' AND T2.risk_tier = 3 AND T1.id = CAST('123e4567-e89b-12d3-a456-426655440000' AS TEXT)
EXPLAIN QUERY PLAN SELECT T1.account_id, T1.amount, T2.user_id FROM ledger_entries AS T1 INNER JOIN accounts AS T2 ON T1.account_id = T2.id WHERE T1.currency = 'USD' AND T1.posting_date > '2022-01-01' AND T2.risk_tier = 3 AND T1.id = CAST('123e4567-e89b-12d3-a456-426655440000' AS TEXT); -- The planner chooses a sub-opt...
The query planner chose this sub-optimal route because the implicit type coercion between the uuid literal and the INTEGER T1.id column forces a full table scan, as SQLite cannot effectively utilize the B-Tree index on T1.id with the coerced type, and thus the join with accounts is also not optimized, resulting in slow...
CREATE INDEX idx_ledger_entries_id ON ledger_entries (id); CREATE INDEX idx_accounts_risk_tier ON accounts (risk_tier);
SELECT T1.account_id, T1.amount, T2.user_id FROM ledger_entries AS T1 INNER JOIN accounts AS T2 ON T1.account_id = T2.id WHERE T1.currency = 'USD' AND T1.posting_date > '2022-01-01' AND T2.risk_tier = 3 AND T1.id = '123e4567-e89b-12d3-a456-426655440000';
MariaDB 11.2
SELECT ci.imp_id, ce.click_id, ca.advertiser_id, SUM(ce.conversion_val) AS total_conversion FROM ad_impressions ci JOIN click_events ce ON ci.imp_id = ce.imp_id JOIN campaigns ca ON ci.campaign_id = ca.campaign_id WHERE ci.served_at > '2022-01-01 00:00:00' AND ce.clicked_at < '2022-01-31 23:59:59' AND ca.daily_budget >...
EXPLAIN format JSON SELECT ci.imp_id, ce.click_id, ca.advertiser_id, SUM(ce.conversion_val) AS total_conversion FROM ad_impressions ci JOIN click_events ce ON ci.imp_id = ce.imp_id JOIN campaigns ca ON ci.campaign_id = ca.campaign_id WHERE ci.served_at > '2022-01-01 00:00:00' AND ce.clicked_at < '2022-01-31 23:59:59' A...
The query planner chose a sub-optimal route because it had to perform a full table scan on the ad_impressions table and then join it with the click_events table on the imp_id column, which is not indexed. This resulted in a huge number of rows being scanned and joined, leading to a significant performance bottleneck. F...
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); CREATE INDEX idx_ad_impressions_served_at ON ad_impressions (served_at); CREATE INDEX idx_click_events_clicked_at ON click_...
SELECT ci.imp_id, ce.click_id, ca.advertiser_id, SUM(ce.conversion_val) AS total_conversion FROM ad_impressions ci USE INDEX (idx_ad_impressions_imp_id, idx_ad_impressions_served_at) JOIN click_events ce USE INDEX (idx_click_events_imp_id, idx_click_events_clicked_at) ON ci.imp_id = ce.imp_id JOIN campaigns ca USE INDE...
MySQL 8.0
SELECT s.tracking_num, c.base_rate, pe.scan_time FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.departed_at > '2022-01-01 00:00:00' AND c.zone_id = 123 AND pe.checkpoint = 'DEL'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 23456.23}, "table": {"table_name": "s", "access_type": "ALL", "possible_keys": ["PRIMARY"], "key": null, "used_key_parts": null, "key_length": null, "rows": 100000, "filtered": 10.00, "extra": "Using filesort"}, "table": {"table_name": "pe", "access_type": "A...
The MySQL query optimizer chose a sub-optimal route because the departed_at column in the shipments table is not indexed, resulting in a full table scan and subsequent filesort operation. Additionally, the lack of an index on the tracking_num column in the parcel_events table led to a Block Nested Loop join, which is l...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); ALTER TABLE shipments ADD INDEX idx_shipments_tracking_num (tracking_num);
SELECT s.tracking_num, c.base_rate, pe.scan_time FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.checkpoint = 'DEL' JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.zone_id = 123 WHERE s.departed_at > '2022-01-01 00:00:00'
PostgreSQL 16.2
SELECT d.device_id, 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.recorded_at > '2022-01-01' AND d.region = 'North America' AND d.status = 'active'
EXPLAIN (ANALYZE, BUFFERS) SELECT d.device_id, 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.recorded_at > '2022-01-01' AND d.region = 'North America' AND d.status = 'active';
The query planner chose a sub-optimal route because the primary key of the device_telematics table is defined as (device_id, metric_type, recorded_at), but the query filters on recorded_at, which is the third column in the primary key, resulting in a leading timestamp mismatch that forces a full partition decompression...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_devices_region_status ON devices (region, status); ALTER TABLE device_telematics SET (parallel_workers = 4); VACUUM ANALYZE device_telematics; VACUUM ANALYZE devices;
SELECT d.device_id, 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.recorded_at > '2022-01-01' AND d.region = 'North America' AND d.status = 'active' ORDER BY dt.recorded_at;
MariaDB 11.2
SELECT a.id, a.workspace_id, b.user_id, b.role FROM audit_logs a JOIN workspace_users b ON a.workspace_id = b.workspace_id WHERE a.event_time > '2022-01-01' AND b.role = 'admin' ORDER BY a.event_time DESC LIMIT 10 OFFSET 1000000
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "431235.67"}, "table": {"table_name": "a", "access_type": "ALL", "rows": 1000211, "filtered": 10.0, "cost": 431235.67}, "extra": ["Using filesort"]}}
The query planner chose this sub-optimal route because the OFFSET clause is forcing the database to sequentially traverse over a million rows of historical audit records to find the desired 10 records, resulting in a full table scan and filesort operation, which is extremely inefficient and leads to high latency and re...
CREATE INDEX idx_audit_logs_workspace_id ON audit_logs (workspace_id); CREATE INDEX idx_workspace_users_workspace_id ON workspace_users (workspace_id);
SELECT a.id, a.workspace_id, b.user_id, b.role FROM (SELECT * FROM audit_logs WHERE event_time > '2022-01-01' ORDER BY event_time DESC LIMIT 1000010) a JOIN workspace_users b ON a.workspace_id = b.workspace_id WHERE b.role = 'admin' ORDER BY a.event_time DESC LIMIT 10
CockroachDB v23.2
SELECT d.device_id, avg(dt.val) AS avg_val FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-07-15' AND dt.recorded_at < '2022-07-16' AND d.region = 'North America' AND dt.metric_type = 'temperature' GROUP BY d.device_id ORDER BY avg_val DESC LIMIT 10;
EXPLAIN (ANALYZE, BUFFERS) SELECT d.device_id, avg(dt.val) AS avg_val FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-07-15' AND dt.recorded_at < '2022-07-16' AND d.region = 'North America' AND dt.metric_type = 'temperature' GROUP BY d.device_id ORDER BY avg_val DESC ...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is defined as (device_id, recorded_at, metric_type), but the query filters on recorded_at first, causing a full partition decompression. Additionally, the lack of an index on the devices table's region column results i...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at, device_id, metric_type); CREATE INDEX idx_devices_region ON devices (region); VACUUM ANALYZE device_telematics; VACUUM ANALYZE devices;
SELECT d.device_id, avg(dt.val) AS avg_val FROM device_telematics dt USE INDEX (idx_device_telematics_recorded_at) JOIN devices d USE INDEX (idx_devices_region) ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-07-15' AND dt.recorded_at < '2022-07-16' AND d.region = 'North America' AND dt.metric_type = 'temper...
ClickHouse 24.3
SELECT pa.admission_id, AVG(lo.numeric_result) AS avg_result FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 145 AND lo.test_code = 'GLUCOSE' AND lo.result_time > '2022-01-01' GROUP BY pa.admission_id HAVING COUNT(lo.order_id) > 5
{"stages":{"1":{"blocks":{"1":{"inputs":[],"where":"(`pa`.`clinic_id` = 145) AND (`lo`.`test_code` = 'GLUCOSE') AND (`lo`.`result_time` > '2022-01-01')","nodes":{"1":{"type":"HashJoin","EstimateRows":10000,"ReadRows":1000000,"ReadBytes":100000000}}}}}
The query planner chose this sub-optimal route because the table statistics for the patient_admissions and lab_orders tables are outdated, causing the planner to severely underestimate the intermediate row counts. The planner estimated only 10,000 rows would be returned from the join, but in reality, over 1 million row...
CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code); ALTER TABLE patient_admissions UPDATE COLUMN STATISTICS; ALTER TABLE lab_orders UPDATE COLUMN STATISTICS; OPTIMIZE TABLE patient_admissions FINAL; OPTIMIZE TABLE lab_orders FINAL;
SELECT pa.admission_id, AVG(lo.numeric_result) AS avg_result FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id AND lo.test_code = 'GLUCOSE' WHERE pa.clinic_id = 145 AND lo.result_time > '2022-01-01' GROUP BY pa.admission_id HAVING COUNT(lo.order_id) > 5
MariaDB 11.2
SELECT dt.metric_type, AVG(dt.val) AS average_value, COUNT(DISTINCT dt.device_id) AS unique_devices FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.recorded_at < '2022-01-31' AND d.region = 'North America' AND dt.firmware_v = '2.5.0' GROUP BY dt.metric_t...
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "34323.98"}, "table": {"table_name": "dt", "access_type": "range", "possible_keys": ["device_id"], "key": "device_id", "used_key_parts": ["device_id"], "key_length": "8", "rows": 1024201, "filtered": 33.33, "extra": ["Using where; Using filesort"]}, "table": ...
The query planner chose this sub-optimal route because it incorrectly estimated the cardinality of the join between device_telematics and devices, resulting in a large number of rows being processed and an inefficient GROUP BY operation that exhausted the available work_mem and spilled to disk. The planner also failed ...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_devices_region ON devices (region); ALTER TABLE device_telematics ADD COLUMN fleet_id INT; UPDATE device_telematics dt JOIN devices d ON dt.device_id = d.device_id SET dt.fleet_id = d.fleet_id; CREATE INDEX idx_device_te...
SELECT dt.metric_type, AVG(dt.val) AS average_value, COUNT(DISTINCT dt.device_id) AS unique_devices FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id AND dt.fleet_id = d.fleet_id WHERE dt.recorded_at >= '2022-01-01' AND dt.recorded_at < '2022-01-31' AND d.region = 'North America' AND dt.firmware_v ...
MariaDB 11.2
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.source_hub = 'New York' AND c.base_rate > 50.00 AND pe.scan_time > '2022-01-01'
EXPLAIN format=json SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.source_hub = 'New York' AND c.base_rate > 50.00 AND pe.scan_time > '2022-01-01'
The query planner chose this sub-optimal route because the join between shipments and parcel_events is performed using a non-indexed column (tracking_num), resulting in a Cartesian product row multiplication, which significantly increases the number of rows being joined and subsequently filtered. Furthermore, the join ...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id);
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND s.source_hub = 'New York' JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.base_rate > 50.00 WHERE pe.scan_time > '2022-01-01'
ClickHouse 24.3
SELECT t2.carrier_id, SUM(t1.weight_kg * t2.base_rate) AS total_revenue FROM shipments t1 INNER JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id WHERE t1.departed_at > '2022-01-01' AND t1.status = 'delivered' AND t2.zone_id = 5 GROUP BY t2.carrier_id ORDER BY total_revenue DESC LIMIT 10;
{"stages":{"1":{"name":"Aggregate","threads":"all","memory":"332.1 MB","bytes_read":"12.21 GB","bytes_written":"0","filter":"0.245","input_rows":"10.23 M","input_bytes":"11.56 GB","output_rows":"1.02 M"},"2":{"name":"HashAggregate","spilled." "true","peak_memory_usage":"431.15 MB"}}}
The query planner chose to use a Hash Aggregate due to the presence of a GROUP BY clause. However, the planner underestimated the amount of memory required for the aggregation, resulting in the operation spilling to temporary disk files. This is likely because the statistics on the shipments table are outdated, leading...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id);
SELECT t2.carrier_id, SUM(t1.weight_kg * t2.base_rate) AS total_revenue FROM shipments t1 INNER JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id AND t2.zone_id = 5 WHERE t1.departed_at > '2022-01-01' AND t1.status = 'delivered' GROUP BY t2.carrier_id ORDER BY total_revenue DESC LIMIT 10;
SQLite 3.45
SELECT SUM(CASE WHEN T1.status = 'in_transit' THEN 1 ELSE 0 END) AS in_transit_count, SUM(CASE WHEN T1.status = 'delivered' THEN 1 ELSE 0 END) AS delivered_count FROM shipments T1 INNER JOIN parcel_events T2 ON T1.tracking_num = T2.tracking_num WHERE T2.scan_time > '2022-01-01' AND T1.carrier_id = 123 AND T1.source_hub...
EXPLAIN QUERY PLAN SELECT SUM(CASE WHEN T1.status = 'in_transit' THEN 1 ELSE 0 END) AS in_transit_count, SUM(CASE WHEN T1.status = 'delivered' THEN 1 ELSE 0 END) AS delivered_count FROM shipments T1 INNER JOIN parcel_events T2 ON T1.tracking_num = T2.tracking_num WHERE T2.scan_time > '2022-01-01' AND T1.carrier_id = 12...
The query planner chose to use a hash aggregate operation which spilled to temporary disk files due to the large number of rows being processed and the limited amount of memory available, this is evident from the EXPLAIN QUERY PLAN output, the planner is unable to efficiently utilize the available indexes on the shipme...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id); CREATE INDEX idx_shipments_source_hub ON shipments (source_hub); CREATE INDEX idx_parcel_events_scan_time ON parcel_events (scan_time); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num);
SELECT SUM(CASE WHEN T1.status = 'in_transit' THEN 1 ELSE 0 END) AS in_transit_count, SUM(CASE WHEN T1.status = 'delivered' THEN 1 ELSE 0 END) AS delivered_count FROM shipments T1 INNER JOIN parcel_events T2 ON T1.tracking_num = T2.tracking_num AND T2.scan_time > '2022-01-01' WHERE T1.carrier_id = 123 AND T1.source_hub...
MariaDB 11.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 > 500 AND ps.ping_ms < 100
{"query_block": {"select_id": 1, "table": {"table_name": "ps", "access_type": "ALL", "rows": 100000, "filtered": 10, "extra": "Using filesort"}}}
The query planner chose a full table scan on the player_stats table because the OR condition across unindexed columns kills and score prevents the optimizer from using an index, even if one existed on either column individually, resulting in a costly filesort operation to satisfy the filtering conditions.
CREATE INDEX idx_player_stats_kills_score ON player_stats (kills, score);
SELECT ps.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms FROM player_stats ps WHERE ps.kills > 15 AND ps.score > 500 AND ps.ping_ms < 100 UNION ALL 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 > 500 AND ps.ping_ms < 100 AND (ps.kills <= 15...
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.id LIMIT 10 OFFSET 1000000
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 234567.89}, "table": {"table_name": "a", "access_type": "ALL", "possible_keys": ["workspace_id"], "key": null, "used_key_parts": null, "key_length": null, "ref": null, "rows": 1234567, "filtered": 10.00, "Extra": "Using filesort"}}}
The query planner chose this sub-optimal route because it had to perform a sequential traversal of the entire audit_logs table to satisfy the large OFFSET value of 1000000, resulting in a full table scan and filesort operation. This was likely due to the lack of an effective index on the event_time column, causing the ...
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 created_at timestamp default current_timestamp; VACUUM ANALYZE;
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 LIMIT 10 OFFSET 1000000
CockroachDB v23.2
SELECT pa.admission_id, AVG(lo.numeric_result) AS avg_result FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 421 AND lo.test_code = 'GLUC' AND lo.flagged = TRUE AND lo.result_time > '2022-01-01 00:00:00' GROUP BY pa.admission_id HAVING AVG(lo.numeric_result) > 150
EXPLAIN (ANALYZE, BUFFERS) SELECT pa.admission_id, AVG(lo.numeric_result) AS avg_result FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 421 AND lo.test_code = 'GLUC' AND lo.flagged = TRUE AND lo.result_time > '2022-01-01 00:00:00' GROUP BY pa.admission_id HAVING A...
The query planner chose this sub-optimal route because the table statistics for patient_admissions and lab_orders are outdated, causing the planner to severely underestimate the intermediate row counts. This led to the selection of a nested loop join instead of a more efficient hash join or merge join. Additionally, th...
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_lab_orders_test_code ON lab_orders (test_code); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders;
SELECT pa.admission_id, AVG(lo.numeric_result) AS avg_result FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id AND lo.test_code = 'GLUC' AND lo.flagged = TRUE AND lo.result_time > '2022-01-01 00:00:00' WHERE pa.clinic_id = 421 GROUP BY pa.admission_id HAVING AVG(lo.numeric_result) > 150
ClickHouse 24.3
SELECT oi.item_id, oi.sku_id, 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 WHERE oi.unit_price > 19.99 AND isk.available_qty > 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 1...
{"type": "Aggregate", "keys": ["item_id", "sku_id"], "funcs": [{"name": "sum", "args": [{"name": "quantity", "type": "UInt32"}, {"name": "unit_price", "type": "Float32"}]}], "filter": {"type": "Filter", "filter": {"type": "And", "filters": [{"type": "Greater", "value": {"type": "Float32", "value": 19.99}}, {"type": "Gr...
The query planner chose this sub-optimal route because it did not have a suitable index on the order_items table to cover the join and filter conditions, resulting in excessive heap fetches on the wide table. The missing covering index (INCLUDE clause) on the sku_id and warehouse_id columns led to a full table scan, wh...
CREATE INDEX idx_order_items_sku_warehouse ON order_items (sku_id, warehouse_id) INCLUDE (item_id, quantity, unit_price);
SELECT oi.item_id, oi.sku_id, 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 WHERE oi.unit_price > 19.99 AND isk.available_qty > 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 1...
PostgreSQL 16.2
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = TRUE AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' LIMIT 100;
EXPLAIN (ANALYZE, BUFFERS) SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = TRUE AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' LIMIT 100; -> Limit (cost=2345.67..2345.68 rows=1 width=44) (actual time=235.123....
The query planner chose this sub-optimal route because it had to perform a sequential scan on the subscriptions table due to the missing partial index on the is_active column, which is filtered to only include rows where is_active is TRUE. This resulted in a full table scan, which is inefficient. Additionally, the plan...
CREATE INDEX subscriptions_is_active_idx ON subscriptions (is_active) WHERE is_active = TRUE; ALTER TABLE subscriptions SET (parallel_workers = 4); VACUUM ANALYZE subscriptions;
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = TRUE AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND su.id IN (SELECT id FROM subscriptions WHERE is_active = TRUE) LIMIT 100;
SQLite 3.45
WITH ranked_players AS (SELECT T1.player_id, T1.mmr_rating, ROW_NUMBER() OVER (PARTITION BY T1.season_id ORDER BY T1.mmr_rating DESC) AS rank FROM leaderboards T1 INNER JOIN player_stats T2 ON T1.player_id = T2.player_id WHERE T2.match_id IN (SELECT match_id FROM match_sessions WHERE region = 'US' AND game_mode = 'Rank...
EXPLAIN QUERY PLAN SELECT T1.player_id, T1.mmr_rating, T1.rank FROM ranked_players T1 INNER JOIN player_stats T2 ON T1.player_id = T2.player_id WHERE T2.kills > 10 AND T2.score > 1000; -- Output: MATERIALIZE ranked_players, SCAN TABLE player_stats, SEARCH TABLE leaderboards USING INDEX sqlite_autoindex_leaderboards_1
The query planner chose this sub-optimal route because it failed to push down the filter predicates into the materialized CTE, resulting in a full table scan of the player_stats table. This was likely due to the lack of statistics on the joined tables, causing the planner to overestimate the cost of the join operation....
CREATE INDEX idx_match_sessions_match_id ON match_sessions (match_id); CREATE INDEX idx_player_stats_player_id ON player_stats (player_id); CREATE INDEX idx_leaderboards_player_id ON leaderboards (player_id);
SELECT T1.player_id, T1.mmr_rating, ROW_NUMBER() OVER (PARTITION BY T1.season_id ORDER BY T1.mmr_rating DESC) AS rank FROM leaderboards T1 INNER JOIN player_stats T2 ON T1.player_id = T2.player_id INNER JOIN match_sessions T3 ON T2.match_id = T3.match_id WHERE T3.region = 'US' AND T3.game_mode = 'Ranked' AND T3.started...
SQLite 3.45
SELECT T1.patient_id, SUM(T3.charge_cents) AS total_charges FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id WHERE T2.test_code = 'ABC123' AND T3.icd10 = 'I10' AND T1.admitted_at > '2022-01-01' AND T1.discharge_date...
EXPLAIN QUERY PLAN SELECT T1.patient_id, SUM(T3.charge_cents) AS total_charges FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id WHERE T2.test_code = 'ABC123' AND T3.icd10 = 'I10' AND T1.admitted_at > '2022-01-01' AN...
The query planner chose a sub-optimal route because the table statistics are outdated, causing it to severely underestimate the intermediate row counts. Specifically, the planner assumed a uniform distribution of test codes in the lab_orders table, resulting in an inaccurate estimate of the number of rows that would ma...
CREATE INDEX idx_patient_admissions_admission_id ON patient_admissions (admission_id); CREATE INDEX idx_lab_orders_admission_id_test_code ON lab_orders (admission_id, test_code); CREATE INDEX idx_billing_codes_admission_id_icd10 ON billing_codes (admission_id, icd10); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE l...
SELECT T1.patient_id, SUM(T3.charge_cents) AS total_charges FROM patient_admissions T1 INNER JOIN lab_orders T2 ON T1.admission_id = T2.admission_id AND T2.test_code = 'ABC123' INNER JOIN billing_codes T3 ON T1.admission_id = T3.admission_id AND T3.icd10 = 'I10' WHERE T1.admitted_at > '2022-01-01' AND T1.discharge_date...
SQLite 3.45
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND user_segment IN ('segment_1', 'segment_7') AND served_at > '2022-01-01 00:00:00'
EXPLAIN QUERY PLAN SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND user_segment IN ('segment_1', 'segment_7') AND served_at > '2022-01-01 00:00:00'; -- Output: The query planner chooses a full table scan due to the...
The query planner chose this sub-optimal route because it couldn't find a suitable composite index to satisfy the conditions specified in the WHERE clause, combined with the need to partition and order the results by the publisher_id and served_at columns, respectively. As a result, it resorted to scanning the entire t...
CREATE INDEX idx_ad_impressions_publisher_id_served_at ON ad_impressions (publisher_id, served_at DESC); CREATE INDEX idx_ad_impressions_bid_cpm_user_segment ON ad_impressions (bid_cpm, user_segment); VACUUM ANALYZE;
WITH ranked_impressions AS (SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND user_segment IN ('segment_1', 'segment_7') AND served_at > '2022-01-01 00:00:00') SELECT * FROM ranked_impressions WHERE row_num <= 100;
CockroachDB v23.2
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE campaign_id IN (123, 456) AND bid_cpm > 5.00 AND served_at > '2022-01-01' LIMIT 100000;
EXPLAIN (ANALYZE, BUFFERS) SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE campaign_id IN (123, 456) AND bid_cpm > 5.00 AND served_at > '2022-01-01' LIMIT 100000; -> Row Count: 100000, Total Time: 2345.12ms, CPU Time: 1234.56ms, Buf...
The query planner chose this sub-optimal route because it attempted to leverage the existing primary key index on the ad_impressions table, but the added filter conditions and window function necessitate a full table scan and subsequent sorting operation, which results in excessive disk I/O and computational overhead, ...
CREATE INDEX idx_ad_impressions_pub_cam_serv ON ad_impressions (publisher_id, campaign_id, served_at); ALTER TABLE ad_impressions SET STATISTICS 1000; VACUUM ANALYZE ad_impressions;
WITH ranked_imps AS (SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE campaign_id IN (123, 456) AND bid_cpm > 5.00 AND served_at > '2022-01-01') SELECT * FROM ranked_imps WHERE row_num <= 100000;
PostgreSQL 16.2
SELECT SUM(le.amount) AS total_amount FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 12345 AND le.posting_date BETWEEN '2022-01-01' AND '2022-12-31' AND a.risk_tier = 'high'
EXPLAIN (ANALYZE, BUFFERS) SELECT SUM(le.amount) AS total_amount FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 12345 AND le.posting_date BETWEEN '2022-01-01' AND '2022-12-31' AND a.risk_tier = 'high'; --> Seq Scan on ledger_entries le (cost=0.00..1556.23 rows=103 width=24) ...
The query planner chose this sub-optimal route because it lacks a composite index on the ledger_entries table for the columns account_id and posting_date. As a result, the planner opted for a full table scan of the ledger_entries table, which is the most expensive operation in terms of I/O and CPU resources. Furthermor...
CREATE INDEX idx_ledger_entries_account_id_posting_date ON ledger_entries (account_id, posting_date);
SELECT SUM(le.amount) AS total_amount FROM ledger_entries le INNER JOIN accounts a ON le.account_id = a.id WHERE le.account_id = 12345 AND le.posting_date BETWEEN '2022-01-01' AND '2022-12-31' AND a.risk_tier = 'high'
MySQL 8.0
SELECT * FROM `t1_patient_admissions` AS `pa` JOIN `t2_lab_orders` AS `lo` ON `pa`.`admission_id` = `lo`.`admission_id` WHERE `lo`.`test_code` LIKE '%AB12%' AND `pa`.`admitted_at` > '2020-01-01' AND `pa`.`clinic_id` IN (101, 102, 103);
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 3456.23}, "table": {"table_name": "lo", "access_type": "ALL", "possible_keys": ["admission_id"], "key": null, "key_len": null, "ref": null, "rows": 12000, "filtered": 10.00, "Extra": "Using where; Using filesort"}}}
The MySQL query planner chose a sub-optimal full table scan route because the leading wildcard in the LIKE clause (`'%AB12%'`) disables the use of the B-Tree index on the `test_code` column, forcing the optimizer to scan the entire table and apply the filter condition afterwards. Furthermore, the join operation with th...
CREATE INDEX idx_lab_orders_test_code ON t2_lab_orders (test_code); CREATE INDEX idx_patient_admissions_admission_id ON t1_patient_admissions (admission_id); ALTER TABLE t2_lab_orders ADD INDEX idx_admission_id (admission_id);
SELECT * FROM `t1_patient_admissions` AS `pa` JOIN `t2_lab_orders` AS `lo` ON `pa`.`admission_id` = `lo`.`admission_id` WHERE `lo`.`test_code` LIKE 'AB12%' AND `pa`.`admitted_at` > '2020-01-01' AND `pa`.`clinic_id` IN (101, 102, 103);
CockroachDB v23.2
SELECT SUM(b.charge_cents) AS total_charges FROM patient_admissions p JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.admitted_at > '2022-01-01' AND b.icd10 = 'M16.1' AND p.clinic_id = 5
EXPLAIN (ANALYZE, BUFFERS) SELECT SUM(b.charge_cents) AS total_charges FROM patient_admissions p JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.admitted_at > '2022-01-01' AND b.icd10 = 'M16.1' AND p.clinic_id = 5; => Gather (cost=10000000000.00..10000000000.00 rows=100 width=64) -> HashAggrega...
The query planner chose this sub-optimal route because the table statistics for patient_admissions and billing_codes are outdated, causing the planner to severely underestimate the intermediate row counts. Specifically, the planner estimated 100 rows for the Seq Scan on patient_admissions, when in reality, there are mi...
CREATE INDEX idx_admitted_at_clinic_id ON patient_admissions (admitted_at, clinic_id); CREATE INDEX idx_admission_id_icd10 ON billing_codes (admission_id, icd10); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE billing_codes;
SELECT SUM(b.charge_cents) AS total_charges FROM patient_admissions p JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.admitted_at > '2022-01-01' AND b.icd10 = 'M16.1' AND p.clinic_id = 5 AND p.admitted_at IS NOT NULL AND b.admission_id IS NOT NULL;
CockroachDB v23.2
SELECT d.device_id, SUM(dt.val) AS total_val, COUNT(ge.id) AS geofence_count FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.recorded_at < '2022-01-31 23:59:59' AND d.status = 'active' AND g...
{"planning_time":10.123,"execution_time":1234.567,"rows":100,"bytes":12345,"plan":{"node_id":1,"node_type":"sort","node_stats":{"rows":100,"bytes":12345},"plan_nodes":[{"node_id":2,"node_type":"hash join","node_stats":{"rows":100000,"bytes":12345678},"plan_nodes":[{"node_id":3,"node_type":"scan","node_stats":{"rows":10...
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 filters on recorded_at first, which leads to a full partition decompression, resulting in a significant increase in execution time. Additionally, the j...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_devices_status ON devices (status); CREATE INDEX idx_geofence_events_logged_at ON geofence_events (logged_at); ALTER TABLE device_telematics SET PRIMARY KEY (recorded_at, device_id, metric_type); VACUUM ANALYZE device_te...
SELECT d.device_id, SUM(dt.val) AS total_val, COUNT(ge.id) AS geofence_count FROM device_telematics dt USE INDEX (idx_device_telematics_recorded_at) JOIN devices d ON dt.device_id = d.device_id JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.recorded_at < '2022...
ClickHouse 24.3
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.source_hub = 'New York' AND cr.zone_id = 5 AND pe.scan_time > '2022-01-01'
EXPLAIN (ANALYZE, BUFFERS) SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.source_hub = 'New York' AND cr.zone_id = 5 AND pe.scan_time > '2022-01-01'; -- The execution plan indicat...
The query planner chose this sub-optimal route because the join operation between the shipments, parcel_events, and carrier_rates tables is performed without a composite join key, leading to a Cartesian product. This results in an explosion of row counts, causing performance degradation. Furthermore, the lack of indexi...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id);
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND s.source_hub = 'New York' JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 WHERE pe.scan_time > '2022-01-01';
PostgreSQL 16.2
SELECT s.tracking_num, SUM(cr.base_rate * 1.2) AS total_cost FROM shipments s JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND s.source_hub = cr.zone_id WHERE s.status = 'in_transit' AND cr.weight_kg > 50 AND s.departed_at > '2022-01-01' GROUP BY s.tracking_num HAVING SUM(cr.base_rate) > 1000
EXPLAIN (ANALYZE, BUFFERS) SELECT s.tracking_num, SUM(cr.base_rate * 1.2) AS total_cost FROM shipments s JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND s.source_hub = cr.zone_id WHERE s.status = 'in_transit' AND cr.weight_kg > 50 AND s.departed_at > '2022-01-01' GROUP BY s.tracking_num HAVING SUM(cr.base_rat...
The query planner chose this sub-optimal route because the available work_mem was too small to hold the entire hash aggregate in memory, causing it to spill to temporary disk files, resulting in significant performance degradation. The planner also decided to perform a sequential scan on the shipments table due to the ...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_shipments_status ON shipments (status); CREATE INDEX idx_carrier_rates_weight_kg ON carrier_rates (weight_kg); ALTER TABLE shipments SET (parallel_workers = 4); VACUUM ANALYZE shipments; VACUUM ANALYZE carrier_rates;
WITH ranked_shipments AS (SELECT tracking_num, carrier_id, source_hub, departed_at, status, ROW_NUMBER() OVER (PARTITION BY tracking_num ORDER BY departed_at DESC) AS row_num FROM shipments WHERE status = 'in_transit' AND departed_at > '2022-01-01') SELECT rs.tracking_num, SUM(cr.base_rate * 1.2) AS total_cost FROM ran...
MariaDB 11.2
SELECT i.imp_id, c.campaign_id, JSON_EXTRACT(i.ad_data, '$.targeting.user_segment') AS user_segment FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE JSON_EXTRACT(i.ad_data, '$.targeting.user_segment') = 'interest_sports_123' AND c.daily_budget > 500.0 AND i.served_at > '2022-01-01 00:00:00'...
{"type": "NESTED LOOP", "table": "ad_impressions", "rows": 100000, "filtered": 0.01, "using": "where", "nested_loop": [{"table": "campaigns", "rows": 5000, "filtered": 0.1, "using": "where"}]}
The query planner chose this sub-optimal route because the JSON_EXTRACT function inside the WHERE filter is not leveraging any index, resulting in a full table scan. Furthermore, the lack of a GIN expression index on the ad_data column prevents the optimizer from efficiently filtering the rows, leading to a significant...
CREATE INDEX idx_ad_impressions_ad_data ON ad_impressions ((JSON_EXTRACT(ad_data, '$.targeting.user_segment'))); CREATE INDEX idx_campaigns_daily_budget ON campaigns (daily_budget);
SELECT i.imp_id, c.campaign_id, JSON_EXTRACT(i.ad_data, '$.targeting.user_segment') AS user_segment FROM ad_impressions i JOIN campaigns c ON i.campaign_id = c.campaign_id WHERE i.imp_id IN (SELECT imp_id FROM ad_impressions WHERE JSON_EXTRACT(ad_data, '$.targeting.user_segment') = 'interest_sports_123') AND c.daily_bu...
PostgreSQL 16.2
SELECT dt.device_id, dt.metric_type, dt.val, dt.recorded_at, d.fleet_id FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.recorded_at < '2022-01-31 23:59:59' AND d.region = 'North America' AND dt.metric_type IN ('temperature', 'humidity', 'pressur...
EXPLAIN (ANALYZE, BUFFERS) SELECT dt.device_id, dt.metric_type, dt.val, dt.recorded_at, d.fleet_id FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.recorded_at < '2022-01-31 23:59:59' AND d.region = 'North America' AND dt.metric_type IN ('tempera...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is not properly utilized due to the leading timestamp mismatch, resulting in a full partition decompression. Additionally, the join operation is performed using a nested loop, which can be inefficient for large dataset...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_devices_region ON devices (region); VACUUM ANALYZE device_telematics; VACUUM ANALYZE devices;
SELECT dt.device_id, dt.metric_type, dt.val, dt.recorded_at, d.fleet_id FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id AND d.region = 'North America' WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.recorded_at < '2022-01-31 23:59:59' AND dt.metric_type IN ('temperature', 'humidity', 'pressur...
MySQL 8.0
SELECT pa.admission_id, lo.test_code, bc.icd10 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 pa.clinic_id = 421 AND lo.flagged = 1 AND bc.charge_cents > 1500 AND lo.result_time > '2022-01-01 00:00:00' AND pa.discharge_...
{"query_block": {"select_id": 1, "table": {"table_name": "pa", "access_type": "ALL", "rows": 115321, "filtered": 10.0, "extra": ""}, "table": {"table_name": "lo", "access_type": "ALL", "rows": 500654, "filtered": 20.0, "extra": "Using where; Using join buffer (Block Nested Loop)"}, "table": {"table_name": "bc", "access...
The query planner chose this sub-optimal route because the table statistics are outdated, causing it to severely underestimate the intermediate row counts. Specifically, the planner estimated that the join between patient_admissions and lab_orders would produce only 1,153 rows, when in reality it produces over 50,000 r...
ANALYZE TABLE patient_admissions; ANALYZE TABLE lab_orders; ANALYZE TABLE billing_codes; 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);
SELECT pa.admission_id, lo.test_code, bc.icd10 FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id AND lo.result_time > '2022-01-01 00:00:00' AND lo.flagged = 1 JOIN billing_codes bc ON pa.admission_id = bc.admission_id AND bc.charge_cents > 1500 WHERE pa.clinic_id = 421 AND pa.discharge_...
CockroachDB v23.2
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2024-01-01'
EXPLAIN (ANALYZE, BUFFERS) SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2024-01-01'; Query Plan: -> Filter: is_active = true AND ro...
The query planner chose to perform a sequential scan on the subscriptions table because there is no index on the is_active column, which is used as a filter condition in the query. Additionally, the join condition on workspace_id does not have an index, leading to another sequential scan on the workspace_users table. T...
CREATE INDEX idx_subscriptions_is_active ON subscriptions (is_active); CREATE INDEX idx_workspace_users_role ON workspace_users (role); CREATE INDEX idx_subscriptions_renewal_date ON subscriptions (renewal_date); CREATE INDEX idx_workspace_users_invited_at ON workspace_users (invited_at); VACUUM ANALYZE subscriptions; ...
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2024-01-01' ORDER BY su.renewal_date
MariaDB 11.2
SELECT d.device_id, d.fleet_id, dt.val, dt.recorded_at FROM devices d JOIN device_telematics dt ON d.device_id = dt.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND d.region = 'North America' AND dt.recorded_at > '2022-01-01'
EXPLAIN format=json SELECT d.device_id, d.fleet_id, dt.val, dt.recorded_at FROM devices d JOIN device_telematics dt ON d.device_id = dt.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND d.region = 'North America' AND dt.recorded_at > '2022-01-01'
The query planner chose this sub-optimal route because the join order was not ideal, resulting in a full table scan on the device_telematics table. Additionally, the filter conditions on the device_telematics table were not effectively utilizing the available indexes, leading to excessive granule loading. The lack of a...
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 /*+ JOIN_ORDER(d, dt) */ d.device_id, d.fleet_id, dt.val, dt.recorded_at FROM devices d JOIN device_telematics dt ON d.device_id = dt.device_id AND dt.metric_type = 'temperature' WHERE dt.val > 50 AND d.region = 'North America' AND dt.recorded_at > '2022-01-01'
SQLite 3.45
SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions AS p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 10.99 AND isk.available_qty > 50 AND p.valid_from < '2022-07-15' AND p.valid_until > '2022-07-15'
EXPLAIN QUERY PLAN SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions AS p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 10.99 AND isk.available_qty > 50 AND p.valid_from < '2022-07-15' AND p.valid_until > '2022-07-15'...
The query planner chose this sub-optimal route because it attempted to utilize the existing indexes on the join columns, but the additional filter conditions on unit_price, available_qty, valid_from, and valid_until led to a full table scan, resulting in a significant increase in execution time. Furthermore, the lack o...
CREATE INDEX idx_order_items_unit_price ON order_items (unit_price); CREATE INDEX idx_inventory_stock_available_qty ON inventory_stock (available_qty); CREATE INDEX idx_promotions_valid_from ON promotions (valid_from); CREATE INDEX idx_promotions_valid_until ON promotions (valid_until); VACUUM ANALYZE;
SELECT * FROM order_items AS oi INNER JOIN inventory_stock AS isk ON oi.sku_id = isk.sku_id AND oi.warehouse_id = isk.warehouse_id INNER JOIN promotions AS p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 10.99 AND isk.available_qty > 50 AND p.valid_from < '2022-07-15' AND p.valid_until > '2022-07-15' ORDER BY oi.unit_p...
MariaDB 11.2
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.departed_at > '2022-01-01' AND s.status = 'IN_TRANSIT' AND pe.checkpoint = 'HUB_SCAN' AND cr.zone_id = 3 AND cr.weight_kg > 10
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "s", "access_type": "ALL", "rows": "100000", "filtered": "10.00", "index_condition": null, "extra": "Using filesort"}, "table": {"table_name": "pe", "access_type": "ALL", "rows": "500000", "filtered": "10.00", "index_condi...
The query planner chose this sub-optimal route because it had to perform a merge join on the shipments and parcel_events tables, which led to an expensive memory sort operation on the unindexed departed_at column. Additionally, the lack of indexes on the carrier_id and zone_id columns forced the optimizer to use a bloc...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); ALTER TABLE shipments ADD INDEX idx_shipments_status (status);
SELECT s.tracking_num, cr.base_rate, pe.scan_time FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.checkpoint = 'HUB_SCAN' JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 3 AND cr.weight_kg > 10 WHERE s.departed_at > '2022-01-01' AND s.status = 'IN_TRANSIT'
MariaDB 11.2
SELECT t1.admission_id, t2.test_code FROM pa_adm AS t1 INNER JOIN lb_ord AS t2 ON t1.admission_id = t2.admission_id WHERE t2.test_code ILIKE '%oxy%' AND t1.admitted_at > '2022-01-01' AND t1.clinic_id = 145
EXPLAIN format=json SELECT t1.admission_id, t2.test_code FROM pa_adm AS t1 INNER JOIN lb_ord AS t2 ON t1.admission_id = t2.admission_id WHERE t2.test_code ILIKE '%oxy%' AND t1.admitted_at > '2022-01-01' AND t1.clinic_id = 145
The query planner chose a sub-optimal route because the leading wildcard search in the ILIKE operator prevents the optimizer from effectively utilizing the B-Tree index on the test_code column, leading to a full table scan of the lb_ord table. Additionally, the join order and the lack of indexes on the admitted_at and ...
CREATE INDEX idx_lb_ord_test_code ON lb_ord (test_code); CREATE INDEX idx_pa_adm_admitted_at ON pa_adm (admitted_at); CREATE INDEX idx_pa_adm_clinic_id ON pa_adm (clinic_id);
SELECT t1.admission_id, t2.test_code FROM pa_adm AS t1 INNER JOIN lb_ord AS t2 ON t1.admission_id = t2.admission_id WHERE t2.test_code LIKE '%oxy' AND t1.admitted_at > '2022-01-01' AND t1.clinic_id = 145
SQLite 3.45
SELECT T1.imp_id, T2.click_id, T1.campaign_id FROM ad_impressions AS T1 INNER JOIN click_events AS T2ON T1.imp_id = T2.imp_id WHERE T1.served_at > '2022-01-01' AND T2.conversion_val > 0.5AND T1.bid_cpm < 10.0
EXPLAIN QUERY PLAN SELECT T1.imp_id, T2.click_id, T1.campaign_id FROM ad_impressions AS T1 INNER JOIN click_events AS T2ON T1.imp_id = T2.imp_id WHERE T1.served_at > '2022-01-01' AND T2.conversion_val > 0.5AND T1.bid_cpm < 10.0 -- The plan is a full table scan of ad_impressions followed by a nested loop join with click...
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned by the join operation, resulting in a full table scan of ad_impressions, which has a large number of rows. Additionally, the lack of an index on the join column imp_id in both tables exacerbated the...
CREATE INDEX idx_ad_impressions_imp_id ON ad_impressions (imp_id); CREATE INDEX idx_click_events_imp_id ON click_events (imp_id);
SELECT T1.imp_id, T2.click_id, T1.campaign_id FROM ad_impressions AS T1 INNER JOIN click_events AS T2ON T1.imp_id = T2.imp_id WHERE T1.served_at > '2022-01-01' AND T2.conversion_val > 0.5AND T1.bid_cpm < 10.0
CockroachDB v23.2
SELECT s.tracking_num, cr.base_rate FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.status = 'in_transit' AND cr.zone_id = 5 AND s.departed_at > '2022-01-01' AND cr.weight_kg > 10
EXPLAIN (ANALYZE, BUFFERS) SELECT s.tracking_num, cr.base_rate FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.status = 'in_transit' AND cr.zone_id = 5 AND s.departed_at > '2022-01-01' AND cr.weight_kg > 10; -> Nested Loop Left Join (cost=100.50..101.52 rows=1 width=44) -> Fil...
The query planner chose this sub-optimal route because it failed to utilize an efficient join order due to the missing composite join key on the carrier_id and zone_id columns, resulting in a Cartesian product row multiplication. The lack of a suitable index on the carrier_rates table for the zone_id and weight_kg colu...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id, status, departed_at); CREATE INDEX idx_carrier_rates_carrier_id_zone_id ON carrier_rates (carrier_id, zone_id, weight_kg); VACUUM ANALYZE shipments; VACUUM ANALYZE carrier_rates;
SELECT s.tracking_num, cr.base_rate FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 WHERE s.status = 'in_transit' AND s.departed_at > '2022-01-01' AND cr.weight_kg > 10
ClickHouse 24.3
SELECT pa.admission_id, lo.test_code, bc.charge_cents FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id INNER JOIN billing_codes bc ON pa.admission_id = bc.admission_id WHERE pa.admitted_at > '2022-01-01' AND lo.flagged = 1 AND bc.icd10 = 'R07.9' LIMIT 10000;
{"type": "NestedLoopJoin", "rows": 125431.0, "bytes": 12041408, "filter": "(pa.admitted_at > \u00272022-01-01\u0027) AND (lo.flagged = 1) AND (bc.icd10 = \u0027R07.9\u0027)", "join": "NestedLoopJoin", "left": {"type": "SeqScan", "rows": 50000.0, "bytes": 4816896, "filter": "(pa.admitted_at > \u00272022-01-01\u0027)", "...
The query planner chose this sub-optimal route because the admission_id columns in the lab_orders and billing_codes tables are not indexed, leading to sequential scans on these tables. Additionally, the NestedLoopJoin algorithm is not the most efficient for this type of query, as it results in a large number of rows be...
CREATE INDEX idx_admission_id ON lab_orders (admission_id); CREATE INDEX idx_admission_id ON billing_codes (admission_id);
SELECT pa.admission_id, lo.test_code, bc.charge_cents FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id INNER JOIN billing_codes bc ON pa.admission_id = bc.admission_id WHERE pa.admitted_at > '2022-01-01' AND lo.flagged = 1 AND bc.icd10 = 'R07.9' LIMIT 10000;
ClickHouse 24.3
SELECT oi.item_id, oi.order_id, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi INNER JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id WHERE oi.unit_price > 15.20 AND ist.available_qty > 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id =...
{"trees":{"0":{"name":"Union","children":[{"name":"Limit","children":[{"name":"Sort","children":[{"name":"Aggregate","children":[{"name":"Join","children":[{"name":"Scan","table":"order_items"},{"name":"Scan","table":"inventory_stock"}]}]}]}]}]},{"name":"Filter","children":[{"name":"Scan","table":"order_items"}]}]},{"t...
The query planner chose this sub-optimal route because it failed to utilize an efficient join order due to the lack of a suitable index on the order_items table, specifically on the sku_id and warehouse_id columns, which led to excessive heap fetches on the wide inventory_stock table, thus resulting in a significant in...
CREATE INDEX idx_order_items_sku_warehouse ON order_items (sku_id, warehouse_id) INCLUDE (quantity, unit_price);
SELECT oi.item_id, oi.order_id, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi INNER JOIN inventory_stock ist ON oi.sku_id = ist.sku_id AND oi.warehouse_id = ist.warehouse_id WHERE oi.unit_price > 15.20 AND ist.available_qty > 50 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id =...
SQLite 3.45
SELECT * FROM t1_ledger_entries WHERE amount > (SELECT AVG(amount) FROM t2_ledger_entries WHERE t2_ledger_entries.account_id = t1_ledger_entries.account_id AND t2_ledger_entries.currency = 'USD' AND t2_ledger_entries.posting_date > '2022-01-01') AND t1_ledger_entries.status = 'PENDING'
EXPLAIN QUERY PLAN FOR SELECT * FROM t1_ledger_entries WHERE amount > (SELECT AVG(amount) FROM t2_ledger_entries WHERE t2_ledger_entries.account_id = t1_ledger_entries.account_id AND t2_ledger_entries.currency = 'USD' AND t2_ledger_entries.posting_date > '2022-01-01') AND t1_ledger_entries.status = 'PENDING'; -- The co...
The optimizer chose this sub-optimal route because it prioritized the correlated subquery in the WHERE clause, which led to a sequential scan of t2_ledger_entries for each row in t1_ledger_entries. This approach increased the execution time exponentially due to the repeated subquery evaluations. Furthermore, the lack o...
CREATE INDEX idx_account_id_currency ON t2_ledger_entries (account_id, currency); CREATE INDEX idx_account_id_status ON t1_ledger_entries (account_id, status);
WITH ledger_entry_avg AS (SELECT account_id, AVG(amount) AS avg_amount FROM t2_ledger_entries WHERE currency = 'USD' AND posting_date > '2022-01-01' GROUP BY account_id) SELECT t1_ledger_entries.* FROM t1_ledger_entries JOIN ledger_entry_avg ON t1_ledger_entries.account_id = ledger_entry_avg.account_id WHERE t1_ledger_...
MariaDB 11.2
SELECT * FROM ledger_entries AS le JOIN accounts AS a ON le.account_id = a.id WHERE le.posting_date > '2022-01-01' AND a.risk_tier = 'high' AND le.currency = 12345
{"query_block": {"select_id": 1, "table": {"table_name": "le", "access_type": "ALL", "rows": 1000000, "filtered": 10, "extra": "Using filesort"}, "table": {"table_name": "a", "access_type": "ALL", "rows": 100000, "filtered": 10, "extra": "Using where; Using join buffer (Block Nested Loop)"}}}
The query planner chose this sub-optimal route because the join condition between ledger_entries and accounts is based on account_id, which is of type varchar in ledger_entries and uuid in accounts, causing an implicit type coercion that prevents the use of the B-Tree index on account_id in accounts. Additionally, the ...
CREATE INDEX idx_account_id ON accounts (id); CREATE INDEX idx_posting_date ON ledger_entries (posting_date); ALTER TABLE ledger_entries MODIFY COLUMN account_id UUID; VACUUM ANALYZE;
SELECT * FROM ledger_entries AS le JOIN accounts AS a ON le.account_id = a.id WHERE le.posting_date > '2022-01-01' AND a.risk_tier = 'high' AND le.currency = 'USD'
SQLite 3.45
SELECT d.device_id, dt.val, dt.recorded_at FROM devices d INNER JOIN device_telematics dt ON d.device_id = dt.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND dt.recorded_at > '2022-01-01' AND d.fleet_id = 123 AND d.region = 'North America'
EXPLAIN QUERY PLAN SELECT d.device_id, dt.val, dt.recorded_at FROM devices d INNER JOIN device_telematics dt ON d.device_id = dt.device_id WHERE dt.metric_type = 'temperature' AND dt.val > 50 AND dt.recorded_at > '2022-01-01' AND d.fleet_id = 123 AND d.region = 'North America'; "SEARCH TABLE devices AS d USING INDEX sq...
The query planner chose this sub-optimal route because the existing index on device_telematics (device_id, metric_type) has a broad granularity, resulting in excessive granule loading. The planner is using the index on devices (fleet_id, region) to filter the results, but the index on device_telematics is not efficient...
CREATE INDEX idx_device_telematics_metric_type_val_recorded_at ON device_telematics (metric_type, val, recorded_at); CREATE INDEX idx_devices_fleet_id_region ON devices (fleet_id, region);
SELECT d.device_id, dt.val, dt.recorded_at FROM devices d INNER JOIN device_telematics dt ON d.device_id = dt.device_id AND dt.metric_type = 'temperature' AND dt.val > 50 AND dt.recorded_at > '2022-01-01' WHERE d.fleet_id = 123 AND d.region = 'North America'
SQLite 3.45
SELECT t1.account_id, t1.amount FROM ledger_entries AS t1 WHERE t1.posting_date > '2022-01-01' AND t1.amount > (SELECT AVG(t2.amount) FROM ledger_entries AS t2 WHERE t2.account_id = t1.account_id AND t2.currency = 'USD')
EXPLAIN QUERY PLAN SELECT t1.account_id, t1.amount FROM ledger_entries AS t1 WHERE t1.posting_date > '2022-01-01' AND t1.amount > (SELECT AVG(t2.amount) FROM ledger_entries AS t2 WHERE t2.account_id = t1.account_id AND t2.currency = 'USD'); -- Output: The correlated subquery is evaluated using a sequential scan of the ...
The query planner chose this sub-optimal route because it did not consider the correlated subquery as a join operation, and therefore did not attempt to optimize it using an index. Additionally, the subquery is evaluating an aggregate function (AVG) for each row in the result set, which further exacerbates the performa...
CREATE INDEX idx_ledger_entries_account_id_currency ON ledger_entries (account_id, currency); CREATE INDEX idx_ledger_entries_posting_date ON ledger_entries (posting_date);
WITH avg_amounts AS (SELECT account_id, AVG(amount) AS avg_amount FROM ledger_entries WHERE currency = 'USD' GROUP BY account_id) SELECT t1.account_id, t1.amount FROM ledger_entries AS t1 JOIN avg_amounts AS t2 ON t1.account_id = t2.account_id WHERE t1.posting_date > '2022-01-01' AND t1.amount > t2.avg_amount
PostgreSQL 16.2
SELECT oi.item_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 > 50.00 AND i.available_qty > 10 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 12345) AND EXISTS (SELECT 1 FROM promotions p WHERE p.sku_id...
{"Plan": {"Node Type": "Bitmap Heap Scan", "Scan on": "order_items oi", "Recheck Cond": "(oi.unit_price > 50.00)", "Filter": "(oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 12345))", "Rows Removed by Filter": 50000, "Heap Blocks": 20000, "Lossy Page Mode": true, "Planning Time": 12.123, "Execution Tim...
The query planner chose the Bitmap Heap Scan plan because it underestimated the number of rows that would be returned by the subquery in the IN clause, leading to an inefficient scan of the order_items table. Additionally, the lack of indexes on the join columns and the filter conditions exacerbated the performance iss...
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...
WITH sku_orders AS (SELECT DISTINCT order_id FROM order_items WHERE sku_id = 12345), promo_skus AS (SELECT DISTINCT sku_id FROM promotions WHERE valid_from < '2022-01-01' AND valid_until > '2022-12-31') SELECT oi.item_id, i.available_qty FROM order_items oi JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehous...
PostgreSQL 16.2
WITH ranked_matches AS (SELECT match_id, region, game_mode, started_at, ended_at, ROW_NUMBER() OVER (PARTITION BY region ORDER BY started_at DESC) AS row_num FROM match_sessions WHERE started_at > '2022-01-01' AND game_mode = 'ranked'), player_performance AS (SELECT match_id, player_id, kills, score, ping_ms, AVG(kills...
{"Plan": {"Node Type": "Nested Loop", "Join Type": "Inner", "Plans": [{"Node Type": "CTE Scan", "CTE Name": "ranked_matches", "Plans": [{"Node Type": "WindowAgg", "Plans": [{"Node Type": "Seq Scan", "Relation Name": "match_sessions", "Alias": "match_sessions", "Filter": "started_at > '2022-01-01' AND game_mode = 'ranke...
The query planner chose this sub-optimal route because it failed to push down the filter predicates into the partitioned match_sessions table, resulting in a full table scan. Additionally, the use of WindowAgg operations within the CTEs prevented the optimizer from effectively reordering the operations, leading to a Ne...
CREATE INDEX idx_match_sessions_started_at ON match_sessions (started_at); CREATE INDEX idx_match_sessions_game_mode ON match_sessions (game_mode); CREATE INDEX idx_player_stats_player_id ON player_stats (player_id); ALTER TABLE match_sessions SET (parallel_workers = 4); VACUUM ANALYZE match_sessions; VACUUM ANALYZE pl...
WITH ranked_matches AS (SELECT match_id, region, game_mode, started_at, ended_at, ROW_NUMBER() OVER (PARTITION BY region ORDER BY started_at DESC) AS row_num FROM match_sessions WHERE started_at > '2022-01-01' AND game_mode = 'ranked' AND match_id IN (SELECT match_id FROM player_stats WHERE kills > 0)) SELECT rm.match_...
MySQL 8.0
SELECT dt.device_id, dt.metric_type, AVG(dt.val) AS average_value, MAX(ge.lat) AS max_lat, MIN(ge.lon) AS min_lon FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.recorded_at < '2022-01-31' AND d.regi...
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "dt", "access_type": "ALL", "rows": 123456, "filtered": 50.0, "cost": 1234.56}, "table": {"table_name": "d", "access_type": "eq_ref", "rows": 1234, "filtered": 100.0, "cost": 12.34}, "table": {"table_name": "ge", "access_t...
The query planner chose this sub-optimal route because the join order and grouping operation led to an explosion of intermediate results, which exceeded the available work_mem, causing the query to spill to disk. Additionally, the lack of suitable indexes on the join and filter columns resulted in full table scans, fur...
CREATE INDEX idx_device_telematics_device_id ON device_telematics (device_id); CREATE INDEX idx_devices_device_id ON devices (device_id); CREATE INDEX idx_geofence_events_device_id ON geofence_events (device_id); CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); ALTER TABLE device_telem...
SELECT dt.device_id, dt.metric_type, AVG(dt.val) AS average_value, MAX(ge.lat) AS max_lat, MIN(ge.lon) AS min_lon FROM device_telematics dt USE INDEX (idx_device_telematics_device_id) JOIN devices d USE INDEX (idx_devices_device_id) ON dt.device_id = d.device_id JOIN geofence_events ge USE INDEX (idx_geofence_events_de...
PostgreSQL 16.2
SELECT oi.item_id, oi.order_id, i.available_qty, p.discount_pct FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 50.00 AND i.available_qty > 100 AND p.valid_from < '2024-09-16' AND p.valid_...
{"Plan": {"Node Type": "Nested Loop", "Join Type": "Inner", "Plans": [{"Node Type": "Nested Loop", "Join Type": "Inner", "Plans": [{"Node Type": "Seq Scan", "Relation Name": "order_items", "Alias": "oi", "Rows": 100000, "Filter": "unit_price > 50.00"}, {"Node Type": "Seq Scan", "Relation Name": "inventory_stock", "Alia...
The query planner chose this sub-optimal route because it failed to utilize a covering index on the join columns and filter conditions, resulting in excessive sequential scans and heap fetches on the wide tables, particularly on the order_items table. The absence of a suitable index on the sku_id and warehouse_id colum...
CREATE INDEX idx_order_items_sku_warehouse ON order_items (sku_id, warehouse_id) INCLUDE (item_id, order_id, unit_price); CREATE INDEX idx_inventory_stock_sku_warehouse ON inventory_stock (sku_id, warehouse_id) INCLUDE (available_qty); CREATE INDEX idx_promotions_sku_valid ON promotions (sku_id, valid_from, valid_until...
SELECT oi.item_id, oi.order_id, i.available_qty, p.discount_pct FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 50.00 AND i.available_qty > 100 AND p.valid_from < '2024-09-16' AND p.valid_...
PostgreSQL 16.2
SELECT p_adm.admission_id, AVG(l_ord.numeric_result) AS average_result FROM patient_admissions p_adm JOIN lab_orders l_ord ON p_adm.admission_id = l_ord.admission_id WHERE p_adm.clinic_id = 421 AND l_ord.test_code = 'GLUC' AND l_ord.result_time > '2022-01-01' GROUP BY p_adm.admission_id HAVING AVG(l_ord.numeric_result)...
EXPLAIN (ANALYZE, BUFFERS) SELECT p_adm.admission_id, AVG(l_ord.numeric_result) AS average_result FROM patient_admissions p_adm JOIN lab_orders l_ord ON p_adm.admission_id = l_ord.admission_id WHERE p_adm.clinic_id = 421 AND l_ord.test_code = 'GLUC' AND l_ord.result_time > '2022-01-01' GROUP BY p_adm.admission_id HAVIN...
The query planner chose this sub-optimal route because the table statistics for patient_admissions and lab_orders are outdated, causing the planner to severely underestimate the intermediate row counts. Specifically, the planner underestimated the number of rows that would satisfy the join condition, leading to a neste...
CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id); CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders;
SELECT p_adm.admission_id, AVG(l_ord.numeric_result) AS average_result FROM patient_admissions p_adm JOIN lab_orders l_ord ON p_adm.admission_id = l_ord.admission_id AND l_ord.test_code = 'GLUC' WHERE p_adm.clinic_id = 421 AND l_ord.result_time > '2022-01-01' GROUP BY p_adm.admission_id HAVING AVG(l_ord.numeric_result)...
MySQL 8.0
SELECT s.tracking_num, c.carrier_id, p.checkpoint FROM shipments s JOIN parcel_events p ON s.tracking_num = p.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.source_hub = 'JFK' AND p.scan_time > '2022-01-01' AND c.base_rate > 10.00
{"query_block": {"select_id": 1, "table": {"table_name": "c", "access_type": "ALL", "rows": 200000, "filtered": 50, "cost": 200000.0}, "nested_loop": [{"table": {"table_name": "s", "access_type": "ALL", "rows": 100000, "filtered": 10, "cost": 100000.0}}, {"table": {"table_name": "p", "access_type": "ALL", "rows": 50000...
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 on the shipments and parcel_events tables, resulting in a Cartesian product row multiplication. This, combined with the full table scans on all three tables, led to an excessive nu...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num, carrier_id); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num, scan_time); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id, base_rate);
SELECT s.tracking_num, c.carrier_id, p.checkpoint FROM shipments s USE INDEX (idx_shipments_tracking_num) JOIN parcel_events p USE INDEX (idx_parcel_events_tracking_num) ON s.tracking_num = p.tracking_num AND s.carrier_id = (SELECT c.carrier_id FROM carrier_rates c USE INDEX (idx_carrier_rates_carrier_id) WHERE c.carri...
MariaDB 11.2
SELECT dt.device_id, AVG(dt.val) AS average_val, MAX(ge.lat) AS max_lat, MIN(ge.lon) AS min_lon FROM device_telematics dt JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.metric_type = 'temperature' AND ge.logged_at < '2022-12-31' GROUP BY dt.device_id, ge.id
EXPLAIN format=json SELECT dt.device_id, AVG(dt.val) AS average_val, MAX(ge.lat) AS max_lat, MIN(ge.lon) AS min_lon FROM device_telematics dt JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.metric_type = 'temperature' AND ge.logged_at < '2022-12-31' GROUP BY dt.device_i...
The query planner chose this sub-optimal route because the join operation between device_telematics and geofence_events tables is based on the device_id column, which has a high cardinality, resulting in a large number of rows being joined and then grouped by the device_id and ge.id columns, exhausting the work_mem and...
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_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_geofence_events_logged_at ON geofence_events (logged_at);
WITH device_telematics_filtered AS (SELECT device_id, val, recorded_at FROM device_telematics WHERE recorded_at > '2022-01-01' AND metric_type = 'temperature'), geofence_events_filtered AS (SELECT device_id, lat, lon, logged_at FROM geofence_events WHERE logged_at < '2022-12-31') SELECT dtf.device_id, AVG(dtf.val) AS a...
CockroachDB v23.2
WITH ranked_match_stats AS (SELECT ms.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms, ROW_NUMBER() OVER (PARTITION BY ms.region ORDER BY ps.mmr_rating DESC) AS rank FROM match_sessions ms JOIN player_stats ps ON ms.match_id = ps.match_id JOIN leaderboards lb ON ps.player_id = lb.player_id WHERE ms.game_mode = '...
EXPLAIN (ANALYZE, BUFFERS) WITH ranked_match_stats AS (SELECT ms.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms, ROW_NUMBER() OVER (PARTITION BY ms.region ORDER BY ps.mmr_rating DESC) AS rank FROM match_sessions ms JOIN player_stats ps ON ms.match_id = ps.match_id JOIN leaderboards lb ON ps.player_id = lb.playe...
The query planner chose this sub-optimal route because the materialized CTE ranked_match_stats is preventing predicate pushdown into the partitioned match_sessions table. The filter conditions on game_mode, started_at, and season_id are not being pushed down to the table scan, resulting in a full table scan of match_se...
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_player_stats_mmr_rating ON player_stats (mmr_rating); ALTER TABLE match_sessions SET (PARTITION_BY = RANGE (started_at)); VACUUM ANALYZE match_sessions; VA...
WITH ranked_match_stats AS (SELECT ms.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms, ROW_NUMBER() OVER (PARTITION BY ms.region ORDER BY ps.mmr_rating DESC) AS rank FROM match_sessions ms JOIN player_stats ps ON ms.match_id = ps.match_id JOIN leaderboards lb ON ps.player_id = lb.player_id WHERE ms.game_mode = '...
MariaDB 11.2
SELECT dt.val, d.region, ge.lat FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01' AND d.status = 'active' AND ge.logged_at < '2023-01-01' AND dt.firmware_v = '2.1.4' AND ge....
EXPLAIN format=json SELECT dt.val, d.region, ge.lat FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id JOIN geofence_events ge ON dt.device_id = ge.device_id WHERE dt.metric_type = 'temperature' AND dt.recorded_at > '2022-01-01' AND d.status = 'active' AND ge.logged_at < '2023-01-01' AND dt.firmware...
The query planner chose this sub-optimal route because the skip index granularity on the device_telematics table is too broad, resulting in excessive granule loading. The index on device_id is not selective enough, causing the optimizer to perform a full table scan. Additionally, the join order is not optimal, leading ...
CREATE INDEX idx_device_telematics_device_id_metric_type ON device_telematics (device_id, metric_type); CREATE INDEX idx_devices_device_id_status ON devices (device_id, status); CREATE INDEX idx_geofence_events_device_id_logged_at ON geofence_events (device_id, logged_at);
SELECT dt.val, d.region, ge.lat FROM device_telematics dt USE INDEX (idx_device_telematics_device_id_metric_type) JOIN devices d USE INDEX (idx_devices_device_id_status) ON dt.device_id = d.device_id JOIN geofence_events ge USE INDEX (idx_geofence_events_device_id_logged_at) ON dt.device_id = ge.device_id WHERE dt.metr...
ClickHouse 24.3
SELECT dt.device_id, dt.metric_type, avg(dt.val) AS avg_val 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.metric_type = 5 AND d.fleet_id = 123 AND dt.firmware_v = '2.1.0' GROUP BY dt.device_id, dt.metric_type ORDER BY avg_val DESC ...
{"rows_read dairies": 23456789, "elapsed": 123.456, "memory_usage": 3456, "partition_key": {"start_date": "2022-01-01", "end_date": "2024-12-31"}, "plan": {"nodes": [{"type": "Aggregate", "keys": ["device_id", "metric_type"], "funcs": [{"type": "Avg", "cols": ["val"]}]}, {"type": "Sort", "keys": ["avg_val"], "dirs": ["...
The query planner chose this sub-optimal route because the primary key of the device_telematics table is not properly aligned with the query's filter conditions, specifically the recorded_at timestamp column, which leads to a full partition decompression. Additionally, the join condition with the devices table is not o...
CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded_at); CREATE INDEX idx_device_telematics_metric_type ON device_telematics (metric_type); CREATE INDEX idx_devices_fleet_id ON devices (fleet_id); ALTER TABLE device_telematics ADD COLUMN firmware_v_index AS (firmware_v); CREATE INDEX idx_devic...
SELECT dt.device_id, dt.metric_type, avg(dt.val) AS avg_val FROM device_telematics AS dt USE INDEX idx_device_telematics_recorded_at USE INDEX idx_device_telematics_metric_type INNER JOIN devices AS d USE INDEX idx_devices_fleet_id ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01 00:00:00' AND dt.metric...
PostgreSQL 16.2
WITH ranked_players AS (SELECT player_id, AVG(mmr_rating) AS avg_mmr FROM leaderboards WHERE season_id = 23 GROUP BY player_id), recent_matches AS (SELECT match_id, region, game_mode, started_at FROM match_sessions WHERE ended_at > '2022-01-01' AND region = 'EU') SELECT rp.player_id, rm.match_id, ps.kills, ps.score FRO...
EXPLAIN (ANALYZE, BUFFERS) SELECT rp.player_id, rm.match_id, ps.kills, ps.score FROM (SELECT player_id, AVG(mmr_rating) AS avg_mmr FROM leaderboards WHERE season_id = 23 GROUP BY player_id) rp JOIN player_stats ps ON rp.player_id = ps.player_id JOIN (SELECT match_id, region, game_mode, started_at FROM match_sessions WH...
The query planner chose this sub-optimal route because the Materialized CTE (WITH clause) prevented predicate pushdown into the partitioned match_sessions table, resulting in a full scan of the CTE and subsequent joins, leading to high startup and total costs. The planner prioritized the join order based on the estimat...
CREATE INDEX idx_match_sessions_ended_at ON match_sessions (ended_at); CREATE INDEX idx_match_sessions_region ON match_sessions (region); CREATE INDEX idx_player_stats_player_id ON player_stats (player_id); CREATE INDEX idx_leaderboards_season_id ON leaderboards (season_id); ALTER TABLE match_sessions SET (parallel_wor...
WITH ranked_players AS (SELECT player_id, AVG(mmr_rating) AS avg_mmr FROM leaderboards WHERE season_id = 23 GROUP BY player_id), recent_matches AS (SELECT match_id, region, game_mode, started_at FROM match_sessions WHERE ended_at > '2022-01-01' AND region = 'EU' AND game_mode = 'Ranked') SELECT rp.player_id, rm.match_i...
SQLite 3.45
SELECT s.tracking_num, c.base_rate, p.scan_time FROM shipments s INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id INNER JOIN parcel_events p ON s.tracking_num = p.tracking_num WHERE s.departed_at > '2022-01-01' AND c.zone_id = 5 AND p.checkpoint = 'DEL'
EXPLAIN QUERY PLAN: SELECT s.tracking_num, c.base_rate, p.scan_time FROM shipments s INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id INNER JOIN parcel_events p ON s.tracking_num = p.tracking_num WHERE s.departed_at > '2022-01-01' AND c.zone_id = 5 AND p.checkpoint = 'DEL'; Scan shipments using WHERE clause, ...
The query planner chose this sub-optimal route because it had to perform a merge join on the unindexed departed_at column in the shipments table, resulting in an expensive memory sort operation. Additionally, the lack of indexes on the tracking_num column in the parcel_events table and the carrier_id column in the carr...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id);
SELECT s.tracking_num, c.base_rate, p.scan_time FROM shipments s INNER JOIN carrier_rates c ON s.carrier_id = c.carrier_id INNER JOIN parcel_events p ON s.tracking_num = p.tracking_num WHERE s.departed_at > '2022-01-01' AND c.zone_id = 5 AND p.checkpoint = 'DEL' ORDER BY s.departed_at;
PostgreSQL 16.2
SELECT ps.match_id, ps.player_id, ps.kills, ps.score, ps.ping_ms FROM player_stats ps WHERE ps.kills > 10 OR ps.ping_ms < 50 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'EU' 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 > 10 OR ps.ping_ms < 50 AND ps.match_id IN (SELECT ms.match_id FROM match_sessions ms WHERE ms.region = 'EU' AND ms.game_mode = 'Ranked'); -> Seq Scan on player_stats ps (cost=0.00..1456.83 ...
The query planner chose a full table scan on the player_stats table due to the OR condition across unindexed columns kills and ping_ms, which prevents the optimizer from effectively utilizing an index. Furthermore, the subquery on match_sessions returns a set of match_id values that are then used to filter the player_s...
CREATE INDEX idx_player_stats_kills ON player_stats (kills); CREATE INDEX idx_player_stats_ping_ms ON player_stats (ping_ms); 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 JOIN match_sessions ms ON ps.match_id = ms.match_id WHERE (ps.kills > 10 OR ps.ping_ms < 50) AND ms.region = 'EU' AND ms.game_mode = 'Ranked';
CockroachDB v23.2
SELECT dte.metric_type, AVG(dte.val) AS avg_val, MAX(dte.recorded_at) AS latest_reading FROM device_telematics dte JOIN devices dev ON dte.device_id = dev.device_id WHERE dte.firmware_v = '2.4.1' AND dev.status = 'online' AND dte.recorded_at > '2022-01-01' GROUP BY dte.metric_type, dev.region ORDER BY avg_val DESC LIMI...
EXPLAIN (ANALYZE, BUFFERS) SELECT dte.metric_type, AVG(dte.val) AS avg_val, MAX(dte.recorded_at) AS latest_reading FROM device_telematics dte JOIN devices dev ON dte.device_id = dev.device_id WHERE dte.firmware_v = '2.4.1' AND dev.status = 'online' AND dte.recorded_at > '2022-01-01' GROUP BY dte.metric_type, dev.region...
The query planner chose this sub-optimal route because it was unable to effectively utilize indexes due to the high-cardinality nature of the GROUP BY columns, leading to an exhaustive sequential scan of both tables, and the large amount of data being processed exceeded the available work_mem, causing the operation to ...
CREATE INDEX idx_device_telematics_device_id ON device_telematics (device_id); CREATE INDEX idx_device_telematics_metric_type ON device_telematics (metric_type); CREATE INDEX idx_devices_device_id ON devices (device_id); CREATE INDEX idx_devices_region ON devices (region); VACUUM ANALYZE device_telematics; VACUUM ANALY...
SELECT dte.metric_type, AVG(dte.val) AS avg_val, MAX(dte.recorded_at) AS latest_reading FROM device_telematics dte JOIN devices dev ON dte.device_id = dev.device_id WHERE dte.firmware_v = '2.4.1' AND dev.status = 'online' AND dte.recorded_at > '2022-01-01' GROUP BY dte.metric_type, dev.region ORDER BY avg_val DESC LIMI...
SQLite 3.45
SELECT oi.item_id, oi.order_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id INNER 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 < '2022-07-15' AN...
EXPLAIN QUERY PLAN SELECT oi.item_id, oi.order_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id INNER JOIN promotions p ON oi.sku_id = p.sku_id WHERE oi.unit_price > 19.99 AND i.available_qty > 50 AND p.valid_fro...
The query planner chose this sub-optimal route because it did not have sufficient statistical information about the data distribution in the order_items, inventory_stock, and promotions tables, and it defaulted to a full table scan. Additionally, the absence of a covering index on the join columns (sku_id and warehouse...
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); CREATE INDEX idx_promotions_sku_id ON promotions (sku_id);
SELECT oi.item_id, oi.order_id, oi.sku_id, i.available_qty, p.discount_pct FROM order_items oi INNER JOIN inventory_stock i ON oi.sku_id = i.sku_id AND oi.warehouse_id = i.warehouse_id INNER 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 < '2022-07-15' AN...
CockroachDB v23.2
SELECT oi.item_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 DATE_TRUNC('day', i.updated_at) = '2024-09-16' AND oi.unit_price > 19.99 AND i.available_qty > 50
{"planning_time":1.123,"execution_time":234.562,"rows":150,"bytes":12000,"plan":{"nodes":[{"type":"HashJoin","description":"HashJoin","rows":150,"bytes":12000},{"type":"Filter","description":"Filter","rows":300,"bytes":24000},{"type":"Scan","description":"inventory_stock","rows":1000,"bytes":80000}]}
The query planner chose this sub-optimal route because the non-SARGable function DATE_TRUNC('day', i.updated_at) prevents the use of an index range scan on the updated_at column. As a result, the planner opted for a full table scan of inventory_stock, leading to increased execution time. Furthermore, the join operation...
CREATE INDEX idx_updated_at ON inventory_stock (updated_at); CREATE INDEX idx_sku_id_warehouse_id ON order_items (sku_id, warehouse_id); CREATE INDEX idx_sku_id_warehouse_id_available_qty ON inventory_stock (sku_id, warehouse_id, available_qty);
SELECT oi.item_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 i.updated_at >= '2024-09-16 00:00:00' AND i.updated_at < '2024-09-17 00:00:00' AND oi.unit_price > 19.99 AND i.available_qty > 50
PostgreSQL 16.2
SELECT oi.item_id, oi.order_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.quantity <10 AND EXISTS (SELECT 1 FROM promotions p WHERE p.sku_id = oi.sku_id AND p.valid_from <...
EXPLAIN (ANALYZE, BUFFERS) SELECT oi.item_id, oi.order_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.quantity <10 AND EXISTS (SELECT 1 FROM promotions p WHERE p.sku_id = o...
The query planner chose this sub-optimal route because the available work_mem was too low to accommodate the entire bitmap in memory, resulting in a lossy page mode for the Bitmap Heap Scan, which led to a significant increase in the number of disk I/O operations, and consequently, a slower query execution time. Additi...
CREATE INDEX order_items_unit_price_quantity_idx ON order_items (unit_price, quantity); CREATE INDEX inventory_stock_available_qty_idx ON inventory_stock (available_qty); ALTER TABLE order_items SET (parallel_workers = 4); VACUUM ANALYZE order_items; VACUUM ANALYZE inventory_stock;
SELECT oi.item_id, oi.order_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.quantity <10 AND EXISTS (SELECT 1 FROM promotions p WHERE p.sku_id = oi.sku_id AND p.valid_from <...
MariaDB 11.2
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.departed_at > '2022-07-15 12:00:00' AND c.base_rate > 50.00 AND pe.scan_time < '2024-03-20 18:00:00'
{"query_block": {"select_id": 1, "table": {"table_name": "s", "access_type": "ALL", "rows": 120000, "filtered": 20.00, "extra": "Using filesort"}, "table": {"table_name": "pe", "access_type": "ALL", "rows": 150000, "filtered": 30.00, "extra": "Using join buffer (Block Nested Loop)"}, "table": {"table_name": "c", "acces...
The query planner chose this sub-optimal route because the joined tables have no suitable index on the departed_at column in the shipments table, forcing the optimizer to perform an expensive filesort operation to satisfy the filter condition. Additionally, the lack of indexing on the tracking_num column in the parcel_...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_base_rate ON carrier_rates (base_rate); ALTER TABLE shipments ADD INDEX idx_shipments_tracking_num (tracking_num);
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.scan_time < '2024-03-20 18:00:00' JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.base_rate > 50.00 WHERE s.departed_at > '2022-07-15 12:00:00'
CockroachDB v23.2
SELECT t1.admission_id, t2.test_code, t3.icd10 FROM patient_admissions t1 INNER JOIN lab_orders t2 ON t1.admission_id = t2.admission_id INNER JOIN billing_codes t3 ON t1.admission_id = t3.admission_id WHERE t1.clinic_id = 145 AND t2.flagged = TRUE AND t3.charge_cents > 5000
EXPLAIN (ANALYZE, BUFFERS) SELECT t1.admission_id, t2.test_code, t3.icd10 FROM patient_admissions t1 INNER JOIN lab_orders t2 ON t1.admission_id = t2.admission_id INNER JOIN billing_codes t3 ON t1.admission_id = t3.admission_id WHERE t1.clinic_id = 145 AND t2.flagged = TRUE AND t3.charge_cents > 5000 -> Nested Loop Lef...
The query planner chose the sub-optimal route of using nested loop joins with sequential scans because the admission_id columns in the lab_orders and billing_codes tables are not indexed, resulting in a full table scan for each join operation. Additionally, the filter conditions on the clinic_id, flagged, and charge_ce...
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); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders; VACUUM ANALYZE billing_codes;
SELECT t1.admission_id, t2.test_code, t3.icd10 FROM patient_admissions t1 INNER JOIN lab_orders t2 ON t1.admission_id = t2.admission_id INNER JOIN billing_codes t3 ON t1.admission_id = t3.admission_id WHERE t1.clinic_id = 145 AND t2.flagged = TRUE AND t3.charge_cents > 5000
MySQL 8.0
SELECT * FROM ledger_entries le WHERE le.posting_date > '2022-01-01' AND le.amount > (SELECT AVG(amount) FROM ledger_entries WHERE account_id = le.account_id AND currency = 'USD') AND le.account_id IN (SELECT account_id FROM accounts WHERE risk_tier = 3 AND balance > 10000);
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "3432.10"}, "table": {"table_name": "le", "access_type": "ALL", "rows": 100000, "filtered": 10, "cost_info": {"row_count": 10000, "cost": "3432.10"}}, "nested_loop": [ {"table": {"table_name": "<derived2>", "access_type": "ALL", "rows": 10000, "filtered": 100...
The MySQL query planner chose this sub-optimal route because the correlated subquery in the WHERE clause is evaluating per-row sequential scans, resulting in a high number of rows being scanned and filtered, leading to increased query cost and execution time. The lack of relevant indexes on the ledger_entries table, pa...
CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); CREATE INDEX idx_ledger_entries_posting_date ON ledger_entries (posting_date); CREATE INDEX idx_accounts_risk_tier_balance ON accounts (risk_tier, balance);
WITH avg_amount AS (SELECT account_id, AVG(amount) AS avg_amount FROM ledger_entries WHERE currency = 'USD' GROUP BY account_id) SELECT le.* FROM ledger_entries le JOIN avg_amount aa ON le.account_id = aa.account_id WHERE le.posting_date > '2022-01-01' AND le.amount > aa.avg_amount AND le.account_id IN (SELECT account_...
CockroachDB v23.2
SELECT SUM(cr.base_rate * 1.1) AS total_revenue FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.departed_at > '2022-01-01' AND s.status = 'delivered' AND cr.zone_id = 3 AND cr.weight_kg > 10
EXPLAIN (ANALYZE, BUFFERS) SELECT SUM(cr.base_rate * 1.1) AS total_revenue FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.departed_at > '2022-01-01' AND s.status = 'delivered' AND cr.zone_id = 3 AND cr.weight_kg > 10; HashAggregate (cost=23455.23..23455.25 rows=1 width=32) (actual...
The query planner chose to use a Hash Aggregate operation to compute the sum of the base rates, but due to the lack of sufficient memory (undersized work_mem), it spilled the intermediate results to temporary disk files, resulting in significant performance degradation. This is because the planner overestimated the num...
CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id); CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_carrier_rates_zone_id ON carrier_rates (zone_id); ALTER TABLE shipments SET (work_mem = '16MB');
SELECT SUM(cr.base_rate * 1.1) AS total_revenue FROM shipments s INNER JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.departed_at > '2022-01-01' AND s.status = 'delivered' AND cr.zone_id = 3 AND cr.weight_kg > 10 ORDER BY 1;
MySQL 8.0
SELECT t1.admission_id, t2.test_code, t3.icd10 FROM patient_admissions t1 INNER JOIN lab_orders t2 ON t1.admission_id = t2.admission_id INNER JOIN billing_codes t3 ON t1.admission_id = t3.admission_id WHERE t1.clinic_id = 145 AND t2.numeric_result > 8.2 AND t3.charge_cents > 1500
{"query_block": {"select_id": 1, "table": {"table_name": "t2", "access_type": "ALL", "rows": 12000, "filtered": 20.0, "cost": 3121.20}, "table": {"table_name": "t1", "access_type": "ref", "rows": 1500, "filtered": 100.0, "cost": 1201.10}, "table": {"table_name": "t3", "access_type": "ALL", "rows": 20000, "filtered": 15...
The query planner chose this sub-optimal route because the table statistics for patient_admissions, lab_orders, and billing_codes are outdated, causing it to severely underestimate the intermediate row counts. Specifically, the planner underestimated the number of rows in the lab_orders table that would match the join ...
ANALYZE TABLE patient_admissions; ANALYZE TABLE lab_orders; ANALYZE TABLE billing_codes; CREATE INDEX idx_clinic_id ON patient_admissions (clinic_id); CREATE INDEX idx_admission_id ON lab_orders (admission_id); CREATE INDEX idx_admission_id ON billing_codes (admission_id);
SELECT t1.admission_id, t2.test_code, t3.icd10 FROM patient_admissions t1 INNER JOIN lab_orders t2 ON t1.admission_id = t2.admission_id AND t2.numeric_result > 8.2 INNER JOIN billing_codes t3 ON t1.admission_id = t3.admission_id AND t3.charge_cents > 1500 WHERE t1.clinic_id = 145
CockroachDB v23.2
SELECT p.admission_id, l.test_code, b.icd10 FROM patient_admissions p JOIN lab_orders l ON p.admission_id = l.order_id JOIN billing_codes b ON p.admission_id = b.code_id WHERE p.admitted_at > '2022-01-01' AND l.flagged = TRUE AND b.charge_cents > 500
{"plan": {"nodes": [{"type": "nested loop join", "args": [{"type": "seq scan", "args": [{"table": "patient_admissions", "alias": "p", "filter": "(admitted_at > '2022-01-01')"}]}, {"type": "seq scan", "args": [{"table": "lab_orders", "alias": "l", "filter": "(flagged = TRUE)"}]}, {"type": "seq scan", "args": [{"table": ...
The query planner chose this sub-optimal route because the foreign key columns admission_id in the lab_orders and billing_codes tables are not indexed, resulting in sequential scans on these tables. Additionally, the join order was not optimized, leading to a nested loop join, which can be inefficient for large dataset...
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_admitted_at ON patient_admissions (admitted_at); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders; VACUUM ANALYZE billing_co...
SELECT p.admission_id, l.test_code, b.icd10 FROM patient_admissions p JOIN lab_orders l ON p.admission_id = l.admission_id JOIN billing_codes b ON p.admission_id = b.admission_id WHERE p.admitted_at > '2022-01-01' AND l.flagged = TRUE AND b.charge_cents > 500
ClickHouse 24.3
SELECT pa.admission_id, pa.patient_id, lo.test_code, lo.numeric_result FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 147 AND lo.flagged = 1 AND lo.result_time > '2022-01-01' AND pa.admitted_at < '2023-01-01'
{"rows":"10923","bytes":"314392","filtered":"0.234","plans":[{"id":"1","rows":"10923","bytes":"314392","filtered":"0.234","plan":"NestedLoopJoin","join":"Inner","on":"pa.admission_id = lo.admission_id","left":{"id":"2","rows":"5012","bytes":"167213","filtered":"0.119","plan":"SeqScan","table":"patient_admissions","filt...
The query planner chose this sub-optimal route because it did not have sufficient indexing information to make a more informed decision, resulting in a full table scan on both tables, which led to the use of a nested loop join. This join type is particularly inefficient for large tables because it compares each row of ...
CREATE INDEX idx_admission_id ON lab_orders (admission_id); CREATE INDEX idx_clinic_id ON patient_admissions (clinic_id); CREATE INDEX idx_result_time ON lab_orders (result_time);
SELECT pa.admission_id, pa.patient_id, lo.test_code, lo.numeric_result FROM patient_admissions pa INNER JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 147 AND lo.flagged = 1 AND lo.result_time > '2022-01-01' AND pa.admitted_at < '2023-01-01'
PostgreSQL 16.2
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.status = 'in_transit' AND c.base_rate > 50.00 AND pe.scan_time > '2022-01-01 00:00:00'
EXPLAIN (ANALYZE, BUFFERS) SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates c ON s.carrier_id = c.carrier_id WHERE s.status = 'in_transit' AND c.base_rate > 50.00 AND pe.scan_time > '2022-01-01 00:00:00'; => Nested Loop Left Jo...
The query planner chose this sub-optimal route because it failed to utilize a composite join key on the shipments and parcel_events tables, resulting in a Cartesian product row multiplication, leading to a significant increase in the number of rows being joined and filtered, thus causing a performance regression. Addit...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); 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 SET (parallel_...
SELECT s.tracking_num, c.zone_id, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND s.status = 'in_transit' JOIN carrier_rates c ON s.carrier_id = c.carrier_id AND c.base_rate > 50.00 WHERE pe.scan_time > '2022-01-01 00:00:00'
MariaDB 11.2
SELECT t1.tracking_num, t2.base_rate FROM shipments t1 INNER JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id WHERE t1.departed_at > '2022-01-01' AND t1.status = 'in_transit' AND t2.zone_id = 5 AND t2.weight_kg > 10 ORDER BY t1.departed_at LIMIT 100;
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "t1", "access_type": "ALL", "rows": "100000", "filtered": "10.00", "index_condition": null}, "table": {"table_name": "t2", "access_type": "ALL", "rows": "50000", "filtered": "20.00", "index_condition": null}, "nested_loop"...
The query planner chose a sub-optimal route because the departed_at column in the shipments table is not indexed, resulting in a full table scan and expensive memory sort operations. Additionally, the join order between shipments and carrier_rates is not optimal, leading to a large number of rows being joined and sorte...
CREATE INDEX idx_shipments_departed_at ON shipments (departed_at); CREATE INDEX idx_carrier_rates_zone_id_weight_kg ON carrier_rates (zone_id, weight_kg); CREATE INDEX idx_shipments_carrier_id ON shipments (carrier_id);
SELECT t1.tracking_num, t2.base_rate FROM shipments t1 INNER JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id AND t2.zone_id = 5 AND t2.weight_kg > 10 WHERE t1.departed_at > '2022-01-01' AND t1.status = 'in_transit' ORDER BY t1.departed_at LIMIT 100;
PostgreSQL 16.2
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE campaign_id IN (123, 456, 789) AND served_at >= '2022-01-01' AND served_at < '2023-01-01'
{"Plan": {"Node Type": "WindowAgg", "Strategy": "Sorted", "Options": ["ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num"], "Plans": [{"Node Type": "Seq Scan", "Relation Name": "ad_impressions", "Alias": "ad_impressions", "Filter": "(served_at >= '2022-01-01'::date) AND (served_at < '2023...
The query planner chose this sub-optimal route because it needs to sort the entire table of 50 million rows on disk due to the lack of a matching composite index on the columns publisher_id and served_at. The ROW_NUMBER() window function requires the data to be sorted, and since there is no suitable index, the planner ...
CREATE INDEX idx_ad_impressions_publisher_id_served_at ON ad_impressions (publisher_id, served_at DESC); VACUUM ANALYZE ad_impressions;
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE campaign_id IN (123, 456, 789) AND served_at >= '2022-01-01' AND served_at < '2023-01-01'
CockroachDB v23.2
SELECT su.id, su.workspace_id, su.plan, su.renewal_date FROM subscriptions su WHERE su.is_active = TRUE AND su.workspace_id = 1042 AND su.plan = 'Enterprise'
{"plan": {"nodes": [{"type": "Scan", "desc": "subscriptions su", "index": null, "filter": "(is_active = TRUE) AND (workspace_id = 1042) AND (plan = 'Enterprise')", "rows": 10000, "bytes": 100000}]}, "stats": {"planning_time": 10, "execution_time": 500, "rows": 10, "bytes": 1000}}
The query planner chose a sequential scan on the subscriptions table because there is no index on the is_active column, which is used in the filter condition. Additionally, the query has a low selectivity due to the equality conditions on workspace_id and plan, which makes the index on these columns less effective. As ...
CREATE INDEX idx_subscriptions_is_active ON subscriptions (is_active); CREATE INDEX idx_subscriptions_workspace_id_plan ON subscriptions (workspace_id, plan); VACUUM ANALYZE subscriptions;
SELECT su.id, su.workspace_id, su.plan, su.renewal_date FROM subscriptions su WHERE su.is_active = TRUE AND su.workspace_id = 5421 AND su.plan = 'Pro'
CockroachDB v23.2
SELECT COUNT(DISTINCT t1.tracking_num) AS total_shipments, AVG(t2.base_rate) AS average_rate FROM shipments t1 JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id WHERE t1.departed_at > '2022-01-01' AND t1.status = 'in_transit' AND t2.zone_id = 5 AND t2.weight_kg > 10
EXPLAIN (ANALYZE, BUFFERS) SELECT COUNT(DISTINCT t1.tracking_num) AS total_shipments, AVG(t2.base_rate) AS average_rate FROM shipments t1 JOIN carrier_rates t2 ON t1.carrier_id = t2.carrier_id WHERE t1.departed_at > '2022-01-01' AND t1.status = 'in_transit' AND t2.zone_id = 5 AND t2.weight_kg > 10; -> HashAggregate (c...
The query planner chose to use a Hash Aggregate to compute the COUNT(DISTINCT) and AVG() aggregations, but due to the large number of rows being processed, the aggregate spilled to temporary disk files, resulting in a significant performance degradation. This is likely because the work_mem setting is too low, causing t...
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 SET (work_mem = '16MB'); VACUUM ANALYZE shipments; VACUUM ANALYZE carrier_rates;
SELECT COUNT(DISTINCT s.tracking_num) AS total_shipments, AVG(cr.base_rate) AS average_rate FROM shipments s JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 AND cr.weight_kg > 10 WHERE s.departed_at > '2022-01-01' AND s.status = 'in_transit'
MariaDB 11.2
WITH ranked_players AS (SELECT T1.player_id, SUM(T1.kills) AS total_kills, SUM(T1.score) AS total_score FROM player_stats T1 INNER JOIN match_sessions T2 ON T1.match_id = T2.match_id WHERE T2.region = 'EUWest' AND T2.game_mode = 'Ranked' AND T2.started_at > '2022-01-01' GROUP BY T1.player_id) SELECT T1.player_id, T1.to...
{"query_block": {"select_id": 1, "table": {"table_name": "derived_table", "access_type": "ALL", "rows": 10000, "filtered": 10, "table_scan": {"rows": 10000, "columns": ["player_id", "total_kills", "total_score"]}}}, "query_block": {"select_id": 2, "table": {"table_name": "T2", "access_type": "ALL", "rows": 100000, "fil...
The query planner chose this sub-optimal route because the Materialized CTE (WITH clause) prevents predicate pushdown into the partitioned match_sessions table, resulting in a full table scan of the derived table and the match_sessions table. This is because the CTE is materialized before the join with the leaderboards...
CREATE INDEX idx_match_sessions_region_game_mode ON match_sessions (region, game_mode); CREATE INDEX idx_player_stats_match_id ON player_stats (match_id); CREATE INDEX idx_leaderboards_season_id ON leaderboards (season_id);
SELECT T1.player_id, SUM(T1.kills) AS total_kills, SUM(T1.score) AS total_score FROM player_stats T1 INNER JOIN match_sessions T2 ON T1.match_id = T2.match_id INNER JOIN leaderboards T3 ON T1.player_id = T3.player_id WHERE T2.region = 'EUWest' AND T2.game_mode = 'Ranked' AND T2.started_at > '2022-01-01' AND T3.season_i...
MySQL 8.0
SELECT t1.id, t2.user_id, t2.balance FROM ledger_entries t1 INNER JOIN accounts t2 ON t1.account_id = t2.id WHERE t1.account_id = 12345 AND t1.posting_date BETWEEN '2022-01-01' AND '2022-12-31' ORDER BY t1.posting_date DESC LIMIT 100;
{"query_block": {"select_id": 1, "table": {"table_name": "t1", "access_type": "ALL", "rows": 1000000, "filtered": 0.1, "extra": "Using filesort"}, "table": {"table_name": "t2", "access_type": "eq_ref", "rows": 1, "filtered": 100.0, "extra": ""}}}
The query planner chose a sub-optimal route because the ledger_entries table has no composite index on the account_id and posting_date columns, resulting in a full table scan. The lack of this index forces the optimizer to use a filesort operation to satisfy the ORDER BY clause, leading to increased execution time and ...
CREATE INDEX idx_account_id_posting_date ON ledger_entries (account_id, posting_date);
SELECT t1.id, t2.user_id, t2.balance FROM ledger_entries t1 INNER JOIN accounts t2 ON t1.account_id = t2.id WHERE t1.account_id = 12345 AND t1.posting_date BETWEEN '2022-01-01' AND '2022-12-31' ORDER BY t1.posting_date DESC LIMIT 100;
PostgreSQL 16.2
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 421 AND lo.test_code = 'GLUC' AND lo.numeric_result > 150 AND pa.admitted_at > '2022-01-01' AND pa.discharge_date < '2022-12-31'
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 421 AND lo.test_code = 'GLUC' AND lo.numeric_result > 150 AND pa.admitted_at > '2022-01-01' AND pa.discharge_date < '2022-12-31'; Hash Join (cost=2345.67..56789.01 rows=1234 width...
The query planner chose this sub-optimal route because the table statistics are outdated, causing it to severely underestimate the intermediate row counts. This leads to a sequential scan on the patient_admissions table, resulting in a high cost and slow performance. Additionally, the hash join is not efficient due to ...
CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id); CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code); VACUUM ANALYZE patient_admissions; VACUUM ANALYZE lab_orders;
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE pa.clinic_id = 421 AND lo.test_code = 'GLUC' AND lo.numeric_result > 150 AND pa.admitted_at > '2022-01-01' AND pa.discharge_date < '2022-12-31' ORDER BY pa.admission_id
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 metric_type = 'temperature' AND firmware_v = '2.1.4' AND recorded_at > '2022-01-01' GROUP BY device_id, EXTRACT(MONTH FROM recorded_at) AS month, EXTRACT(YEAR FROM recorded_at) AS year
{"plans": [{"nodes": [{"id": "Aggregate", "rows": 1000000, "bytes": 100000000, "spilled": true}, {"id": "GroupBy", "keys": ["device_id", "month", "year"], "rows": 1000000, "bytes": 100000000}], "bytes_spilled": 1000000000, "time_spilled": 10000}]}
The query planner chose this sub-optimal route because the high-cardinality GROUP BY operation on the device_telematics table, combined with the filtering conditions, led to an explosion of intermediate results that exceeded the available work_mem, causing the query to spill to disk. The lack of suitable indexes on the...
CREATE INDEX idx_device_telematics_device_id ON device_telematics (device_id); CREATE INDEX idx_device_telematics_metric_type ON device_telematics (metric_type); CREATE INDEX idx_device_telematics_firmware_v ON device_telematics (firmware_v); CREATE INDEX idx_device_telematics_recorded_at ON device_telematics (recorded...
SELECT device_id, AVG(val) AS avg_val, MAX(val) AS max_val, MIN(val) AS min_val FROM device_telematics WHERE metric_type = 'temperature' AND firmware_v = '2.1.4' AND recorded_at > '2022-01-01' GROUP BY device_id, toYYYYMM(recorded_at) AS month_year
MariaDB 11.2
SELECT d.device_id, SUM(dt.val) AS total_val FROM device_telematics dt JOIN devices d ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.metric_type = 'temperature' AND d.fleet_id = 123 AND d.region = 'North America' ORDER BY dt.recorded_at DESC LIMIT 100;
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "23456.23"}, "table": {"table_name": "dt", "access_type": "range", "possible_keys": ["PRIMARY", "idx_device_id"], "key": "idx_device_id", "used_key_parts": ["device_id"], "key_length": "8", "rows": 100000, "filtered": 10, "extra": "Using where; Using index; U...
The query planner chose this sub-optimal route because the leading timestamp column in the primary key of the device_telematics table is not properly aligned with the filter condition dt.recorded_at > '2022-01-01', resulting in a full partition decompression, and the join with the devices table on device_id is not util...
CREATE INDEX idx_device_id_recorded_at ON device_telematics (device_id, recorded_at); CREATE INDEX idx_fleet_id_region ON devices (fleet_id, region); ANALYZE TABLE device_telematics; ANALYZE TABLE devices;
SELECT d.device_id, SUM(dt.val) AS total_val FROM device_telematics dt USE INDEX (idx_device_id_recorded_at) JOIN devices d USE INDEX (idx_fleet_id_region) ON dt.device_id = d.device_id WHERE dt.recorded_at > '2022-01-01' AND dt.metric_type = 'temperature' AND d.fleet_id = 123 AND d.region = 'North America' ORDER BY dt...
MySQL 8.0
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.status = 'IN_TRANSIT' AND cr.zone_id = 5 AND pe.scan_time > '2022-01-01 00:00:00' AND s.source_hub = 'NEW_YORK'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": 23453.23}, "table": {"table_name": "s", "access_type": "ALL", "rows": 12345, "filtered": 10.0, "index_condition": null}, "table": {"table_name": "pe", "access_type": "ALL", "rows": 54321, "filtered": 5.0, "index_condition": null}, "table": {"table_name": "cr"...
The query planner chose this sub-optimal route because it failed to utilize a composite index that could have efficiently joined the shipments, parcel_events, and carrier_rates tables. As a result, the optimizer resorted to a full table scan for each table, leading to a Cartesian product that significantly increased th...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num, carrier_id, source_hub); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num, scan_time); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id, zone_id); ALTER TABLE shipments ADD CONSTRAINT fk_shipments_carrier...
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND s.carrier_id = cr.carrier_id JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 WHERE s.status = 'IN_TRANSIT' AND pe.scan_time > '2022-01-01 00:00:00' AND s.source_hub ...
MySQL 8.0
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 oi.unit_price > 50 AND i.available_qty > 100 AND oi.order_id IN (SELECT order_id FROM order_items WHERE sku_id = 123AND quantity > 10);
{"query_block": {"select_id":1, "table": {"table_name": "oi", "access_type": "ALL", "rows": 10000, "filtered": 10, "extra": "Using filesort"}, "table": {"table_name": "i", "access_type": "ALL", "rows": 5000, "filtered": 20, "extra": "Using join buffer (Block Nested Loop)"}}}
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned from the subquery, resulting in a full table scan of the order_items table, which led to a large number of rows being joined with the inventory_stock table, causing the join buffer to overflow and r...
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 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 oi.unit_price > 50 AND i.available_qty > 100 AND EXISTS (SELECT 1 FROM order_items o2 WHERE o2.order_id = oi.order_id AND o2.sku_id = 123 AND o2.quantity > ...
CockroachDB v23.2
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id WHERE s.status = 'in_transit' AND pe.scan_time > '2022-01-01' AND cr.weight_kg > 10 AND s.source_hub = 'New York'
{"plans":[{"plan":"HashJoin","args":[{"plan":"HashJoin","args":[{"plan":"Scan","args":[{"plan":"TableScan","args":["shipments"]}]}, {"plan":"Filter","args":[{"plan":"TableScan","args":["parcel_events"]}, "pe.tracking_num = s.tracking_num"]}]}, {"plan":"Filter","args":[{"plan":"TableScan","args":["carrier_rates"]}, "cr....
The query planner chose this sub-optimal route because it couldn't effectively utilize the existing indexes due to the lack of a composite join key, resulting in a Cartesian product row multiplication, thus causing the HashJoin operation to be highly inefficient, as it needs to scan the entire table to find matching ro...
CREATE INDEX idx_shipments_tracking_num ON shipments (tracking_num); CREATE INDEX idx_parcel_events_tracking_num ON parcel_events (tracking_num); CREATE INDEX idx_carrier_rates_carrier_id ON carrier_rates (carrier_id); CREATE INDEX idx_shipments_source_hub ON shipments (source_hub); VACUUM ANALYZE;
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN parcel_events pe ON s.tracking_num = pe.tracking_num AND pe.scan_time > '2022-01-01' JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.weight_kg > 10 WHERE s.status = 'in_transit' AND s.source_hub = 'New York';
PostgreSQL 16.2
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE lo.test_code ILIKE '%thyroid%' AND pa.clinic_id = 145
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE lo.test_code ILIKE '%thyroid%' AND pa.clinic_id = 145 -> Nested Loop Left Join (cost=2345.23..485632.12 rows=118 width=432) -> Seq Scan on patient_admissions pa (cost=0.00..14563.91 rows=234 ...
The query planner chose this sub-optimal route because the ILIKE operator with a leading wildcard ('%thyroid%') disables the use of the available B-Tree index on the test_code column, forcing the planner to perform a sequential scan on the lab_orders table. Additionally, the join order chosen by the planner results in ...
CREATE INDEX idx_lab_orders_test_code ON lab_orders (test_code varchar_pattern_ops); CREATE INDEX idx_patient_admissions_clinic_id ON patient_admissions (clinic_id); VACUUM ANALYZE lab_orders; VACUUM ANALYZE patient_admissions;
SELECT * FROM patient_admissions pa JOIN lab_orders lo ON pa.admission_id = lo.admission_id WHERE lo.test_code ILIKE '%thyroid%' AND pa.clinic_id = 145 AND lo.test_code >= 'thyroid' AND lo.test_code < 'tz'
MariaDB 11.2
SELECT t1.tracking_num, t2.checkpoint, t3.base_rate FROM shipments t1 JOIN parcel_events t2 ON t1.tracking_num = t2.tracking_num JOIN carrier_rates t3 ON t1.carrier_id = t3.carrier_id WHERE t1.status = 'in_transit' AND t2.scan_time > '2022-01-01' AND t3.weight_kg > 50 AND t3.zone_id = 4 GROUP BY t1.tracking_num, t2.che...
EXPLAIN format=json SELECT t1.tracking_num, t2.checkpoint, t3.base_rate FROM shipments t1 JOIN parcel_events t2 ON t1.tracking_num = t2.tracking_num JOIN carrier_rates t3 ON t1.carrier_id = t3.carrier_id WHERE t1.status = 'in_transit' AND t2.scan_time > '2022-01-01' AND t3.weight_kg > 50 AND t3.zone_id = 4 GROUP BY t1....
The query planner chose this sub-optimal route because it incorrectly estimated the number of rows that would be returned from the join operations. As a result, it chose to use a Hash Aggregate operation, which spilled to temporary disk files due to the undersized work_mem, leading to significant performance degradatio...
CREATE INDEX idx_shipments_status ON shipments (status); CREATE INDEX idx_parcel_events_scan_time ON parcel_events (scan_time); CREATE INDEX idx_carrier_rates_zone_id_weight_kg ON carrier_rates (zone_id, weight_kg); ALTER TABLE shipments ADD COLUMN tracking_num_hash INT; UPDATE shipments SET tracking_num_hash = CRC32(t...
SELECT t1.tracking_num, t2.checkpoint, t3.base_rate FROM shipments t1 JOIN parcel_events t2 ON t1.tracking_num_hash = CRC32(t2.tracking_num) JOIN carrier_rates t3 ON t1.carrier_id = t3.carrier_id WHERE t1.status = 'in_transit' AND t2.scan_time > '2022-01-01' AND t3.weight_kg > 50 AND t3.zone_id = 4 GROUP BY t1.tracking...
MariaDB 11.2
SELECT * FROM ledger_entries AS le JOIN accounts AS ac ON le.account_id = ac.id WHERE ac.risk_tier = 'high' AND le.posting_date > '2022-01-01' AND le.amount > 1000 AND ac.user_id = '123e4567-e89b-12d3-a456-426655440000'
{"query_block": {"select_id": 1, "cost": 23451.23, "rows": 10423, "filtered": 10.23, "table": {"table_name": "le", "access_type": "ALL", "possible_keys": ["PRIMARY", "idx_account_id"], "key": null, "key_len": null, "ref": null, "rows": 123456, "filtered": 100, "Extra": "Using where; Using filesort"}}}
The query planner chose this sub-optimal route because the join condition between ledger_entries and accounts is based on a string column (account_id) and an integer column (id), which requires implicit type coercion, preventing the use of the B-Tree index on the accounts table, and instead opting for a full table scan...
CREATE INDEX idx_account_id ON accounts (id); CREATE INDEX idx_ledger_entries_account_id ON ledger_entries (account_id); ALTER TABLE ledger_entries MODIFY COLUMN account_id CHAR(36); ALTER TABLE accounts MODIFY COLUMN id CHAR(36);
SELECT * FROM ledger_entries AS le JOIN accounts AS ac ON le.account_id = ac.id WHERE ac.risk_tier = 'high' AND le.posting_date > '2022-01-01' AND le.amount > 1000 AND ac.user_id = UNHEX(REPLACE('123e4567-e89b-12d3-a456-426655440000', '-', ''))
CockroachDB v23.2
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2023-01-01'
EXPLAIN (ANALYZE, BUFFERS) SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2023-01-01'; -> Filter: (su.is_active = true) AND (wu...
The query planner chose a sub-optimal route because it did not consider creating an index on the is_active column of the subscriptions table, which is a boolean flag. The lack of a partial index on is_active = true led to a sequential scan on the entire subscriptions table, resulting in slower performance. Additionally...
CREATE INDEX idx_subscriptions_is_active ON subscriptions (is_active); CREATE INDEX idx_subscriptions_workspace_id ON subscriptions (workspace_id); CREATE INDEX idx_workspace_users_workspace_id ON workspace_users (workspace_id); VACUUM ANALYZE subscriptions; VACUUM ANALYZE workspace_users;
SELECT su.id, su.plan, su.renewal_date FROM subscriptions su INNER JOIN workspace_users wu ON su.workspace_id = wu.workspace_id WHERE su.is_active = true AND wu.role = 'admin' AND su.renewal_date > '2022-01-01' AND wu.invited_at < '2023-01-01' ORDER BY su.renewal_date;
MySQL 8.0
SELECT * FROM ad_impressions ai INNER JOIN campaigns c ON ai.campaign_id = c.campaign_id WHERE JSON_EXTRACT(ai.metadata, '$.user_info.age') > 25 AND c.daily_budget > 1000 AND ai.served_at > '2022-01-01'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "ai", "access_type": "ALL", "rows": 123456, "filtered": 10, "extra": "Using filesort"}, "table": {"table_name": "c", "access_type": "eq_ref", "rows": 1000, "filtered": 100, "key": "PRIMARY", "key_len": "4"}}}
The query planner chose this sub-optimal route because the JSON_EXTRACT function inside the WHERE filter prevents the optimizer from using a more efficient index on the ad_impressions table. Without a GIN expression index on the metadata column, the optimizer falls back to a full table scan, resulting in high query cos...
CREATE INDEX idx_ad_impressions_metadata ON ad_impressions ((JSON_EXTRACT(metadata, '$.user_info.age'))); ALTER TABLE ad_impressions ADD COLUMN user_info_age INT GENERATED ALWAYS AS (JSON_EXTRACT(metadata, '$.user_info.age')) STORED; CREATE INDEX idx_ad_impressions_user_info_age ON ad_impressions (user_info_age);
SELECT * FROM ad_impressions ai INNER JOIN campaigns c ON ai.campaign_id = c.campaign_id WHERE ai.user_info_age > 25 AND c.daily_budget > 1000 AND ai.served_at > '2022-01-01'
MySQL 8.0
SELECT a.id, b.workspace_id, b.plan FROM audit_logs a JOIN subscriptions b ON a.workspace_id = b.workspace_id WHERE b.is_active = 1 AND a.event_time > '2022-01-01 00:00:00' AND a.actor_id = 12345
EXPLAIN FORMAT=JSON { "query_block": { "select_id": 1, "cost_info": { "query_cost": "43123.20" }, "table": { "table_name": "a", "access_type": "ALL", "rows": 100000, "filtered": 10, "cost_info": { "read_cost": "20292.10", "eval_cost": "10.00", ...
The query planner chose this sub-optimal route because it had to perform a sequential scan on the audit_logs table due to the missing partial index on the is_active column of the subscriptions table. This resulted in a high query cost of 43123.20, indicating that the optimizer had to scan a large number of rows to sati...
CREATE INDEX idx_subscriptions_is_active ON subscriptions (is_active); CREATE INDEX idx_audit_logs_event_time ON audit_logs (event_time); CREATE INDEX idx_audit_logs_actor_id ON audit_logs (actor_id);
SELECT a.id, b.workspace_id, b.plan FROM audit_logs a JOIN subscriptions b ON a.workspace_id = b.workspace_id AND b.is_active = 1 WHERE a.event_time > '2022-01-01 00:00:00' AND a.actor_id = 12345
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": "1042121.60"}, "table": {"table_name": "a", "access_type": "ALL", "possible_keys": ["PRIMARY", "idx_workspace_id"], "key": null, "key_length": null, "ref": null, "rows": 12345678, "filtered": 10.0, "index_condition": null, "extra": "Using filesort"}}}
The MySQL query planner chose this sub-optimal route because it preferred a full table scan on the audit_logs table due to the large OFFSET value, which led to a sequential traversal of millions of historical audit records. This resulted in a high query cost and slow performance. Additionally, the join with the workspa...
CREATE INDEX idx_event_time ON audit_logs (event_time); CREATE INDEX idx_workspace_id ON audit_logs (workspace_id); CREATE INDEX idx_role ON workspace_users (role);
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 s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.status = 'IN_TRANSIT' AND cr.zone_id = 5 AND pe.scan_time > '2022-01-01 00:00:00'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "12345.67"}, "table": {"table_name": "s", "access_type": "ALL", "possible_keys": ["carrier_id"], "key": null, "used_key_parts": null, "key_length": null, "ref": null, "rows": 100000, "filtered": 10, "Extra": "Using filesort"}, "table": {"table_name": "cr", "a...
The query planner chose this sub-optimal route because it failed to utilize a composite index on the join columns (carrier_id, tracking_num), resulting in a Cartesian product and excessive row multiplication. This led to a full table scan on the shipments table and the use of a block nested loop join, causing performan...
CREATE INDEX idx_shipments_carrier_id 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 ON parcel_events (tracking_num);
SELECT s.tracking_num, cr.base_rate, pe.checkpoint FROM shipments s JOIN carrier_rates cr ON s.carrier_id = cr.carrier_id AND cr.zone_id = 5 JOIN parcel_events pe ON s.tracking_num = pe.tracking_num WHERE s.status = 'IN_TRANSIT' AND pe.scan_time > '2022-01-01 00:00:00'
MySQL 8.0
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND user_segment = 'demographic_32' AND served_at > '2022-01-01 00:00:00'
{"query_block": {"select_id": 1, "cost_info": {"query_cost": "431239.00"}, "table": {"table_name": "ad_impressions", "access_type": "ALL", "rows": 50000000, "filtered": 10.0, "index_cond": null, "rows_skipped": null}}}
The query planner chose this sub-optimal route because the ad_impressions table lacks a composite index on the publisher_id and served_at columns, which are used in the window function and filter conditions respectively, resulting in a full table scan and sorting of 50 million rows on disk, leading to high query latenc...
CREATE INDEX idx_ad_impressions_publisher_id_served_at ON ad_impressions (publisher_id, served_at);
SELECT imp_id, campaign_id, ROW_NUMBER() OVER (PARTITION BY publisher_id ORDER BY served_at DESC) AS row_num FROM ad_impressions WHERE bid_cpm > 5.25 AND user_segment = 'demographic_32' AND served_at > '2022-01-01 00:00:00'
MariaDB 11.2
SELECT ps.match_id, ps.player_id, AVG(ps.kills) AS avg_kills, AVG(ps.score) AS avg_score FROM player_stats ps WHERE ps.ping_ms > 50 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, "cost_info": {"query_cost": "3432.98"}, "table": {"table_name": "ps", "access_type": "ALL", "possible_keys": null, "key": null, "used_key_parts": null, "key_length": null, "ref": null, "rows": 102121, "filtered": 10.0, "cost": 3432.98}}}
The query planner chose a full table scan on the player_stats table because the OR condition across the unindexed columns ping_ms and score prevents the optimizer from using any available indexes, resulting in a costly full table scan. Furthermore, the subquery in the IN clause adds additional overhead, making the quer...
CREATE INDEX idx_player_stats_ping_ms ON player_stats (ping_ms); CREATE INDEX idx_player_stats_score ON player_stats (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 avg_kills, AVG(ps.score) AS avg_score FROM player_stats ps USE INDEX (idx_player_stats_ping_ms, idx_player_stats_score) WHERE ps.ping_ms > 50 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...
ClickHouse 24.3
SELECT l.season_id, l.player_id, l.mmr_rating, l.rank_tier FROM leaderboards AS lb JOIN player_stats AS ps ON lb.player_id = ps.player_id JOIN match_sessions AS ms ON ps.match_id = ms.match_id WHERE ms.region = 'NA' AND ms.game_mode = 'Ranked' AND ms.started_at > '2022-01-01' AND lb.mmr_rating > 1500 AND ps.kills > 10 ...
{"stages":{"0":{"name":"Limit","avg_time":"12.50 ms","rows":"50"},"1":{"name":"Sorting","avg_time":"25.10 ms","rows":"100"},"2":{"name":"MergeJoin","avg_time":"37.30 ms","rows":"150"},"3":{"name":"Filter","avg_time":"10.20 ms","rows":"200"},"4":{"name":"TableScan","avg_time":"5.50 ms","rows":"1000"}}}
The query planner chose this sub-optimal route because it prioritized the join order based on the estimated row counts of the tables, which led to a nested loop join with a high number of iterations, resulting in significant lock contention and potential deadlocks due to the lack of deterministic ordering in the join a...
CREATE INDEX idx_leaderboards_mmr_rating ON leaderboards (mmr_rating); CREATE INDEX idx_match_sessions_region_game_mode ON match_sessions (region, game_mode); ALTER TABLE leaderboards ADD COLUMN row_id UInt64; ALTER TABLE match_sessions ADD COLUMN row_id UInt64; ALTER TABLE player_stats ADD COLUMN row_id UInt64;
SELECT /*+ SET join_order = 'lb, ps, ms' */ lb.season_id, lb.player_id, lb.mmr_rating, lb.rank_tier FROM leaderboards AS lb JOIN player_stats AS ps ON lb.player_id = ps.player_id AND lb.row_id = ps.row_id JOIN match_sessions AS ms ON ps.match_id = ms.match_id AND ps.row_id = ms.row_id WHERE ms.region = 'NA' AND ms.game...