【问题标题】:What is the most efficient way to extract a date from a timestamp in PostgreSQL?从 PostgreSQL 中的时间戳中提取日期的最有效方法是什么?
【发布时间】:2014-07-22 15:36:48
【问题描述】:

查询表格

select * from foo
where created_on::date = '2014/1/1'

select * from foo
where date_trunc('day', created_on) = '2014/1/1'

select * from foo
where date(created_on) = '2014/1/1'

在什么条件下不同的查询会更好/更差?这三个选项中哪个最有效?

【问题讨论】:

  • 您需要查看执行计划以确定,但一般来说,将表列包装在像您的第二个和第三个示例这样的函数中会阻止任何索引使用,这会使您陷入表扫描。
  • 第四种可能性(待测试)是select * from foo where created_on between '2014/1/1 00:00:00' and '2014/1/2 00:00:00'
  • @Brandon:第一个表达式也会阻止索引的使用。
  • 好点,它正在铸造。
  • 第四个怎么样?因为很明显,如果我们在过滤日期的同时寻找性能,我们可能会使用索引。

标签: sql database performance postgresql


【解决方案1】:

总结 cmets,您的第一个和第三个解决方案是相同的。根据@Nick Barnes,投射到日期只需使用date 函数。

这些选项,加上选项 2,需要针对表的每一行运行一个函数,因此即使您有索引,也无法使用它。

假设created_on 上有一个索引,这是你最好的选择:

select * from foo
where created_on >= '2014/1/1 00:00:00'
  and created_on < '2014/1/2 00:00:00';

【讨论】:

  • 如果我根据月份对数据进行了分区,我相信它不会扫描所有分区吧?
猜你喜欢
  • 2017-08-10
  • 2017-03-06
  • 2011-09-02
  • 2011-11-11
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多