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)
| column | type |
|---|---|
diary_id | BIGINT |
duck_id | BIGINT |
entry_date | DATE |
diary_text | VARCHAR |
mood | VARCHAR |
duck_surveys (5000 rows)
| column | type |
|---|---|
survey_id | BIGINT |
duck_id | BIGINT |
age | BIGINT |
favorite_food | VARCHAR |
favorite_pond | BIGINT |
swimming_rating | BIGINT |
migration_preference | VARCHAR |
social_behavior | VARCHAR |
health_status | VARCHAR |
activity_level | VARCHAR |
survey_date | DATE |
survey_location | BIGINT |
ducks (15 rows)
| column | type |
|---|---|
id | BIGINT |
name | VARCHAR |
age | BIGINT |
species | VARCHAR |
birth_date | DATE |
arrival_date | DATE |
ponds (3 rows)
| column | type |
|---|---|
pond_id | BIGINT |
pond_name | VARCHAR |
location_lat | DOUBLE |
location_lng | DOUBLE |
capacity | BIGINT |
features | VARCHAR[] |
amenities | VARCHAR[] |
Files
data/pond_visits.csv (40 rows)
| column | type |
|---|---|
visit_id | BIGINT |
duck_id | BIGINT |
pond_id | BIGINT |
visit_date | DATE |
duration_minutes | BIGINT |
Database: https://dbquacks.com/data/databases/tutorial.duckdb
This page as markdown: https://dbquacks.com/tutorial/25.md
All levels
- 1. SHOW TABLES in DuckDB
- 2. DESCRIBE a Table in SQL
- 3. SQL SELECT *
- 4. SQL WHERE Clause
- 5. SQL ORDER BY
- 6. SQL LIMIT
- 7. SQL Calculated Columns
- 8. SQL SELECT DISTINCT
- 9. DuckDB USING SAMPLE
- 10. SQL Aggregate Functions
- 11. SQL Date Intervals
- 12. SQL GROUP BY
- 13. SQL HAVING
- 14. Read a CSV File in DuckDB
- 15. Read a JSON File in DuckDB
- 16. Read a Parquet File in DuckDB
- 17. SQL INNER JOIN
- 18. SQL JOIN with WHERE
- 19. SQL CASE WHEN
- 20. SQL LEFT JOIN
- 21. Join CSV and JSON Files in SQL
- 22. GROUP BY, HAVING and ORDER BY
- 23. SQL UNION
- 24. SQL ROW_NUMBER
- 25. SQL LAG and LEAD
- 26. SQL Running Total with SUM OVER
- 27. SQL CTE (WITH Clause)
- 28. Recursive CTE in SQL
- 29. SQL Subquery
- 30. DuckDB SELECT * EXCLUDE
- 31. SQL PIVOT
- 32. SQL UNPIVOT
- 33. SQL ROLLUP
- 34. DuckDB JSON Functions
- 35. Query Remote Files with DuckDB httpfs
- 36. DuckDB Spatial
- 37. DuckDB Full-Text Search
- 38. DuckDB ASOF JOIN
More: every SQL tutorial lesson · practice SQL exercises online