How do you calculate the difference between two dates in SQL? For example, if you want to calculate the difference between a hire date and a birth date, how would you do that?
💡 Model Answer
In SQL, the most common way to find the difference between two dates is to use a date difference function that is built into the database engine. In Microsoft SQL Server you use DATEDIFF, in MySQL you can use TIMESTAMPDIFF or DATEDIFF, and in PostgreSQL you can simply subtract the dates or use AGE. For example, in SQL Server: SELECT DATEDIFF(day, birth_date, hire_date) AS days_between; This returns the number of days between the two dates. If you need the difference in months or years, you can change the first argument to month or year. In MySQL, you could write: SELECT TIMESTAMPDIFF(DAY, birth_date, hire_date) AS days_between; In PostgreSQL: SELECT (hire_date - birth_date) AS days_between; The result is an interval or integer depending on the function. Always be mindful of the order of arguments; the first date is the start, the second is the end. If you need a negative value when the first date is later, you can swap the order or use ABS() to get an absolute difference.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500