Complete the code to find the number of days between two dates.
SELECT DATEDIFF([1], '2024-01-01') AS days_difference;
The DATEDIFF function returns the number of days between two dates. Here, the first date should be later than the second to get a positive difference.
Complete the code to find the number of months between two dates using TIMESTAMPDIFF.
SELECT TIMESTAMPDIFF([1], '2023-01-01', '2024-01-01') AS months_difference;
TIMESTAMPDIFF calculates the difference between two dates in the specified unit. Here, MONTH returns the number of full months between the dates.
Fix the error in the code to correctly calculate the difference in hours between two timestamps.
SELECT TIMESTAMPDIFF([1], '2024-01-01 08:00:00', '2024-01-01 12:00:00') AS hours_difference;
The unit HOUR correctly calculates the difference in hours between two timestamps.
Fill both blanks to calculate the number of years and days between two dates.
SELECT TIMESTAMPDIFF([1], '2000-01-01', '2024-01-01') AS years_diff, DATEDIFF('2024-01-01', [2]) AS days_diff;
The first blank uses YEAR to get full years difference. The second blank uses the start date '2000-01-01' to calculate days difference from the end date.
Fill all three blanks to calculate the difference in days, months, and years between two dates.
SELECT DATEDIFF([1], [2]) AS days_diff, TIMESTAMPDIFF([3], [2], [1]) AS months_diff, TIMESTAMPDIFF(YEAR, [2], [1]) AS years_diff;
The first two blanks are dates: the later date first, then the earlier date. The third blank is the unit 'MONTH' for months difference.