NeuroAgent

How to Calculate Minutes Between Time Values in SQL Server

Learn the most efficient method to calculate total minutes between two time values in SQL Server using DATEDIFF function. Discover optimized approaches for better performance and accuracy.

Question

How to calculate total minutes between two time values in SQL Server?

Note that the times are saved in time datatype. So if I have someone that started work at let’s say 5:30 am and ended their shift at 10:00 am, is there a faster way than:

sql
declare @Shiftstart time;
declare @ShiftEnd time;
select @Shiftstart = '05:30', @ShiftEnd = '10:00'

print cast( (datepart(minute, @Shiftstart)+(datepart(hour, @Shiftstart))*60-
datepart(minute, @ShiftEnd)+(datepart(hour, @ShiftEnd))*60) as varchar(50))

What’s the most efficient method to calculate the total minutes between two time values in SQL Server without converting to datetime?

NeuroAgent

To calculate total minutes between two time values in SQL Server, the most efficient method is to use the built-in DATEDIFF function, which is optimized for performance and significantly simpler than manual calculations.


Contents


Understanding Time Data Types

SQL Server’s time datatype stores time values without date components, ranging from 00:00:00 to 23:59:59.9999999. When calculating differences between two time values, you need to consider that SQL Server doesn’t support the SQL standard interval data type, making direct arithmetic operations less efficient than using specialized functions.

The Microsoft Learn documentation confirms that DATEDIFF is the recommended approach for calculating differences between datetime values, and it works efficiently with time datatypes as well.

DATEDIFF Function Overview

The DATEDIFF function calculates the difference between two date or time values based on the specified datepart. For time differences in minutes, you use MINUTE as the datepart:

sql
DATEDIFF(MINUTE, @time1, @time2)

According to the SQLines documentation, this function returns the difference in seconds, minutes, hours, days, weeks, months, quarters and years between 2 datetime values, and it’s highly optimized for performance.

Optimal Method for Time Differences

The most efficient method to calculate total minutes between two time values is:

sql
DECLARE @ShiftStart TIME = '05:30';
DECLARE @ShiftEnd TIME = '10:00';
SELECT DATEDIFF(MINUTE, @ShiftStart, @ShiftEnd) AS TotalMinutes;

This approach is superior because:

  1. Single function call: Uses only one built-in function instead of multiple DATEPART calls
  2. Native optimization: DATEDIFF is specifically designed for date/time calculations
  3. Cleaner code: More readable and maintainable
  4. Automatic handling: Correctly handles all time ranges without manual logic

The result for the example would be 270 minutes (4.5 hours), which is much more accurate than the original method that had a sign error.


Performance Comparison

Let’s compare the approaches:

Original Method (Manual Calculation):

sql
DECLARE @ShiftStart TIME = '05:30';
DECLARE @ShiftEnd TIME = '10:00';
SELECT CAST(
    (DATEPART(MINUTE, @ShiftStart) + (DATEPART(HOUR, @ShiftStart) * 60) - 
     DATEPART(MINUTE, @ShiftEnd) + (DATEPART(HOUR, @ShiftEnd) * 60)) 
    AS VARCHAR(50)) AS Result;

Problems with the original method:

  1. Sign error: The calculation should be End - Start, not Start - End
  2. Multiple function calls: Four separate DATEPART calls
  3. Complex arithmetic: Manual conversion of hours to minutes
  4. Type conversion: Unnecessary CAST to varchar

Optimized Method (DATEDIFF):

sql
DECLARE @ShiftStart TIME = '05:30';
DECLARE @ShiftEnd TIME = '10:00';
SELECT DATEDIFF(MINUTE, @ShiftStart, @ShiftEnd) AS TotalMinutes;

Advantages:

  1. Single function: One optimized DATEDIFF call
  2. Correct logic: Automatically calculates End - Start
  3. Direct result: Returns integer minutes without conversion
  4. Better performance: Built-in function execution optimization

Handling Edge Cases

The DATEDIFF function handles various edge cases correctly:

