Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Optimize Slow Partitioned Query
00:00
5 left

Optimize Slow Partitioned Query

HardSQL · PostgreSQL

Problem

How would you optimize a slow-running query that scans millions of rows across multiple partitioned tables?

Provide a PostgreSQL query that returns the required aggregates for the supplied date range. Keep the result logically correct while demonstrating choices appropriate for large partitioned datasets.

Output

  1. One row per calendar month and region for active enterprise customers with completed, positive-value sales from January 1 through March 31, 2025.
  2. Columns: month_start, region_name, total_revenue, order_count, and distinct_customers.
  3. Sort by month_start ascending, then region_name ascending.

Schema

sales_events
ColumnTypeDescription
event_idPKINTUnique sales event identifier
order_idVARCHAR(20)Business order identifier
customer_idINTCustomer associated with the event
event_dateDATEPartition key and sales date
amountNUMERIC(12,2)Value of the sales event
statusVARCHAR(20)Sales event status
customers
ColumnTypeDescription
customer_idPKINTUnique customer identifier
customer_nameVARCHAR(100)Customer display name
segmentVARCHAR(30)Customer market segment
region_idINTCustomer region
is_activeBOOLEANWhether the customer is currently active
regions
ColumnTypeDescription
region_idPKINTUnique region identifier
region_nameVARCHAR(60)Region display name
country_codeVARCHAR(3)Country or territory code
Tablessales_eventscustomersregions
Interviewer

Your question is Optimize Slow Partitioned Query. Start with the requirements and the three tables in the Question tab.

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.
CodePostgreSQL
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.