Dataset Viewer
Auto-converted to Parquet Duplicate
nl
stringlengths
28
72
good
stringlengths
46
256
bad
stringlengths
50
253
notes
stringlengths
36
170
Get user activity events for a specific user
SELECT u.name, a.event_timestamp, a.event_type FROM users u JOIN ( SELECT user_id, event_timestamp, event_type FROM massive_event_log ) AS a ON u.id = a.user_id WHERE u.id = 123;
WITH all_user_activity AS ( SELECT user_id, event_timestamp, event_type FROM massive_event_log ) SELECT u.name, a.event_timestamp, a.event_type FROM users u JOIN all_user_activity a ON u.id = a.user_id WHERE u.id = 123;
You have a WITH clause that pulls a large amount of data, and you filter it afterward. The planner might materialize the entire CTE result first, then discard most of it.
Get customer purchase history for a specific customer
SELECT c.customer_name, p.purchase_date, p.amount FROM customers c JOIN ( SELECT customer_id, purchase_date, amount FROM huge_purchase_log ) AS p ON c.id = p.customer_id WHERE c.id = 456;
WITH all_purchases AS ( SELECT customer_id, purchase_date, amount FROM huge_purchase_log ) SELECT c.customer_name, p.purchase_date, p.amount FROM customers c JOIN all_purchases p ON c.id = p.customer_id WHERE c.id = 456;
CTE materializes entire purchase log before filtering by customer_id.
Get employee clock-in records for a specific employee
SELECT e.full_name, t.clock_in_time, t.clock_out_time FROM employees e JOIN ( SELECT employee_id, clock_in_time, clock_out_time FROM massive_timesheet_log ) AS t ON e.id = t.employee_id WHERE e.id = 789;
WITH all_timesheets AS ( SELECT employee_id, clock_in_time, clock_out_time FROM massive_timesheet_log ) SELECT e.full_name, t.clock_in_time, t.clock_out_time FROM employees e JOIN all_timesheets t ON e.id = t.employee_id WHERE e.id = 789;
CTE processes all timesheet records before applying employee filter.
Get student exam scores for a specific student
SELECT s.student_name, ex.exam_date, ex.score FROM students s JOIN ( SELECT student_id, exam_date, score FROM large_exam_results ) AS ex ON s.id = ex.student_id WHERE s.id = 101;
WITH all_exam_results AS ( SELECT student_id, exam_date, score FROM large_exam_results ) SELECT s.student_name, ex.exam_date, ex.score FROM students s JOIN all_exam_results ex ON s.id = ex.student_id WHERE s.id = 101;
CTE pulls all exam results before filtering by student.
Get patient visit history for a specific patient
SELECT p.patient_name, v.visit_date, v.diagnosis FROM patients p JOIN ( SELECT patient_id, visit_date, diagnosis FROM enormous_visit_log ) AS v ON p.id = v.patient_id WHERE p.id = 555;
WITH all_visits AS ( SELECT patient_id, visit_date, diagnosis FROM enormous_visit_log ) SELECT p.patient_name, v.visit_date, v.diagnosis FROM patients p JOIN all_visits v ON p.id = v.patient_id WHERE p.id = 555;
CTE materializes entire visit log before patient filter.
Get vehicle maintenance records for a specific vehicle
SELECT v.vehicle_number, m.service_date, m.service_type FROM vehicles v JOIN ( SELECT vehicle_id, service_date, service_type FROM massive_maintenance_log ) AS m ON v.id = m.vehicle_id WHERE v.id = 777;
WITH all_maintenance AS ( SELECT vehicle_id, service_date, service_type FROM massive_maintenance_log ) SELECT v.vehicle_number, m.service_date, m.service_type FROM vehicles v JOIN all_maintenance m ON v.id = m.vehicle_id WHERE v.id = 777;
CTE loads all maintenance records before filtering by vehicle.
Get product view events for a specific product
SELECT pr.product_name, pv.view_timestamp, pv.user_id FROM products pr JOIN ( SELECT product_id, view_timestamp, user_id FROM huge_product_views ) AS pv ON pr.id = pv.product_id WHERE pr.id = 999;
WITH all_product_views AS ( SELECT product_id, view_timestamp, user_id FROM huge_product_views ) SELECT pr.product_name, pv.view_timestamp, pv.user_id FROM products pr JOIN all_product_views pv ON pr.id = pv.product_id WHERE pr.id = 999;
CTE processes all product view events before product filter.
Get account transactions for a specific account
SELECT a.account_number, t.transaction_date, t.amount FROM accounts a JOIN ( SELECT account_id, transaction_date, amount FROM massive_transaction_log ) AS t ON a.id = t.account_id WHERE a.id = 1234;
WITH all_transactions AS ( SELECT account_id, transaction_date, amount FROM massive_transaction_log ) SELECT a.account_number, t.transaction_date, t.amount FROM accounts a JOIN all_transactions t ON a.id = t.account_id WHERE a.id = 1234;
CTE materializes all transactions before account filter.
Get sensor readings for a specific sensor
SELECT s.sensor_name, r.reading_time, r.value FROM sensors s JOIN ( SELECT sensor_id, reading_time, value FROM enormous_sensor_readings ) AS r ON s.id = r.sensor_id WHERE s.id = 321;
WITH all_readings AS ( SELECT sensor_id, reading_time, value FROM enormous_sensor_readings ) SELECT s.sensor_name, r.reading_time, r.value FROM sensors s JOIN all_readings r ON s.id = r.sensor_id WHERE s.id = 321;
CTE pulls all sensor readings before filtering by sensor.
Get shipment tracking events for a specific shipment
SELECT sh.tracking_number, te.event_time, te.location FROM shipments sh JOIN ( SELECT shipment_id, event_time, location FROM huge_tracking_events ) AS te ON sh.id = te.shipment_id WHERE sh.id = 888;
WITH all_tracking_events AS ( SELECT shipment_id, event_time, location FROM huge_tracking_events ) SELECT sh.tracking_number, te.event_time, te.location FROM shipments sh JOIN all_tracking_events te ON sh.id = te.shipment_id WHERE sh.id = 888;
CTE processes entire tracking log before shipment filter.
Get device error logs for a specific device
SELECT d.device_name, el.error_timestamp, el.error_code FROM devices d JOIN ( SELECT device_id, error_timestamp, error_code FROM massive_error_log ) AS el ON d.id = el.device_id WHERE d.id = 654;
WITH all_error_logs AS ( SELECT device_id, error_timestamp, error_code FROM massive_error_log ) SELECT d.device_name, el.error_timestamp, el.error_code FROM devices d JOIN all_error_logs el ON d.id = el.device_id WHERE d.id = 654;
CTE materializes all error logs before device filter.
Get users created before 2020 or inactive since 2022
SELECT id, username FROM users WHERE created_at < '2020-01-01' UNION ALL SELECT id, username FROM users WHERE last_login < '2022-01-01' AND created_at >= '2020-01-01';
SELECT id, username FROM users WHERE created_at < '2020-01-01' OR last_login < '2022-01-01';
UNION ALL allows efficient use of both indexes, while OR may cause full table scan.
Get products created before 2019 or out of stock since 2023
SELECT id, product_name FROM products WHERE created_at < '2019-01-01' UNION ALL SELECT id, product_name FROM products WHERE last_stocked < '2023-01-01' AND created_at >= '2019-01-01';
SELECT id, product_name FROM products WHERE created_at < '2019-01-01' OR last_stocked < '2023-01-01';
Planner can use separate indexes with UNION ALL instead of choosing one or scanning.
Get employees hired after 2018 or terminated before 2023
SELECT id, name FROM employees WHERE hire_date > '2018-12-31' UNION ALL SELECT id, name FROM employees WHERE termination_date < '2023-01-01' AND hire_date <= '2018-12-31';
SELECT id, name FROM employees WHERE hire_date > '2018-12-31' OR termination_date < '2023-01-01';
UNION ALL enables dual index usage for better performance.
Get orders placed before 2021 or cancelled since 2024
SELECT id, order_number FROM orders WHERE order_date < '2021-01-01' UNION ALL SELECT id, order_number FROM orders WHERE cancelled_date >= '2024-01-01' AND order_date >= '2021-01-01';
SELECT id, order_number FROM orders WHERE order_date < '2021-01-01' OR cancelled_date >= '2024-01-01';
Separate index scans via UNION ALL vs potential full scan with OR.
Get students enrolled after 2015 or graduated before 2020
SELECT id, name FROM students WHERE enrollment_date > '2015-12-31' UNION ALL SELECT id, name FROM students WHERE graduation_date < '2020-01-01' AND enrollment_date <= '2015-12-31';
SELECT id, name FROM students WHERE enrollment_date > '2015-12-31' OR graduation_date < '2020-01-01';
UNION ALL allows planner to use both indexes efficiently.
Get accounts opened before 2017 or closed since 2022
SELECT id, account_number FROM accounts WHERE opened_date < '2017-01-01' UNION ALL SELECT id, account_number FROM accounts WHERE closed_date >= '2022-01-01' AND opened_date >= '2017-01-01';
SELECT id, account_number FROM accounts WHERE opened_date < '2017-01-01' OR closed_date >= '2022-01-01';
UNION ALL prevents index selection confusion with OR clause.
Get vehicles registered before 2016 or sold since 2023
SELECT id, vin FROM vehicles WHERE registration_date < '2016-01-01' UNION ALL SELECT id, vin FROM vehicles WHERE sale_date >= '2023-01-01' AND registration_date >= '2016-01-01';
SELECT id, vin FROM vehicles WHERE registration_date < '2016-01-01' OR sale_date >= '2023-01-01';
Dual index usage with UNION ALL vs suboptimal OR execution.
Get properties listed before 2018 or rented since 2024
SELECT id, address FROM properties WHERE listed_date < '2018-01-01' UNION ALL SELECT id, address FROM properties WHERE rented_date >= '2024-01-01' AND listed_date >= '2018-01-01';
SELECT id, address FROM properties WHERE listed_date < '2018-01-01' OR rented_date >= '2024-01-01';
UNION ALL enables efficient index scans on both conditions.
Get subscriptions created before 2019 or expired since 2023
SELECT id, subscription_id FROM subscriptions WHERE created_at < '2019-01-01' UNION ALL SELECT id, subscription_id FROM subscriptions WHERE expired_at >= '2023-01-01' AND created_at >= '2019-01-01';
SELECT id, subscription_id FROM subscriptions WHERE created_at < '2019-01-01' OR expired_at >= '2023-01-01';
UNION ALL allows both indexes to be used independently.
Get tickets created before 2020 or resolved since 2024
SELECT id, ticket_number FROM tickets WHERE created_at < '2020-01-01' UNION ALL SELECT id, ticket_number FROM tickets WHERE resolved_at >= '2024-01-01' AND created_at >= '2020-01-01';
SELECT id, ticket_number FROM tickets WHERE created_at < '2020-01-01' OR resolved_at >= '2024-01-01';
UNION ALL prevents planner confusion with multiple indexes.
Get invoices issued before 2021 or paid since 2024
SELECT id, invoice_number FROM invoices WHERE issue_date < '2021-01-01' UNION ALL SELECT id, invoice_number FROM invoices WHERE payment_date >= '2024-01-01' AND issue_date >= '2021-01-01';
SELECT id, invoice_number FROM invoices WHERE issue_date < '2021-01-01' OR payment_date >= '2024-01-01';
UNION ALL enables optimal dual index usage.
Get campaigns launched before 2022 or ended since 2024
SELECT id, campaign_name FROM campaigns WHERE launch_date < '2022-01-01' UNION ALL SELECT id, campaign_name FROM campaigns WHERE end_date >= '2024-01-01' AND launch_date >= '2022-01-01';
SELECT id, campaign_name FROM campaigns WHERE launch_date < '2022-01-01' OR end_date >= '2024-01-01';
UNION ALL allows efficient use of separate indexes.
Find customers who have never placed an order
SELECT c.name FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id );
SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
NOT EXISTS handles NULLs correctly and uses efficient anti-join algorithms.
Find products that have never been ordered
SELECT p.product_name FROM products p WHERE NOT EXISTS ( SELECT 1 FROM order_items oi WHERE oi.product_id = p.id );
SELECT product_name FROM products WHERE id NOT IN (SELECT product_id FROM order_items);
NOT IN fails with NULL values; NOT EXISTS is NULL-safe with anti-join.
Find employees who have never been assigned to a project
SELECT e.name FROM employees e WHERE NOT EXISTS ( SELECT 1 FROM project_assignments pa WHERE pa.employee_id = e.id );
SELECT name FROM employees WHERE id NOT IN (SELECT employee_id FROM project_assignments);
NOT EXISTS uses anti-join; NOT IN generates poor plans with NULLs.
Find students who have never enrolled in a course
SELECT s.student_name FROM students s WHERE NOT EXISTS ( SELECT 1 FROM enrollments en WHERE en.student_id = s.id );
SELECT student_name FROM students WHERE id NOT IN (SELECT student_id FROM enrollments);
NOT EXISTS is NULL-safe and efficient; NOT IN is problematic.
Find stores that have never recorded a sale
SELECT st.store_name FROM stores st WHERE NOT EXISTS ( SELECT 1 FROM sales sa WHERE sa.store_id = st.id );
SELECT store_name FROM stores WHERE id NOT IN (SELECT store_id FROM sales);
NOT EXISTS handles NULL store_id correctly with anti-join.
Find authors who have never published a book
SELECT a.author_name FROM authors a WHERE NOT EXISTS ( SELECT 1 FROM books b WHERE b.author_id = a.id );
SELECT author_name FROM authors WHERE id NOT IN (SELECT author_id FROM books);
NOT EXISTS uses efficient anti-join vs NOT IN poor plan.
Find suppliers who have never shipped inventory
SELECT sp.supplier_name FROM suppliers sp WHERE NOT EXISTS ( SELECT 1 FROM shipments sh WHERE sh.supplier_id = sp.id );
SELECT supplier_name FROM suppliers WHERE id NOT IN (SELECT supplier_id FROM shipments);
NOT EXISTS is NULL-safe; NOT IN breaks with NULL values.
Find categories with no active listings
SELECT cat.category_name FROM categories cat WHERE NOT EXISTS ( SELECT 1 FROM listings li WHERE li.category_id = cat.id AND li.is_active = true );
SELECT category_name FROM categories WHERE id NOT IN (SELECT category_id FROM listings WHERE is_active = true);
NOT EXISTS handles NULLs and uses anti-join efficiently.
Find departments with no current employees
SELECT d.dept_name FROM departments d WHERE NOT EXISTS ( SELECT 1 FROM employees e WHERE e.department_id = d.id AND e.status = 'active' );
SELECT dept_name FROM departments WHERE id NOT IN (SELECT department_id FROM employees WHERE status = 'active');
NOT EXISTS is NULL-safe with efficient execution plan.
Find warehouses with no inventory
SELECT w.warehouse_name FROM warehouses w WHERE NOT EXISTS ( SELECT 1 FROM inventory i WHERE i.warehouse_id = w.id AND i.quantity > 0 );
SELECT warehouse_name FROM warehouses WHERE id NOT IN (SELECT warehouse_id FROM inventory WHERE quantity > 0);
NOT EXISTS uses anti-join; NOT IN generates poor plans.
Find courses with no enrolled students
SELECT co.course_name FROM courses co WHERE NOT EXISTS ( SELECT 1 FROM enrollments en WHERE en.course_id = co.id );
SELECT course_name FROM courses WHERE id NOT IN (SELECT course_id FROM enrollments);
NOT EXISTS handles NULLs correctly vs NOT IN failures.
Get all users with their most recent order date
SELECT u.id, u.name, o_stats.last_order_date FROM users u LEFT JOIN ( SELECT user_id, MAX(order_date) AS last_order_date FROM orders GROUP BY user_id ) AS o_stats ON u.id = o_stats.user_id;
SELECT u.id, u.name, (SELECT MAX(o.order_date) FROM orders o WHERE o.user_id = u.id) AS last_order_date FROM users u;
Pre-aggregated join does one pass; correlated subquery runs per user.
Get all customers with their total spending
SELECT c.id, c.name, order_totals.total_spent FROM customers c LEFT JOIN ( SELECT customer_id, SUM(amount) AS total_spent FROM orders GROUP BY customer_id ) AS order_totals ON c.id = order_totals.customer_id;
SELECT c.id, c.name, (SELECT SUM(o.amount) FROM orders o WHERE o.customer_id = c.id) AS total_spent FROM customers c;
Single aggregation pass vs per-customer subquery execution.
Get all products with their average rating
SELECT p.id, p.product_name, rating_stats.avg_rating FROM products p LEFT JOIN ( SELECT product_id, AVG(rating) AS avg_rating FROM reviews GROUP BY product_id ) AS rating_stats ON p.id = rating_stats.product_id;
SELECT p.id, p.product_name, (SELECT AVG(r.rating) FROM reviews r WHERE r.product_id = p.id) AS avg_rating FROM products p;
Pre-computed aggregation vs repeated calculations per product.
Get all employees with their total hours worked
SELECT e.id, e.name, hours_stats.total_hours FROM employees e LEFT JOIN ( SELECT employee_id, SUM(hours) AS total_hours FROM timesheets GROUP BY employee_id ) AS hours_stats ON e.id = hours_stats.employee_id;
SELECT e.id, e.name, (SELECT SUM(t.hours) FROM timesheets t WHERE t.employee_id = e.id) AS total_hours FROM employees e;
One aggregation pass vs N subquery executions.
Get all students with their GPA
SELECT s.id, s.student_name, grade_stats.gpa FROM students s LEFT JOIN ( SELECT student_id, AVG(grade) AS gpa FROM grades GROUP BY student_id ) AS grade_stats ON s.id = grade_stats.student_id;
SELECT s.id, s.student_name, (SELECT AVG(g.grade) FROM grades g WHERE g.student_id = s.id) AS gpa FROM students s;
Single pass aggregation vs per-student subquery.
Get all departments with their average salary
SELECT d.id, d.name, salary_stats.avg_salary FROM departments d LEFT JOIN ( SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY department_id ) AS salary_stats ON d.id = salary_stats.department_id;
SELECT d.id, d.name, (SELECT AVG(e.salary) FROM employees e WHERE e.department_id = d.id) AS avg_salary FROM departments d;
Pre-aggregation is efficient; correlated subquery recalculates per department.
Get all warehouses with their total inventory count
SELECT w.id, w.warehouse_name, inv_stats.total_quantity FROM warehouses w LEFT JOIN ( SELECT warehouse_id, SUM(quantity) AS total_quantity FROM inventory GROUP BY warehouse_id ) AS inv_stats ON w.id = inv_stats.warehouse_id;
SELECT w.id, w.warehouse_name, (SELECT SUM(i.quantity) FROM inventory i WHERE i.warehouse_id = w.id) AS total_quantity FROM warehouses w;
One aggregation vs repeated sums per warehouse.
Get all categories with their product count
SELECT cat.id, cat.category_name, prod_stats.product_count FROM categories cat LEFT JOIN ( SELECT category_id, COUNT(*) AS product_count FROM products GROUP BY category_id ) AS prod_stats ON cat.id = prod_stats.category_id;
SELECT cat.id, cat.category_name, (SELECT COUNT(*) FROM products p WHERE p.category_id = cat.id) AS product_count FROM categories cat;
Single count operation vs per-category counting.
Get all projects with their total budget
SELECT pr.id, pr.project_name, budget_stats.total_budget FROM projects pr LEFT JOIN ( SELECT project_id, SUM(budget) AS total_budget FROM project_tasks GROUP BY project_id ) AS budget_stats ON pr.id = budget_stats.project_id;
SELECT pr.id, pr.project_name, (SELECT SUM(pt.budget) FROM project_tasks pt WHERE pt.project_id = pr.id) AS total_budget FROM projects pr;
Pre-aggregated join efficient; subquery runs per project.
Get all locations with their total revenue
SELECT l.id, l.location_name, revenue_stats.total_revenue FROM locations l LEFT JOIN ( SELECT location_id, SUM(revenue) AS total_revenue FROM sales GROUP BY location_id ) AS revenue_stats ON l.id = revenue_stats.location_id;
SELECT l.id, l.location_name, (SELECT SUM(s.revenue) FROM sales s WHERE s.location_id = l.id) AS total_revenue FROM locations l;
One aggregation pass vs per-location subquery execution.
Get all authors with their book count
SELECT a.id, a.author_name, book_stats.book_count FROM authors a LEFT JOIN ( SELECT author_id, COUNT(*) AS book_count FROM books GROUP BY author_id ) AS book_stats ON a.id = book_stats.author_id;
SELECT a.id, a.author_name, (SELECT COUNT(*) FROM books b WHERE b.author_id = a.id) AS book_count FROM authors a;
Single counting operation vs repeated counts per author.
Join tables filtering by document IDs in both tables
SELECT papa.six FROM tango_zulu papa INNER JOIN hotel alpha ON papa.six = alpha.quebec WHERE alpha.quebec = ANY (:documents) AND papa.six = ANY (:documents);
SELECT papa.six FROM tango_zulu papa INNER JOIN hotel alpha ON papa.six = alpha.quebec WHERE alpha.quebec = ANY (:documents);
Redundant predicate allows both tables to be filtered before join.
Join inventory and warehouse tables filtering by location codes
SELECT inv.item_code FROM inventory inv INNER JOIN warehouse wh ON inv.warehouse_id = wh.id WHERE wh.location_code = ANY (:locations) AND inv.warehouse_id = ANY (:location_ids);
SELECT inv.item_code FROM inventory inv INNER JOIN warehouse wh ON inv.warehouse_id = wh.id WHERE wh.location_code = ANY (:locations);
Both-side filtering enables better join algorithm selection.
Join orders and customers filtering by region IDs
SELECT o.order_id FROM orders o INNER JOIN customers c ON o.customer_id = c.id WHERE c.region_id = ANY (:regions) AND o.customer_id = ANY (:customer_ids);
SELECT o.order_id FROM orders o INNER JOIN customers c ON o.customer_id = c.id WHERE c.region_id = ANY (:regions);
Redundant predicate allows index usage on both tables before join.
Join products and suppliers filtering by supplier codes
SELECT p.product_name FROM products p INNER JOIN suppliers s ON p.supplier_id = s.id WHERE s.supplier_code = ANY (:codes) AND p.supplier_id = ANY (:supplier_ids);
SELECT p.product_name FROM products p INNER JOIN suppliers s ON p.supplier_id = s.id WHERE s.supplier_code = ANY (:codes);
Filtering both sides before join improves performance.
Join employees and departments filtering by department codes
SELECT e.employee_name FROM employees e INNER JOIN departments d ON e.department_id = d.id WHERE d.dept_code = ANY (:codes) AND e.department_id = ANY (:dept_ids);
SELECT e.employee_name FROM employees e INNER JOIN departments d ON e.department_id = d.id WHERE d.dept_code = ANY (:codes);
Redundant predicate enables dual index filtering.
Join students and courses filtering by course codes
SELECT s.student_name FROM students s INNER JOIN enrollments en ON s.id = en.student_id INNER JOIN courses c ON en.course_id = c.id WHERE c.course_code = ANY (:codes) AND en.course_id = ANY (:course_ids);
SELECT s.student_name FROM students s INNER JOIN enrollments en ON s.id = en.student_id INNER JOIN courses c ON en.course_id = c.id WHERE c.course_code = ANY (:codes);
Both-side filtering allows better join plan.
Join shipments and carriers filtering by carrier codes
SELECT sh.tracking_number FROM shipments sh INNER JOIN carriers c ON sh.carrier_id = c.id WHERE c.carrier_code = ANY (:codes) AND sh.carrier_id = ANY (:carrier_ids);
SELECT sh.tracking_number FROM shipments sh INNER JOIN carriers c ON sh.carrier_id = c.id WHERE c.carrier_code = ANY (:codes);
Redundant predicate on shipments enables index filtering before join.
Join transactions and accounts filtering by account types
SELECT t.transaction_id FROM transactions t INNER JOIN accounts a ON t.account_id = a.id WHERE a.account_type = ANY (:types) AND t.account_id = ANY (:account_ids);
SELECT t.transaction_id FROM transactions t INNER JOIN accounts a ON t.account_id = a.id WHERE a.account_type = ANY (:types);
Filtering both tables before join improves execution plan.
Join bookings and rooms filtering by room types
SELECT b.booking_id FROM bookings b INNER JOIN rooms r ON b.room_id = r.id WHERE r.room_type = ANY (:types) AND b.room_id = ANY (:room_ids);
SELECT b.booking_id FROM bookings b INNER JOIN rooms r ON b.room_id = r.id WHERE r.room_type = ANY (:types);
Redundant predicate allows dual index usage before join.
Join tickets and users filtering by user groups
SELECT tk.ticket_number FROM tickets tk INNER JOIN users u ON tk.user_id = u.id WHERE u.user_group = ANY (:groups) AND tk.user_id = ANY (:user_ids);
SELECT tk.ticket_number FROM tickets tk INNER JOIN users u ON tk.user_id = u.id WHERE u.user_group = ANY (:groups);
Both-side filtering enables better join algorithm.
Join sales and regions filtering by region codes
SELECT sl.sale_id FROM sales sl INNER JOIN regions r ON sl.region_id = r.id WHERE r.region_code = ANY (:codes) AND sl.region_id = ANY (:region_ids);
SELECT sl.sale_id FROM sales sl INNER JOIN regions r ON sl.region_id = r.id WHERE r.region_code = ANY (:codes);
Redundant predicate allows index filtering on both tables.
Join two tables on matching values greater than 99000
SELECT t1.a, t2.a FROM t1 JOIN t2 USING (a) WHERE (t1.a > 99000) AND (t2.a > 99000) ORDER BY t1.a LIMIT 100;
SELECT t1.a, t2.a FROM t1 JOIN t2 USING (a) WHERE (t1.a > 99000) ORDER BY t1.a LIMIT 100;
Redundant predicate helps optimizer filter both sides before join.
Join two tables on matching values greater than 50000
SELECT x.value, y.value FROM table_x x JOIN table_y y USING (value) WHERE (x.value > 50000) AND (y.value > 50000) ORDER BY x.value LIMIT 100;
SELECT x.value, y.value FROM table_x x JOIN table_y y USING (value) WHERE (x.value > 50000) ORDER BY x.value LIMIT 100;
Both-side filtering prevents nested loop with full scan.
Join orders and items on amount greater than 1000
SELECT o.order_id, oi.item_id FROM orders o JOIN order_items oi USING (order_id) WHERE (o.total_amount > 1000) AND (oi.order_id IN (SELECT id FROM orders WHERE total_amount > 1000)) ORDER BY o.order_id LIMIT 50;
SELECT o.order_id, oi.item_id FROM orders o JOIN order_items oi USING (order_id) WHERE (o.total_amount > 1000) ORDER BY o.order_id LIMIT 50;
Redundant filtering enables index usage on both tables.
Join employees and salaries on salary greater than 100000
SELECT e.employee_id, s.salary FROM employees e JOIN salaries s USING (employee_id) WHERE (s.salary > 100000) AND (e.employee_id IN (SELECT employee_id FROM salaries WHERE salary > 100000)) ORDER BY e.employee_id LIMIT 75;
SELECT e.employee_id, s.salary FROM employees e JOIN salaries s USING (employee_id) WHERE (s.salary > 100000) ORDER BY e.employee_id LIMIT 75;
Dual filtering improves join performance.
Join products and prices on price greater than 500
SELECT p.product_id, pr.price FROM products p JOIN prices pr USING (product_id) WHERE (pr.price > 500) AND (p.product_id IN (SELECT product_id FROM prices WHERE price > 500)) ORDER BY p.product_id LIMIT 100;
SELECT p.product_id, pr.price FROM products p JOIN prices pr USING (product_id) WHERE (pr.price > 500) ORDER BY p.product_id LIMIT 100;
Both-side predicates enable better execution plan.
Join students and scores on score greater than 90
SELECT st.student_id, sc.score FROM students st JOIN test_scores sc USING (student_id) WHERE (sc.score > 90) AND (st.student_id IN (SELECT student_id FROM test_scores WHERE score > 90)) ORDER BY st.student_id LIMIT 50;
SELECT st.student_id, sc.score FROM students st JOIN test_scores sc USING (student_id) WHERE (sc.score > 90) ORDER BY st.student_id LIMIT 50;
Redundant predicate allows index filtering before join.
Join accounts and balances on balance greater than 10000
SELECT a.account_id, b.balance FROM accounts a JOIN balances b USING (account_id) WHERE (b.balance > 10000) AND (a.account_id IN (SELECT account_id FROM balances WHERE balance > 10000)) ORDER BY a.account_id LIMIT 100;
SELECT a.account_id, b.balance FROM accounts a JOIN balances b USING (account_id) WHERE (b.balance > 10000) ORDER BY a.account_id LIMIT 100;
Dual filtering prevents inefficient join algorithm.
Join vehicles and mileages on mileage greater than 100000
SELECT v.vehicle_id, m.mileage FROM vehicles v JOIN vehicle_mileage m USING (vehicle_id) WHERE (m.mileage > 100000) AND (v.vehicle_id IN (SELECT vehicle_id FROM vehicle_mileage WHERE mileage > 100000)) ORDER BY v.vehicle_id LIMIT 50;
SELECT v.vehicle_id, m.mileage FROM vehicles v JOIN vehicle_mileage m USING (vehicle_id) WHERE (m.mileage > 100000) ORDER BY v.vehicle_id LIMIT 50;
Both-side filtering improves join efficiency.
Join properties and valuations on value greater than 500000
SELECT pr.property_id, val.value FROM properties pr JOIN valuations val USING (property_id) WHERE (val.value > 500000) AND (pr.property_id IN (SELECT property_id FROM valuations WHERE value > 500000)) ORDER BY pr.property_id LIMIT 100;
SELECT pr.property_id, val.value FROM properties pr JOIN valuations val USING (property_id) WHERE (val.value > 500000) ORDER BY pr.property_id LIMIT 100;
Redundant predicate enables dual index usage.
Join campaigns and budgets on budget greater than 50000
SELECT c.campaign_id, b.budget FROM campaigns c JOIN campaign_budgets b USING (campaign_id) WHERE (b.budget > 50000) AND (c.campaign_id IN (SELECT campaign_id FROM campaign_budgets WHERE budget > 50000)) ORDER BY c.campaign_id LIMIT 75;
SELECT c.campaign_id, b.budget FROM campaigns c JOIN campaign_budgets b USING (campaign_id) WHERE (b.budget > 50000) ORDER BY c.campaign_id LIMIT 75;
Both-side filtering allows better join plan.
Join projects and costs on cost greater than 100000
SELECT pj.project_id, pc.cost FROM projects pj JOIN project_costs pc USING (project_id) WHERE (pc.cost > 100000) AND (pj.project_id IN (SELECT project_id FROM project_costs WHERE cost > 100000)) ORDER BY pj.project_id LIMIT 50;
SELECT pj.project_id, pc.cost FROM projects pj JOIN project_costs pc USING (project_id) WHERE (pc.cost > 100000) ORDER BY pj.project_id LIMIT 50;
Redundant filtering enables efficient join execution.
Join two tables where matching values are in a specific list
SELECT t1.a, t2.a FROM t1 JOIN t2 USING (a) WHERE (t1.a IN (99000, 99001)) AND (t2.a IN (99000, 99001)) ORDER BY t1.a LIMIT 100;
SELECT t1.a, t2.a FROM t1 JOIN t2 USING (a) WHERE (t1.a IN (99000, 99001)) ORDER BY t1.a LIMIT 100;
Redundant IN predicate enables index scans on both tables.
Join categories and products on specific category IDs
SELECT c.category_id, p.product_id FROM categories c JOIN products p USING (category_id) WHERE (c.category_id IN (1, 2, 3)) AND (p.category_id IN (1, 2, 3)) ORDER BY c.category_id LIMIT 100;
SELECT c.category_id, p.product_id FROM categories c JOIN products p USING (category_id) WHERE (c.category_id IN (1, 2, 3)) ORDER BY c.category_id LIMIT 100;
Both-side filtering allows efficient index usage.
Join departments and employees on specific department IDs
SELECT d.dept_id, e.employee_id FROM departments d JOIN employees e USING (dept_id) WHERE (d.dept_id IN (10, 20, 30)) AND (e.dept_id IN (10, 20, 30)) ORDER BY d.dept_id LIMIT 150;
SELECT d.dept_id, e.employee_id FROM departments d JOIN employees e USING (dept_id) WHERE (d.dept_id IN (10, 20, 30)) ORDER BY d.dept_id LIMIT 150;
Redundant predicate enables dual index scans.
Join warehouses and inventory on specific warehouse IDs
SELECT w.warehouse_id, i.item_id FROM warehouses w JOIN inventory i USING (warehouse_id) WHERE (w.warehouse_id IN (100, 101, 102)) AND (i.warehouse_id IN (100, 101, 102)) ORDER BY w.warehouse_id LIMIT 200;
SELECT w.warehouse_id, i.item_id FROM warehouses w JOIN inventory i USING (warehouse_id) WHERE (w.warehouse_id IN (100, 101, 102)) ORDER BY w.warehouse_id LIMIT 200;
Both-side filtering improves join performance.
Join regions and stores on specific region IDs
SELECT r.region_id, s.store_id FROM regions r JOIN stores s USING (region_id) WHERE (r.region_id IN (5, 6, 7)) AND (s.region_id IN (5, 6, 7)) ORDER BY r.region_id LIMIT 100;
SELECT r.region_id, s.store_id FROM regions r JOIN stores s USING (region_id) WHERE (r.region_id IN (5, 6, 7)) ORDER BY r.region_id LIMIT 100;
Redundant IN allows index filtering on both tables.
Join courses and enrollments on specific course IDs
SELECT co.course_id, en.student_id FROM courses co JOIN enrollments en USING (course_id) WHERE (co.course_id IN (201, 202, 203)) AND (en.course_id IN (201, 202, 203)) ORDER BY co.course_id LIMIT 250;
SELECT co.course_id, en.student_id FROM courses co JOIN enrollments en USING (course_id) WHERE (co.course_id IN (201, 202, 203)) ORDER BY co.course_id LIMIT 250;
Dual filtering enables efficient join algorithm.
Join projects and tasks on specific project IDs
SELECT pj.project_id, tk.task_id FROM projects pj JOIN tasks tk USING (project_id) WHERE (pj.project_id IN (50, 51, 52)) AND (tk.project_id IN (50, 51, 52)) ORDER BY pj.project_id LIMIT 100;
SELECT pj.project_id, tk.task_id FROM projects pj JOIN tasks tk USING (project_id) WHERE (pj.project_id IN (50, 51, 52)) ORDER BY pj.project_id LIMIT 100;
Both-side predicates allow index scans before join.
Join customers and orders on specific customer IDs
SELECT c.customer_id, o.order_id FROM customers c JOIN orders o USING (customer_id) WHERE (c.customer_id IN (1000, 1001, 1002)) AND (o.customer_id IN (1000, 1001, 1002)) ORDER BY c.customer_id LIMIT 150;
SELECT c.customer_id, o.order_id FROM customers c JOIN orders o USING (customer_id) WHERE (c.customer_id IN (1000, 1001, 1002)) ORDER BY c.customer_id LIMIT 150;
Redundant filtering enables better join plan.
Join authors and books on specific author IDs
SELECT a.author_id, b.book_id FROM authors a JOIN books b USING (author_id) WHERE (a.author_id IN (15, 16, 17)) AND (b.author_id IN (15, 16, 17)) ORDER BY a.author_id LIMIT 100;
SELECT a.author_id, b.book_id FROM authors a JOIN books b USING (author_id) WHERE (a.author_id IN (15, 16, 17)) ORDER BY a.author_id LIMIT 100;
Both-side filtering improves execution efficiency.
Join suppliers and products on specific supplier IDs
SELECT sp.supplier_id, pr.product_id FROM suppliers sp JOIN products pr USING (supplier_id) WHERE (sp.supplier_id IN (25, 26, 27)) AND (pr.supplier_id IN (25, 26, 27)) ORDER BY sp.supplier_id LIMIT 200;
SELECT sp.supplier_id, pr.product_id FROM suppliers sp JOIN products pr USING (supplier_id) WHERE (sp.supplier_id IN (25, 26, 27)) ORDER BY sp.supplier_id LIMIT 200;
Redundant IN predicate enables dual index usage.
Join teams and members on specific team IDs
SELECT tm.team_id, mb.member_id FROM teams tm JOIN team_members mb USING (team_id) WHERE (tm.team_id IN (8, 9, 10)) AND (mb.team_id IN (8, 9, 10)) ORDER BY tm.team_id LIMIT 100;
SELECT tm.team_id, mb.member_id FROM teams tm JOIN team_members mb USING (team_id) WHERE (tm.team_id IN (8, 9, 10)) ORDER BY tm.team_id LIMIT 100;
Both-side filtering allows efficient join.
Find all records where JSON age field equals 27
SELECT * FROM json_stack WHERE json->>'age' = '27';
SELECT * FROM json_stack WHERE json @> '{"age":27}'::jsonb;
Text extraction allows B-tree index and better statistics.
Find all records where JSON status field equals active
SELECT * FROM documents WHERE metadata->>'status' = 'active';
SELECT * FROM documents WHERE metadata @> '{"status":"active"}'::jsonb;
->> operator enables B-tree index usage and accurate cardinality.
Find all records where JSON city field equals Boston
SELECT * FROM locations WHERE data->>'city' = 'Boston';
SELECT * FROM locations WHERE data @> '{"city":"Boston"}'::jsonb;
Text extraction with ->> allows standard index and statistics.
Find all records where JSON role field equals admin
SELECT * FROM users WHERE profile->>'role' = 'admin';
SELECT * FROM users WHERE profile @> '{"role":"admin"}'::jsonb;
->> enables B-tree index; @> uses GIN with less accurate stats.
Find all records where JSON category field equals electronics
SELECT * FROM products WHERE attributes->>'category' = 'electronics';
SELECT * FROM products WHERE attributes @> '{"category":"electronics"}'::jsonb;
Text extraction allows efficient B-tree index usage.
Find all records where JSON priority field equals high
SELECT * FROM tasks WHERE settings->>'priority' = 'high';
SELECT * FROM tasks WHERE settings @> '{"priority":"high"}'::jsonb;
->> operator provides better selectivity estimates.
Find all records where JSON type field equals premium
SELECT * FROM accounts WHERE config->>'type' = 'premium';
SELECT * FROM accounts WHERE config @> '{"type":"premium"}'::jsonb;
Text extraction enables standard indexing and statistics.
Find all records where JSON level field equals 5
SELECT * FROM game_progress WHERE data->>'level' = '5';
SELECT * FROM game_progress WHERE data @> '{"level":5}'::jsonb;
->> allows B-tree index with accurate cardinality estimates.
Find all records where JSON department field equals sales
SELECT * FROM employees WHERE info->>'department' = 'sales';
SELECT * FROM employees WHERE info @> '{"department":"sales"}'::jsonb;
Text extraction operator enables efficient index usage.
Find all records where JSON color field equals red
SELECT * FROM inventory WHERE specs->>'color' = 'red';
SELECT * FROM inventory WHERE specs @> '{"color":"red"}'::jsonb;
->> allows B-tree index and better query planning.
Find all records where JSON region field equals west
SELECT * FROM stores WHERE details->>'region' = 'west';
SELECT * FROM stores WHERE details @> '{"region":"west"}'::jsonb;
Text extraction provides better statistics for optimizer.
Aggregate values into arrays grouped by key with sorting
SET enable_presorted_aggregate = off; SELECT a, ARRAY_AGG(c ORDER BY c) FROM t GROUP BY a;
SELECT a, ARRAY_AGG(c ORDER BY c) FROM t GROUP BY a;
Disabling presorted aggregate prevents extra incremental sort.
Concatenate strings grouped by department with ordering
SET enable_presorted_aggregate = off; SELECT dept_id, STRING_AGG(employee_name ORDER BY employee_name) FROM employees GROUP BY dept_id;
SELECT dept_id, STRING_AGG(employee_name ORDER BY employee_name) FROM employees GROUP BY dept_id;
Prevents planner from using existing index requiring incremental sort.
Aggregate scores by student with ordering
SET enable_presorted_aggregate = off; SELECT student_id, ARRAY_AGG(score ORDER BY score DESC) FROM test_scores GROUP BY student_id;
SELECT student_id, ARRAY_AGG(score ORDER BY score DESC) FROM test_scores GROUP BY student_id;
Avoiding presorted path prevents expensive incremental sort step.
Group products by category with name aggregation
SET enable_presorted_aggregate = off; SELECT category_id, ARRAY_AGG(product_name ORDER BY product_name) FROM products GROUP BY category_id;
SELECT category_id, ARRAY_AGG(product_name ORDER BY product_name) FROM products GROUP BY category_id;
Disabling presorted aggregate avoids suboptimal sort strategy.
Aggregate amounts by account with ordering
SET enable_presorted_aggregate = off; SELECT account_id, ARRAY_AGG(amount ORDER BY amount) FROM transactions GROUP BY account_id;
SELECT account_id, ARRAY_AGG(amount ORDER BY amount) FROM transactions GROUP BY account_id;
Prevents using existing index that would require additional sort.
Group orders by customer with date aggregation
SET enable_presorted_aggregate = off; SELECT customer_id, ARRAY_AGG(order_date ORDER BY order_date) FROM orders GROUP BY customer_id;
SELECT customer_id, ARRAY_AGG(order_date ORDER BY order_date) FROM orders GROUP BY customer_id;
Avoiding presorted path is more efficient than incremental sort.
Aggregate events by user with timestamp ordering
SET enable_presorted_aggregate = off; SELECT user_id, ARRAY_AGG(event_timestamp ORDER BY event_timestamp) FROM events GROUP BY user_id;
SELECT user_id, ARRAY_AGG(event_timestamp ORDER BY event_timestamp) FROM events GROUP BY user_id;
Disabling presorted aggregate prevents expensive sort operation.
Group tasks by project with priority aggregation
SET enable_presorted_aggregate = off; SELECT project_id, ARRAY_AGG(priority ORDER BY priority DESC) FROM tasks GROUP BY project_id;
SELECT project_id, ARRAY_AGG(priority ORDER BY priority DESC) FROM tasks GROUP BY project_id;
Prevents planner from choosing presorted path with incremental sort.
Aggregate readings by sensor with timestamp ordering
SET enable_presorted_aggregate = off; SELECT sensor_id, ARRAY_AGG(reading_value ORDER BY reading_timestamp) FROM sensor_readings GROUP BY sensor_id;
SELECT sensor_id, ARRAY_AGG(reading_value ORDER BY reading_timestamp) FROM sensor_readings GROUP BY sensor_id;
Avoiding presorted aggregate is faster than extra sort step.
Group sales by region with amount aggregation
SET enable_presorted_aggregate = off; SELECT region_id, ARRAY_AGG(sale_amount ORDER BY sale_amount DESC) FROM sales GROUP BY region_id;
SELECT region_id, ARRAY_AGG(sale_amount ORDER BY sale_amount DESC) FROM sales GROUP BY region_id;
Disabling presorted path avoids incremental sort overhead.
Aggregate comments by post with timestamp ordering
SET enable_presorted_aggregate = off; SELECT post_id, ARRAY_AGG(comment_text ORDER BY created_at) FROM comments GROUP BY post_id;
SELECT post_id, ARRAY_AGG(comment_text ORDER BY created_at) FROM comments GROUP BY post_id;
Prevents using existing index requiring additional sort.
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
3