Calculate Date Differences with DATEDIFF and TIMESTAMPDIFF in MySQL
📖 Scenario: You work in a small library that tracks when books are borrowed and returned. You want to find out how many days each book was borrowed and also calculate the difference in months between borrow dates and today.
🎯 Goal: Build SQL queries using DATEDIFF and TIMESTAMPDIFF functions to calculate the number of days between two dates and the number of months between a borrow date and the current date.
📋 What You'll Learn
Create a table called
borrow_records with columns book_id, borrow_date, and return_date.Insert three records with exact dates for borrow and return.
Write a query using
DATEDIFF to find the number of days each book was borrowed.Write a query using
TIMESTAMPDIFF to find the number of months between the borrow date and today.💡 Why This Matters
🌍 Real World
Libraries, rental services, and any system that tracks borrowing or usage periods need to calculate date differences to manage returns and analyze usage.
💼 Career
Database developers and analysts often write queries to calculate durations between dates for reporting, billing, or operational decisions.
Progress0 / 4 steps