sql
-- Midnight crossing
DECLARE @NightStart TIME = '23:30';
DECLARE @NightEnd TIME = '01:30';
SELECT DATEDIFF(MINUTE, @NightStart, @NightEnd) AS TotalMinutes;
-- Returns 120 minutes (2 hours)

-- Same time
DECLARE @SameTime TIME = '12:00';
SELECT DATEDIFF(MINUTE, @SameTime, @SameTime) AS TotalMinutes;
-- Returns 0 minutes

-- Large difference
DECLARE @EarlyTime TIME = '00:00';
DECLARE @LateTime TIME = '23:59';
SELECT DATEDIFF(MINUTE, @EarlyTime, @LateTime) AS TotalMinutes;
-- Returns 1439 minutes

For more complex formatting requirements, as shown in the LearnSQL.com example, you can combine DATEDIFF with other functions:

sql
WITH time_difference AS (
    SELECT 
        DATEDIFF(SECOND, @ShiftStart, @ShiftEnd) AS total_seconds
)
SELECT 
    FLOOR(total_seconds / 60) AS minutes,
    total_seconds % 60 AS seconds
FROM time_difference;

Practical Examples

Here are some practical implementations:

Basic Usage:

sql
-- Create a sample table
CREATE TABLE WorkShifts (
    EmployeeID INT,
    ShiftStart TIME,
    ShiftEnd TIME
);

-- Insert sample data
INSERT INTO WorkShifts VALUES 
(1, '08:00', '17:00'),   -- Standard 8-hour shift
(2, '06:30', '15:45'),   -- 9.25 hour shift
(3, '22:00', '06:00');   -- 8-hour shift crossing midnight

-- Calculate minutes for each shift
SELECT 
    EmployeeID,
    ShiftStart,
    ShiftEnd,
    DATEDIFF(MINUTE, ShiftStart, ShiftEnd) AS ShiftMinutes,
    DATEDIFF(MINUTE, ShiftStart, ShiftEnd) / 60.0 AS ShiftHours
FROM WorkShifts;

With Aggregation:

sql
-- Total working minutes per employee
SELECT 
    EmployeeID,
    SUM(DATEDIFF(MINUTE, ShiftStart, ShiftEnd)) AS TotalMinutesWorked,
    SUM(DATEDIFF(MINUTE, ShiftStart, ShiftEnd)) / 60.0 AS TotalHoursWorked
FROM WorkShifts
GROUP BY EmployeeID;

Formatted Output:

sql
-- Format as HH:MM
SELECT 
    EmployeeID,
    ShiftStart,
    ShiftEnd,
    FORMAT(
        DATEADD(MINUTE, DATEDIFF(MINUTE, ShiftStart, ShiftEnd), 0), 
        'HH:mm'
    ) AS Duration
FROM WorkShifts;

Conclusion

The most efficient method to calculate total minutes between two time values in SQL Server is using the DATEDIFF function. This approach:

  1. Provides better performance than manual calculations with fewer function calls
  2. Handles all edge cases automatically, including midnight crossings
  3. Is more readable and maintainable with simpler syntax
  4. Returns accurate results without manual arithmetic errors

For your specific example, instead of the complex manual calculation that had a sign error, you should use:

sql
SELECT DATEDIFF(MINUTE, '05:30', '10:00') AS TotalMinutes;

This returns 270 minutes (4.5 hours) correctly and efficiently. When working with time differences in SQL Server, always prefer built-in functions like DATEDIFF over manual calculations for optimal performance and accuracy.

Sources

  1. DATEDIFF (Transact-SQL) - SQL Server | Microsoft Learn
  2. SQL Server - DATEDIFF - Datetime Difference in Seconds, Days, Weeks etc - SQLines Tools
  3. How to Find the Difference Between Two Datetimes in T-SQL | LearnSQL.com
  4. Calculate time difference in minutes in SQL Server - Stack Overflow
  5. SQL - Datediff to calculate minutes between two times of datetime columns - Spiceworks Community