Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Time Between Visits

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Time Between Visits. Start with the requirements and the one table on the right.

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.

Problem

Tempus Lens uses longitudinal patient records to support clinical insights. Given a patient visit table, write a PostgreSQL query that measures the interval between each patient's first and second completed visits.

Requirements

  1. Consider only visits with visit_status = 'completed' and a non-null visit_started_at.
  2. Number each patient's valid visits chronologically, using visit_id to break timestamp ties.
  3. Return only patients with at least two valid completed visits, including the first visit timestamp, second visit timestamp, and elapsed interval.
  4. Sort the final results by patient_id.

Schema

patient_visits
ColumnTypeDescription
visit_idPKINTUnique identifier for the visit
patient_idINTIdentifier of the patient receiving care
visit_started_atTIMESTAMPTimestamp when the visit started
visit_statusVARCHAR(20)Status or outcome of the visit
Tablespatient_visits
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results