Extract Month From Date In Postgresql

8 min read

Extracting the month from a date or timestamp is a fundamental operation in PostgreSQL, essential for reporting, data aggregation, and time-series analysis. Whether you are building a dashboard that groups sales by month, filtering records for a specific period, or formatting timestamps for display, understanding the nuances of the EXTRACT function and its alternatives ensures your queries are both performant and readable. This guide explores the standard methods, performance considerations, and practical examples for retrieving the month component in PostgreSQL.

The Standard Approach: Using the EXTRACT Function

The most explicit and SQL-standard way to retrieve a sub-field like a month from a date or timestamp value is the EXTRACT function. It conforms to the SQL standard and offers clear syntax that signals intent to anyone reading the code.

The basic syntax follows this pattern:

EXTRACT(field FROM source)

To get the month, the field argument is MONTH. The source can be a DATE, TIMESTAMP, TIMESTAMPTZ, or INTERVAL data type. The return type is DOUBLE PRECISION (a floating-point number), typically representing the month as an integer from 1 (January) to 12 (December).

Consider a table named orders with a created_at column of type TIMESTAMPTZ. To select the order ID alongside the month number:

SELECT
    order_id,
    EXTRACT(MONTH FROM created_at) AS order_month
FROM
    orders;

This query returns a numeric value, such as 1.0 for January or 12.0 for December Easy to understand, harder to ignore..

SELECT
    order_id,
    EXTRACT(MONTH FROM created_at)::INT AS order_month
FROM
    orders;

The PostgreSQL Shortcut: DATE_PART Function

PostgreSQL provides a native function, DATE_PART, which predates the SQL standard EXTRACT function. While EXTRACT is preferred for portability across database systems, DATE_PART is widely used in legacy PostgreSQL codebases and offers identical functionality for this specific use case Not complicated — just consistent. Surprisingly effective..

The syntax requires the field name as a string literal (text) and the source timestamp:

DATE_PART('month', source)

Note that the field identifier 'month' must be enclosed in single quotes. Functionally, it behaves exactly like EXTRACT:

SELECT
    order_id,
    DATE_PART('month', created_at)::INT AS order_month
FROM
    orders;

Key Difference: EXTRACT is standard SQL; DATE_PART is PostgreSQL-specific. If you are writing code intended to run on other databases (like MySQL, SQL Server, or Oracle), EXTRACT is the safer choice. For purely PostgreSQL environments, both are perfectly acceptable.

Formatting for Display: The TO_CHAR Function

When the goal is human-readable output—such as "January," "Jan," or "01"—rather than a numeric value for calculation, the TO_CHAR function is the superior tool. It converts a timestamp to a string based on a formatting template.

Common templates for the month include:

  • MM: Two-digit month number (01–12).
  • MONTH: Full uppercase month name (blank-padded to 9 chars). And * Month: Full capitalized month name (blank-padded). * Mon: Abbreviated capitalized name (Jan, Feb, etc.In real terms, ). * RM: Month in Roman numerals (I–XII).

Example usage:

SELECT
    order_id,
    TO_CHAR(created_at, 'Month') AS full_month_name,
    TO_CHAR(created_at, 'Mon') AS abbreviated_month,
    TO_CHAR(created_at, 'MM') AS two_digit_month
FROM
    orders;

Output might look like:

order_id full_month_name abbreviated_month two_digit_month
101 **January ** Jan 01
102 **December ** Dec 12

Worth pausing on this one.

Be aware that MONTH and Month return blank-padded strings (fixed width of 9 characters). If you need trimmed results, wrap the function: TRIM(TO_CHAR(created_at, 'Month')).

Practical Application: Grouping and Aggregation

One of the most common reasons to extract the month is data aggregation. Here's a good example: calculating monthly revenue or counting user sign-ups per month.

Using EXTRACT in a GROUP BY clause:

SELECT
    EXTRACT(YEAR FROM created_at)::INT AS year,
    EXTRACT(MONTH FROM created_at)::INT AS month,
    COUNT(*) AS total_orders,
    SUM(amount) AS total_revenue
FROM
    orders
GROUP BY
    EXTRACT(YEAR FROM created_at),
    EXTRACT(MONTH FROM created_at)
ORDER BY
    year, month;

Performance Tip: When grouping by month on large tables, PostgreSQL cannot use a standard B-tree index on the created_at column directly for the EXTRACT expression. To optimize this, create a functional index (expression index):

CREATE INDEX idx_orders_created_at_month ON orders (EXTRACT(MONTH FROM created_at));

This allows the planner to satisfy the GROUP BY or WHERE clause using the index without scanning the entire table.

Filtering Data by Month

Filtering rows for a specific month requires careful handling to remain SARGable (Search ARGument Able), meaning the query can apply indexes.

The Anti-Pattern (Avoid This)

Applying a function to the column in the WHERE clause prevents standard index usage:

