3

How to implement add_months in PostgreSQL ?? Like oracle ADD_MONTHS returns the date. Ex. ADD_MONTHS(hire_date,1)

2
  • 5
    hire_date + interval '1' month Commented Nov 27, 2015 at 8:41
  • ADD_MONTHS has a special logic when the first argument is the last day of a month. In PostgreSQL, '2025-02-28'::date + interval '1 month' returns 2025-03-28. While in Oracle add_months(to_date('2025-02-28','yyyy-mm-dd'), 1) returns 2025-03-31. So, the already answered question does not answer how to implement add_months logic properly in PostgreSQL. Commented Jul 5 at 15:18

3 Answers 3

12

use

 hire_date + interval '1 month'

this will return exactly one month added to hire_date.

For More References on date and time functions in postgre Date time function

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

1 Comment

This doesn't cover the case when hire_date is the last day of a month. add_months(to_date('2025-02-28','yyyy-mm-dd'), 1) returns 2025-03-31, while the month interval logic in PostgreSQL returns 2025-03-28.
6
CREATE FUNCTION add_months(start DATE, months INT) RETURNS DATE AS
$$
  SELECT (start + months * '1 month'::INTERVAL)::DATE
$$
LANGUAGE sql IMMUTABLE

Comments

1

In PostgreSQL you can create a function to do the job

create or replace function ADD_MONTHS(var_dte date,cnt int) returns setof date as
$$
declare
qry text;
begin
qry = format( 'select (''%s''::date + interval ''%s'')::date',var_dte,cnt||' month') ;
RETURN QUERY
     EXECUTE qry;
end
$$
language plpgsql

and call this function

select ADD_MONTHS('2015-11-27',1)

Result:

add_months
      date
----------
2015-12-27

in your case

select hire_date
      ,ADD_MONTHS(hire_date,1)
from table_name 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.