T-SQL – Find Transactions in Time Range Ignoring Date

t-sql

My client wants to know all the people that logged in to the system during the night hours. I keep all login times. Basically looking for anyone who logged in from 1am-5am for all of this year. Is there a way to find this using SQL?

I keep my time in basic DateTime Format with a 24 hour clock.

Best Answer

I think you will be fine using DATEPART.

Assume the following columns exist, and assume dates and times don't test for daylight saving time.

This will select all the UserIDs from a table where the time is between 1am and 5pm, since January 1st.

SELECT
    UserID,
    LoginDate
FROM
    [dbo].[LoginDates]
WHERE
    [LoginDate] > '20160101'
    AND DATEPART(HOUR,[LoginDate]) >= 1
    AND DATEPART(HOUR,[LoginDate]) < 5

Notes:

  • The LoginDate > '20160101' will check for all logins after midnight on the 1st of January 2016.

  • I'm using >= and < instead of BETWEEN, because it's more accurate.