-- Bad: Sequential scan likely on large tables
SELECT * FROM orders
WHERE EXTRACT(MONTH FROM created_at) = 1;

The Optimized Pattern (Range Query)

Instead of extracting the month from every row, define a range window using the column directly. This allows a standard B-tree index on created_at to be used effectively.

-- Good: Index scan possible
SELECT * FROM orders
WHERE created_at >= DATE_TRUNC('month', '2024-01-01'::TIMESTAMPTZ)
  AND created_at <  DATE_TRUNC('month', '2024-01-01'::TIMESTAMPTZ) + INTERVAL '1 month';

DATE_TRUNC('month', timestamp) truncates the timestamp to the first day of the month at midnight (00:00:00). Here's the thing — adding an interval of '1 month' gives you the exclusive upper bound. This pattern is vastly faster on indexed columns Nothing fancy..

Handling Time Zones: TIMESTAMP vs TIMESTAMPTZ

PostgreSQL handles time zones in a way that directly impacts month extraction. Here's the thing — the result of EXTRACT(MONTH FROM ... ) depends entirely on the time zone context of the timestamp.

  • TIMESTAMP WITHOUT TIME ZONE: The month is extracted exactly as stored. If the database stores 2023-12-31 23:00:00, the month is 12.
  • TIMESTAMP WITH TIME ZONE (TIMESTAMPTZ): PostgreSQL converts the stored UTC value to the current session's TimeZone setting (or the AT TIME ZONE clause) before extracting the field.

Example scenario: A global event occurs at `2024-01-01 00

:00:00 UTC. Consider how the month is reported under different session time zones:

-- The event is stored as 2024-01-01 00:00:00+00 (UTC)
SET TIME ZONE 'UTC';
SELECT EXTRACT(MONTH FROM '2024-01-01 00:00:00+00'::TIMESTAMPTZ);  -- returns 1

SET TIME ZONE 'America/New_York';  -- UTC-5
SELECT EXTRACT(MONTH FROM '2024-01-01 00:00:00+00'::TIMESTAMPTZ);  -- returns 12 (Dec 31, 23:00 local)

The same instant in time yields month 1 in UTC but month 12 in New York, because the local representation falls on the previous day. This is not a bug; it is the defined behavior of TIMESTAMPTZ Still holds up..

Making Time Zones Explicit

To guarantee consistent results regardless of the session setting, pin the zone with AT TIME ZONE:

-- Force interpretation in a specific zone before extracting
SELECT EXTRACT(MONTH FROM created_at AT TIME ZONE 'UTC') AS month
FROM orders;

The rule of thumb: if your timestamps are TIMESTAMPTZ and your reporting should be timezone-agnostic (e.That said, g. Even so, , daily billing cycles in UTC), always convert explicitly. If your column is TIMESTAMP WITHOUT TIME ZONE, the value is taken literally and no conversion occurs, which is simpler but pushes the burden of correctness onto your application when writing the data.

Common Pitfalls

A few mistakes surface repeatedly when working with month extraction:

  • Assuming month is enough. EXTRACT(MONTH ...) returns 1–12 with no year attached. Grouping by month alone merges January 2023 with January 2024. Always pair it with EXTRACT(YEAR ...) or, better, group by DATE_TRUNC('month', created_at) so each bucket is a distinct, sortable point in time.
  • Using EXTRACT in WHERE on large tables. As shown earlier, this defeats ordinary indexes. Prefer a half-open range (>= start AND < end) built with DATE_TRUNC.
  • Mixing ::INT casts inconsistently. EXTRACT returns a numeric in modern PostgreSQL. Casting to INT is fine for display and grouping, but be consistent so your result types stay predictable across queries.
  • Forgetting the exclusive upper bound. Using <= end_of_month with a timestamp column silently drops rows recorded later in the final day. The >= start AND < next_start pattern avoids this entirely.

Conclusion

Extracting the month from a date in PostgreSQL is straightforward at the surface—EXTRACT(MONTH FROM ...) or DATE_TRUNC('month', ...)—but doing it correctly and efficiently depends on three decisions: whether you need a numeric field or a truncated timestamp, whether your filter can remain SARGable, and how time zones affect the value you actually get back.

For grouping and reporting, reach for DATE_TRUNC('month', created_at) to get clean, sortable buckets. In real terms, for filtering, always prefer a half-open range over a function wrapped around the column, and add a functional index only when the expression-based query is unavoidable. Finally, treat time zones as a first-class concern: with TIMESTAMPTZ, the month you extract is a function of the session's TimeZone, so make your intent explicit with AT TIME ZONE whenever the answer must be stable Took long enough..

Master these patterns and month-based queries in PostgreSQL become both fast and predictable, no matter how large your tables grow or how global your data becomes The details matter here..

New In

Just Shared

Along the Same Lines

More on This Topic

Thank you for reading about Extract Month From Date In Postgresql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home