Skip to content

Instantly share code, notes, and snippets.

@deterralba
Created August 24, 2017 13:18
Show Gist options
  • Save deterralba/2ad65b539160c2efcd7cf6e9de0f5cf9 to your computer and use it in GitHub Desktop.
Save deterralba/2ad65b539160c2efcd7cf6e9de0f5cf9 to your computer and use it in GitHub Desktop.
Error with extract and dates soustraction in postgres

Issue

Let's say you want to get an integer that is the number of months between two dates in psql (payment_date and creation_date are dates), and the following command:

select extract(month from (payment_date - creation_date) * interval '1 day') from invoice;

fails with:

ERROR:  function pg_catalog.date_part(unknown, integer) does not exist
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

Solution

You have to multiply by interval '1 day', because the difference of dates in an integer and not an interval:

select extract(month from (payment_date - creation_date) * interval '1 day') from invoice;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment