1

Function:

CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN
IF d1 = NULL THEN
RETURN SELECT extract(year from age(current_date,d2));
ELSE
RETURN SELECT extract(year from age(d1,d2));
END IF;
END
$$ language plpgsql;

My requirement is to find the difference between two dates in years. So, I write the above function. Here, if d1 is NULL then it is assigned with current date. But, it produce error like as shown below.

ERROR:  syntax error at or near "SELECT"
LINE 1: SELECT  SELECT extract(year from age(current_date, $1 ))
QUERY:  SELECT  SELECT extract(year from age(current_date, $1 ))
CONTEXT:  SQL statement in PL/PgSQL function "diff" near line 4 

Does any one help me to solve this problem.

3
  • 1
    did you try removing SELECT ? RETURN extract(year from age(d1,d2)); Commented Feb 3, 2016 at 5:16
  • Other than Jay's comment, another potential problem might be that AGE() is not returning a date type which extract() can handle. Commented Feb 3, 2016 at 5:18
  • @JayKumarR As per your suggestion, the function created successfully. But, it doesn't give the expected output. If d1 is null, it returns NULL as output. Commented Feb 3, 2016 at 5:31

1 Answer 1

1

Try :

date_part('year',age(coalesce(d1,current_date), d2))::int;

age(d1,d2) function returns the number of years, months, and days between two dates in following format:

xxx year(s) xxx mon(s) xxx day(s).

from this output using date_part() to pick the only the year difference. and also no need to put if statement to handle NULL as I have added coalesece which returns first NON Null value, So if d1 is NULL it return cuurent_date

Function Structure:

CREATE OR REPLACE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN

 RETURN date_part('year',age(coalesce(d1,current_date), d2))::int;
END
$$ language plpgsql;

Function Call:

select * from diff(null,'2010-04-01');
select * from diff('2012-10-01','2010-04-01');
Sign up to request clarification or add additional context in comments.

5 Comments

It shows error like 'ERROR: mismatched parentheses at or near ")" LINE 7: RETURN date_part('year',age(d1,current_date), d2))::int; ^
share the function you have created.
This is working for mine. Please check the updated answer.
CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$ BEGIN IF d1 = NULL THEN RETURN extract(year from age(current_date,d2)); ELSE RETURN extract(year from age(d1,d2)); END IF; END $$ language plpgsql;
@mrg: Create the function as in answer and No need to check for NULL value.

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.