Select a date range from a timestamp column

邮差的信 提交于 2019-12-05 12:29:18
Erwin Brandstetter

If you are going to cast the timestamp values of the field to date, as suggested in another answer, performance will degrade because every single value in the column needs to be cast for comparison and simple indexes cannot be used. You would have to create a special index on the expression, like so:

CREATE INDEX some_idx ON tbl (cast(mdate AS date));

In this case the query should also be simplified to:

SELECT * FROM tbl WHERE mdate::date = '2011-09-12'::date; -- 2nd cast optional

However, as far as I can see, your problem is a simple typo / thinko in your query:
You switched upper & lower boundaries. Try:

SELECT * FROM tbl WHERE mdate >= '2011-09-12 00:00:00.0'
                  AND   mdate <= '2011-09-13 00:00:00.0';

Or, to simplify your syntax and be more precise:

SELECT * FROM tbl WHERE mdate >= '2011-09-12 00:00'
                  AND   mdate <  '2011-09-13 00:00';
  • There is no need to spell out seconds and fractions that are 0.
  • You don't want to include 2011-09-13 00:00, so use < instead of <=.
    Don't use BETWEEN here, for the same reason:

    WHERE mdate BETWEEN '2011-09-12 00:00' AND '2011-09-13 00:00'

    This would include 00:00 of the next day.

Also be aware that a column of type timestamp [without time zone] is interpreted according to your current time zone setting. The date part depends on that setting, which should generally work as expected. More details:
Ignoring timezones altogether in Rails and PostgreSQL

Just treat the timestamp as a date:

select * 
from table 
where mdate::date >= DATE '2011-09-12' 
  and mdate::date <= DATE '2011-09-13'

The expression mdate::date will cast the timestamp to a date type which will remove the time part from the value.

DATE '2011-09-13' is a (standard) DATE literal which is a bit more robust than simply writing '2011-09-13' as it isn't affected by any language settings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!