How do you calculate the difference between two dates in SQL, for example between a higher date and a birth date?
💡 Model Answer
In SQL you can compute the difference between two dates using built‑in date functions that return the interval in a specific unit. The most common approach is to use the DATEDIFF function, which is available in many RDBMS such as SQL Server, MySQL, and PostgreSQL (via the age() function). For example, in SQL Server:
SELECT DATEDIFF(day, birth_date, current_date) AS age_in_days
FROM users;
This returns the number of days between the birth_date and the current_date. If you need the result in months or years, replace "day" with "month" or "year".
In MySQL you can use the same DATEDIFF syntax:
SELECT DATEDIFF(CURDATE(), birth_date) AS age_in_days
FROM users;
PostgreSQL does not have a DATEDIFF function, but you can subtract dates directly, which yields an interval:
SELECT (current_date - birth_date) AS age_interval
FROM users;
You can then extract the number of days, months, or years from that interval using EXTRACT:
SELECT EXTRACT(year FROM current_date - birth_date) AS age_years
FROM users;
All these methods give you the difference between two dates. Choose the one that matches your database engine and the unit of measurement you need.
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