Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
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 feedbackCoaching1:1 coaching with people at your target companiesSuccess 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
Optimizing Slow SQL at Scale
00:00
5 left

Optimizing Slow SQL at Scale

MediumSQL · PostgreSQL

Problem

How do you optimize slow-running SQL queries in a relational database containing millions of patient records?

Using the provided PostgreSQL tables, write a query that returns active patients whose latest appointment was on or after 2025-01-01, along with their active prescription count. Consider how the query would perform at scale.

Output

  1. One row per qualifying active patient with patient_id, full_name, latest_appointment_date, and active_prescription_count.
  2. Include only active patients with a qualifying appointment, ordered by appointment date descending, then patient_id ascending.

Schema

patients
ColumnTypeDescription
patient_idPKINTUnique patient identifier
full_nameVARCHAR(120)Patient's full name
statusVARCHAR(20)Patient status
appointments
ColumnTypeDescription
appointment_idPKINTUnique appointment identifier
patient_idINTReferenced patient
appointment_dateDATEDate of the appointment
statusVARCHAR(20)Appointment status
prescriptions
ColumnTypeDescription
prescription_idPKINTUnique prescription identifier
patient_idINTReferenced patient
medication_nameVARCHAR(100)Prescribed medication
statusVARCHAR(20)Prescription status
Tablespatientsappointmentsprescriptions
Interviewer

Your question is Optimizing Slow SQL at Scale. 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.