sql-servert-sqldeclare

Selecting Records Modified on a Specific Date Using SMALLDATETIME Variables


encountered an SQL challenge in an interview and need some help. The task was to modify a given query to return all contacts modified at any time on January 1st, 2018, using two SMALLDATETIME variables, @StartDateInput and @EndDateInput.

DECLARE @StartDateInput SMALLDATETIME = '1/1/2018',
        @EndDateInput SMALLDATETIME = '1/1/2018';


Query to modify

SELECT *
FROM   dbo.Contacts;

I attempted to modify the query but couldn't figure out how to incorporate @EndDateInput correctly. My attempt was:

SELECT *
FROM dbo.Contacts
WHERE ModifiedDate = SMALLDATETIME;

However, this approach seems incorrect. I think the solution should involve both @StartDateInput and @EndDateInput to accurately capture contacts modified at any time on January 1st, 2018, but I'm unsure how to achieve this.

Could anyone suggest the correct way to modify this query to meet the specified criteria?


Solution

  • It looks like the question is probing your understanding of date and datetime types, namely that a date with a time is after a date without a time (if there is even such a thing; most timeless dates are considered to be midnight on the relevant date, which is a time too.. in the same way that 1.0 is the same thing as 1, and 1.1 is after 1.0)

    I'd use a range:

    SELECT *
    FROM   dbo.Contacts
    WHERE ModifiedDate >= @StartDateInput AND ModifiedDate < DATEADD(DAY, 1, @EndDateInput)
    

    Why?

    The only thing I would say is that strictly, the spec only calls for one day's records, which means it's not mandatory to use the @EndDateInput at all. It seems logical to use it, but it could be argued that if the spec is that this query will only ever return one day, the @End variable could be discarded and a DATEADD performed on the @Start instead