2014-07-22 51 views
5

擁有的形式從PostgreSQL的時間戳中提取日期的最有效方法是什麼?

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' 

在什麼條件下不同的查詢執行得更好/更糟糕的查詢?哪三種選擇最有效?

+3

你需要看執行計劃可以肯定的,但總的來講,在這樣一個功能包裝的表列你的第二個和第三個例子將防止任何索引使用,這會使你進行表掃描。 – Brandon

+3

第四種可能性(待測試)是'select * from foo where created_on'2014/1/1 00:00:00'和'2014/1/2 00:00:00'' – Brandon

+0

@Brandon:第一個表達式也會阻止索引的使用。 –

回答

2

總結評論,你的第一個和第三個解決方案是相同的。根據@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'; 
相關問題