10

I have a postgres table that has the following fields

start_date,duration

duration contains any number of months, so to calculate the end date you add the months in duration to the start date. Now I want to do something like this with a postgres query.

SELECT * 
FROM table 
WHERE start_date > '2010-05-12' 
AND (start_date + duration) < '2010-05-12'

Is this possible and how does one right the syntax?

The version of my postgres is PostgreSQL 8.1.22 on x86_64-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-48)

3
  • 1
    8.1 ? You should really upgrade ! If "duration" is of type INTERVAL then it will work, if it's an integer number of months you have to do "duration * '1 MONTH'::INTERVAL". Commented May 6, 2011 at 9:40
  • @pefeu: you should make that an answer. Commented May 6, 2011 at 9:57
  • @peufeu - 8.1 is the default version on RHEL5. It is stable and will be supported by Red Hat until at least 2014. In some cases that matters a lot more than having the latest version. Commented May 7, 2011 at 18:34

2 Answers 2

19

try:

(start_date + (duration * '1 month'::INTERVAL)) < '2010-05-12'

or

(start_date + (duration || ' month')::INTERVAL) < '2010-05-12'

More info: Date/Time Functions and Operators

Sign up to request clarification or add additional context in comments.

1 Comment

= Getting Syntax ERROR: syntax error at or near "duration" at character 220
1

You might find this article useful: PostgreSQL: month := interval '30 days';

Also this link: http://wiki.postgresql.org/wiki/Working_with_Dates_and_Times_in_PostgreSQL, more specifically the section called "WORKING with DATETIME, DATE, and INTERVAL VALUES".

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.