Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Debug and Optimize SQL
00:00
5 left

Debug and Optimize SQL

HardSQL · PostgreSQL

Problem

Walk through your approach to debugging and optimizing a sluggish SQL query handling millions of records.

Use the provided PostgreSQL schema to write an efficient equivalent query that reports paid invoice revenue for January and February 2025. Explain how you would inspect the execution plan, identify bottlenecks, and choose indexes.

Output

  1. One row per billing month and customer segment.
  2. Columns: billing_month, segment, invoice_count, and total_revenue.
  3. Include only paid invoices in the specified date range, include zero-value invoices with line items, sort by month and segment, and place a null segment last.

Schema

customers
ColumnTypeDescription
customer_idPKINTUnique customer identifier
segmentVARCHAR(40)Customer market segment
invoices
ColumnTypeDescription
invoice_idPKINTUnique invoice identifier
customer_idINTCustomer associated with the invoice
statusVARCHAR(20)Invoice status
issued_atTIMESTAMPInvoice creation timestamp
invoice_lines
ColumnTypeDescription
invoice_line_idPKINTUnique invoice line identifier
invoice_idINTInvoice containing the line item
descriptionVARCHAR(100)Line item description
quantityINTQuantity billed
unit_priceDECIMAL(12,2)Price per unit
Tablescustomersinvoicesinvoice_lines
Interviewer

Your question is Debug and Optimize SQL. 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.