26

I am using PostreSQl server and have to get data grouped by date part of timestamp (ie. group by month or year or week) so I am using the Extract(year from timestamp) function but I saw in the Postgresql documentation that there is a function date_part('year',timestamp) too which can do the same. Here I confused which function I have to use and which function will be efficient. Also please tell me if there is another good way to get data groped by date part.

2
  • Can you include the query you are using? Jul 18, 2016 at 17:09
  • Hi Tim, I am using the query is : select EXTRACT(MONTH FROM date(ticket.transactiondate)),(round(cast(sum(ticketitem.netprice)as NUMERIC(36,2)), 2)) as grandTotal,count(ticketitem.id) as noOfItem,count(distinct ticket.id)as kpi from ticket INNER JOIN ticketitem on ticket.id=ticketitem.ticketid where (EXTRACT(MONTH FROM date(ticket.transactiondate))='7' or EXTRACT(MONTH FROM date(ticket.transactiondate))='6') and EXTRACT(YEAR FROM date(ticket.transactiondate))='2015' group by 1 order by 1 asc Thank you!! Jul 21, 2016 at 7:25

2 Answers 2

36

They are both the same.

In fact extract() gets re-written to date_part() - check the execution plan and you will see.

extract() complies with the SQL standard, date_part() is a Postgres specific query. As one gets converted to the other, there is absolutely no performance difference. If you prefer to write standard SQL, stick to extract()

Update 2021-12-16

Starting with Postgres 14 this is no longer the case, the implementation is now different:

The release notes state:

Change EXTRACT() to return type numeric instead of float8 (Peter Eisentraut).

This avoids loss-of-precision issues in some usages. The old behavior can still be obtained by using the old underlying function date_part().

4
  • Do you mean date_part? May 14, 2019 at 14:12
  • @EugenKonkov: yes, indeed. Thanks
    – user330315
    May 14, 2019 at 15:46
  • 2
    In fact extract() gets re-written to date_part() - Not any more! Compare 9.6 (up to 13.4), but 14.1! Not sure why this is the case... Googled - got nothing!
    – Vérace
    Dec 16, 2021 at 8:59
  • @Vérace-getVACCINATEDNOW: there is an entry in the release notes. I have updated my answer.
    – user330315
    Dec 16, 2021 at 9:08
8

I quote the answer from Postgresql.org

Blockquote The EXTRACT syntax ends up as a call to the internal date_part(...) function. If SQL-portability is not a concern, calling date_part() directly should be a bit quicker.

Reference Link

1
  • Not any more - see my comment here.
    – Vérace
    Dec 16, 2021 at 9:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.