MONTH() equivalent

From PostgreSQL wiki
Jump to navigationJump to search

Compatibility Snippets

MONTH() substitute

Works with PostgreSQL

Any version

Written in

SQL

Depends on

Nothing


These functions extract the month from timestamp (with/without TZ and date format). If you want to extract another piece of data (like year), you only have to replace the correct word in the extract function.

CREATE OR REPLACE FUNCTION month(timestamp without time zone) RETURNS integer
AS $$ 
      SELECT extract(MONTH FROM $1)::integer; 
$$ LANGUAGE sql IMMUTABLE;
CREATE OR REPLACE FUNCTION month(timestamp with time zone) RETURNS integer
AS $$
      SELECT extract(MONTH FROM $1)::integer;
$$ LANGUAGE sql STABLE;
CREATE OR REPLACE FUNCTION month(date) RETURNS integer
AS $$
      SELECT extract(MONTH FROM $1)::integer;
$$ LANGUAGE sql IMMUTABLE;

See also

EXTRACT() documentation