[Solved] Using TSQL to find variance in minutes between two dates where seconds portion is greater than zero
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Using TSQL to find variance in minutes between two dates where seconds portion is greater than zero

Need some help to verify this is the correct way of obtaining the result. I need to find the variance in minutes between two dates where the seconds portion of the date > 0.

List for the past minute, Variance = (Event_BeginTime - Event_CreateDate) where the seconds portion of HH:MM:SS > 0

    SELECT Event_BeginTime
        ,Event_CreateDate
        ,DATEDIFF(MINUTE,Event_BeginTime,Event_CreateDate) AS 'Variance'
    FROM Events WITH (NOLOCK)
    WHERE RIGHT(CAST(Event_BeginTime AS TIME(0)), 2) > 0 AND Event_CreateDate >= DATEADD(MINUTE, -1, GETDATE())
    ORDER BY Event_CreateDate DESC

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Calling Functions With Indexed Columns (query line: 11): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `Event_BeginTime` is indexed, the index won’t be used as it’s wrapped with the function `RIGHT`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `Events` ADD INDEX `events_idx_event_createdate` (`Event_CreateDate`);
The optimized query:
SELECT
        Events.Event_BeginTime,
        Events.Event_CreateDate,
        DATEDIFF(MINUTE,
        Events.Event_BeginTime,
        Events.Event_CreateDate) AS 'Variance' 
    FROM
        Events WITH (NOLOCK) 
    WHERE
        
    RIGHT(CAST(Events.Event_BeginTime AS TIME (0)), 2) > 0 
    AND Events.Event_CreateDate >= DATEADD(MINUTE, -1, GETDATE()) ORDER BY
        Events.Event_CreateDate DESC

Related Articles



* original question posted on StackOverflow here.