how to get entries for a specific date?

George Botonakis 0 Reputation points
2023-01-31T09:50:27.7733333+00:00

Good morning all,

We have MSSMS and our tables we have TimeStamp columns which are set as datetime.

How can we select entries based on a specific date apart from using the below?

SELECT *

FROM table

WHERE TimeStamp < '2021-09-03 23:59:59.999' AND TimeStamp > '2021-09-03 00:00:00.000'

Is there a way we can shorten this?

Thank you in advance

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,676 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 40,736 Reputation points
    2023-01-31T10:29:22.6266667+00:00

    You can cast to "date" datatype to truncate the time portion, like

    SELECT *
    FROM table
    WHERE cast(TimeStamp as date) = '2021-09-03' 
    

    But that will prevent the usage of a may existing index.

    WHERE TimeStamp < '2021-09-03 23:59:59.999'

    That will return a wrong result. Datetime has a precise of 3 milliseconds and SQL Server "round" it up to 2021-09-04, see

    https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver16

    select cast( '2021-09-03 23:59:59.999' as datetime)
    
    

  2. Jingyang Li 5,891 Reputation points
    2023-01-31T15:59:50.44+00:00

    SELECT * FROM table

    WHERE TimeStamp >= '2021-09-03' AND TimeStamp < '2021-09-04'

    0 comments No comments

  3. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-02-01T01:52:38.2366667+00:00

    Hi @George Botonakis

    In addition to the above two methods, you can also try this one.

    select * from table where Convert(char(10),TimeStamp,120) = '2021-09-03';
    

    I've done the test.

    create table table(TimeStamp datetime);
    insert into table values
    ('2021-09-03 23:59:59'),
    ('2021-09-03 00:00:00'),
    ('2021-09-03 00:01:00'),
    ('2021-09-02 23:59:59'),
    ('2021-09-04 00:00:00'),
    ('2021-09-04 02:00:00'),
    ('2021-09-02 21:45:59');
    

    It will get data in yyyy-mm-dd format.

    User's image

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments