Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimize Slow Multi-Join Query

HardSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimize Slow Multi-Join Query. Start with the requirements and the four tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

How would you optimize a slow-running SQL query that involves multiple joins and aggregations on tables containing millions of rows?

Using the supplied schema, write the query that returns filtered completed-order totals by region, month, and product category. Explain the performance decisions and how you would validate them with PostgreSQL execution plans.

Output

  1. One row per region, calendar month, and product category.
  2. Columns: region, order_month, category, order_count, units_sold, and gross_revenue.
  3. Include completed orders from 2024-01-01 through 2024-03-31, sort by order_month, region, and category.

Schema

accounts
ColumnTypeDescription
account_idPKINTAccount identifier
regionVARCHAR(40)Account region
orders
ColumnTypeDescription
order_idPKINTOrder identifier
account_idINTAccount that placed the order
order_dateDATEOrder date
statusVARCHAR(20)Order processing status
order_items
ColumnTypeDescription
order_item_idPKINTOrder line identifier
order_idINTParent order identifier
product_idINTReferenced product identifier
quantityINTUnits on the order line
unit_priceDECIMAL(12,2)Price per unit
products
ColumnTypeDescription
product_idPKINTProduct identifier
categoryVARCHAR(40)Product category
Tablesaccountsordersorder_itemsproducts
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results