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

Optimize a Slow SQL Query

HardSQL · PostgreSQL

Problem

How would you optimize a slow-running SQL query?

Given the supplied PostgreSQL schema and data, rewrite the query so it returns the same business result while reducing unnecessary scans and aggregation work. The result should include active loans with payments during the specified date range and more than 1,000 in total payments.

Output

  1. One row per qualifying active loan
  2. Columns: loan_id, borrower_name, and total_paid
  3. Include payments from 2025-01-01 through 2025-02-28
  4. Sort by total_paid descending, then loan_id ascending

Schema

borrowers
ColumnTypeDescription
borrower_idPKINTUnique borrower identifier
borrower_nameVARCHAR(100)Borrower display name
loans
ColumnTypeDescription
loan_idPKINTUnique loan identifier
borrower_idINTBorrower associated with the loan
statusVARCHAR(20)Current loan status
original_principalDECIMAL(12,2)Original principal balance
loan_payments
ColumnTypeDescription
payment_idPKINTUnique payment identifier
loan_idINTLoan associated with the payment
payment_dateDATEDate the payment was recorded
amountDECIMAL(12,2)Payment amount
Tablesloan_paymentsloansborrowers
Interviewer

Your question is Optimize a Slow SQL 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.