Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
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
Sign up free to run your codeLog inLn 1
Run your query to see results here.