Datetime vs Date and Time Mysql

后端 未结 4 643
自闭症患者
自闭症患者 2020-12-31 00:19

I generally use datetime field to store created_time updated time of data within an application.

But now i have come across a database table where they have kept dat

4条回答
  •  -上瘾入骨i
    2020-12-31 00:38

    One difference I found is using BETWEEN for dates with non-zero time.

    Imagine a search with "between dates" filter. Standard user's expectation is it will return records from the end day as well, so using DATETIME you have to always add an extra day for the BETWEEN to work as expected, while using DATE you only pass what user entered, with no extra logic needed.

    So query

    SELECT * FROM mytable WHERE mydate BETWEEN '2020-06-24' AND '2020-06-25'
    

    will return a record for 2020-06-25 16:30:00, while query:

    SELECT * FROM mytable WHERE mydatetime BETWEEN '2020-06-24' AND '2020-06-25'
    

    won't - you'd have to add an extra day:

    SELECT * FROM mytable WHERE mydatetime BETWEEN '2020-06-24' AND '2020-06-26'
    

    But as victor diaz mentioned, doing datetime calculations with date+time would be a super inefficient nightmare and far worse, than just adding a day to the second datetime. Therefore I'd only use DATE if the time is irrelevant, or as a "cache" for speeding queries up for date lookups (see Elwin's answer).

提交回复
热议问题