DB Quacks SQL Tutorial · Chapter 5

Back to the Future: LAG and LEAD

Time-traveling scientist Dr. Temporal appears with a glowing device. Great Scott! I need temporal analysis - compare each pond visit with previous and next visit dates to understand behavioral trends!

Your task

Show each pond visit with the previous and next visit dates for comparison using the 'data/pond_visits.csv' file. You will be using window functions to access adjacent rows.

Hint

Look for window functions that can access data from the previous or next row in your result set.

Expected result

A table showing each visit with duck names and previous/next visit dates.

Tables

duck_diaries (10 rows)

columntype
diary_idBIGINT
duck_idBIGINT
entry_dateDATE
diary_textVARCHAR
moodVARCHAR

duck_surveys (5000 rows)

columntype
survey_idBIGINT
duck_idBIGINT
ageBIGINT
favorite_foodVARCHAR
favorite_pondBIGINT
swimming_ratingBIGINT
migration_preferenceVARCHAR
social_behaviorVARCHAR
health_statusVARCHAR
activity_levelVARCHAR
survey_dateDATE
survey_locationBIGINT

ducks (15 rows)

columntype
idBIGINT
nameVARCHAR
ageBIGINT
speciesVARCHAR
birth_dateDATE
arrival_dateDATE

ponds (3 rows)

columntype
pond_idBIGINT
pond_nameVARCHAR
location_latDOUBLE
location_lngDOUBLE
capacityBIGINT
featuresVARCHAR[]
amenitiesVARCHAR[]

Files

data/pond_visits.csv (40 rows)

columntype
visit_idBIGINT
duck_idBIGINT
pond_idBIGINT
visit_dateDATE
duration_minutesBIGINT

Database: https://dbquacks.com/data/databases/tutorial.duckdb

This page as markdown: https://dbquacks.com/tutorial/25.md

Start level 25 →

DuckDB docs for this lesson