For each patient's visits (ordered by date), calculate the number of days since their previous visit. Use a CTE to compute the LAG window function, then filter out first visits in the outer query. Return the patient's full name as patient_name, visit_date, previous_visit_date, and days_since_last. Sort by days_since_last descending to highlight the largest gaps.
Schema
🔑idINT
first_nameTEXT
last_nameTEXT
date_of_birthTEXT
genderTEXT
emailTEXT
phoneTEXTNULL
blood_typeTEXT
cityTEXT
stateTEXT
🔗insurance_idINTNULL
created_atTIMESTAMP
postgresql
Run your query to see results
Press Ctrl + Enter to execute