postgresqlpostgresql-9.4

check leap year or not in PostgreSQL


How to check the given year is leap year or not in PostgreSQL.?

I tried below query.But it is showing error message.

select extract(year from hiredate)% 4 = 0 from emp

Solution

  • You must cast the extracted year to an integer.

    select extract(year from hiredate)::integer % 4 = 0 from emp
    

    However, that is the incorrect formula for a leap year. It is Every four years except every 100 except every 400. 1900 was not a leap year, but 2000 was.

    create function is_leap_year(timestamp)
    returns boolean as $$
    declare y integer;
    begin
      y := extract(year from $1);
      return (y % 4 = 0) and (y % 100 <> 0 or y % 400 = 0);
    end
    $$ language plpgsql;
    

    Alternatively, you can check to see what day comes before March 1st in that year. This is safer as it will use Postgresql's internal logic.

    create function is_leap_year(timestamp)
    returns boolean as $$
    begin
      return date_part(
        'day',
        make_date(date_part('year', $1)::int, 3, 1) - '1 day'::interval
      ) = 29;
    end
    $$ language plpgsql;