Postgres GROUP BY Month, Year, Day by Example

Updated

postgres group by month

Use DATE_TRUNC and group by the output alias:

SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales GROUP BY month ORDER BY month;

That alias works in GROUP BY and ORDER BY. Naming an output column in ORDER BY is standard SQL; in GROUP BY it is a documented PostgreSQL extension of the standard. As of October 2026, MySQL accepts it too, while SQL Server does not. In PostgreSQL the alias does not work in WHERE or HAVING, which is where this trips people up.

A table you can follow along with

CREATE TABLE sales (
  id       serial PRIMARY KEY,
  product  text NOT NULL,
  quantity int  NOT NULL,
  sold_at  timestamptz NOT NULL
);

INSERT INTO sales (product, quantity, sold_at) VALUES
  ('Widget', 5, '2026-01-14 09:12+00'), ('Widget', 3, '2026-01-28 16:40+00'),
  ('Gadget', 7, '2026-02-03 11:05+00'), ('Widget', 2, '2026-02-19 08:30+00'),
  ('Gadget', 4, '2026-02-27 14:55+00'), ('Widget', 9, '2026-03-08 10:00+00');

SET TimeZone = 'UTC';   -- so your output matches the output below

Note the column is sold_at. There is no column called month; that name exists only as an alias you create in the SELECT list.

Group by month

SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales GROUP BY month ORDER BY month;

         month          | total
------------------------+-------
 2026-01-01 00:00:00+00 |     8
 2026-02-01 00:00:00+00 |    13
 2026-03-01 00:00:00+00 |     9
(3 rows)

DATE_TRUNC returns a timestamp snapped to the start of the bucket, so the rows sort chronologically and stay comparable to other timestamps. Swap 'month' for 'year', 'week', 'day', or 'hour'; the query shape never changes.

Group by day

DATE_TRUNC('day', sold_at) returns a timestamptz at midnight of that day, while sold_at::date returns a plain date; both group the same way, and each sale here falls on its own day. Both depend on the session TimeZone, as the timezone section below shows for DATE_TRUNC; I checked the ::date cast with SET TimeZone = 'America/Chicago' on PostgreSQL 17.11 on 23 October 2026, and it moved 03:00 UTC on 1 February to 31 January.

SELECT DATE_TRUNC('day', sold_at) AS day_trunc, sold_at::date AS day_cast, SUM(quantity) AS total
FROM sales GROUP BY day_trunc, day_cast ORDER BY day_trunc;
       day_trunc        |  day_cast  | total 
------------------------+------------+-------
 2026-01-14 00:00:00+00 | 2026-01-14 |     5
 2026-01-28 00:00:00+00 | 2026-01-28 |     3
 2026-02-03 00:00:00+00 | 2026-02-03 |     7
 2026-02-19 00:00:00+00 | 2026-02-19 |     2
 2026-02-27 00:00:00+00 | 2026-02-27 |     4
 2026-03-08 00:00:00+00 | 2026-03-08 |     9
(6 rows)

Group by year and month as separate numbers

Use EXTRACT when you want the parts as integers, typically to feed a pivot or a chart axis:

SELECT EXTRACT(YEAR FROM sold_at) AS yr, EXTRACT(MONTH FROM sold_at) AS mon,
       SUM(quantity) AS total
FROM sales GROUP BY yr, mon ORDER BY yr, mon;

  yr  | mon | total
------+-----+-------
 2026 |   1 |     8
 2026 |   2 |    13
 2026 |   3 |     9
(3 rows)

Which one should you use?

Function Returns Pick it when
DATE_TRUNC('month', c) A timestamp: 2026-02-01 00:00:00+00 Default choice. Sorts correctly, stays a date type, can be compared to other timestamps and used with an index on c.
EXTRACT(MONTH FROM c) A number: 2 You want month-of-year across all years (seasonality), or separate year/month columns.
TO_CHAR(c, 'YYYY-MM') Text: 2026-02 Display only. Text sorts lexically: fine for YYYY-MM, wrong for MM-YYYY or Mon YYYY.

Grouping by two things at once

SELECT product, DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales GROUP BY product, month ORDER BY month, product;

 product |         month          | total
---------+------------------------+-------
 Widget  | 2026-01-01 00:00:00+00 |     8
 Gadget  | 2026-02-01 00:00:00+00 |    11
 Widget  | 2026-02-01 00:00:00+00 |     2
 Widget  | 2026-03-01 00:00:00+00 |     9
(4 rows)

A common mistake is writing SELECT product, month, … and naming month without defining it as an alias. PostgreSQL rejects it:

SELECT product, month, SUM(quantity) FROM sales GROUP BY product, month;
ERROR:  column "month" does not exist
LINE 1: SELECT product, month, SUM(quantity) FROM sales GROUP BY pro...
                        ^

The alias caveat: GROUP BY yes, WHERE and HAVING no

The alias resolves in GROUP BY:

... GROUP BY month ORDER BY month;      -- works

and fails in both filter clauses:

SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales GROUP BY month HAVING month >= '2026-02-01';
ERROR:  column "month" does not exist

SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales WHERE month >= '2026-02-01' GROUP BY month;
ERROR:  column "month" does not exist

Three fixes, in order of preference:

-- 1. Filter the raw column in WHERE. Fastest: it can use an index on sold_at
--    and cuts rows before aggregation.
SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
FROM sales WHERE sold_at >= '2026-02-01' GROUP BY month ORDER BY month;

-- 2. Repeat the expression in HAVING (needed when the filter is on an aggregate
--    or must run after grouping).
... GROUP BY month HAVING DATE_TRUNC('month', sold_at) >= '2026-02-01';

-- 3. Wrap it in a subquery or CTE, then the alias is a real column.
SELECT * FROM (
  SELECT DATE_TRUNC('month', sold_at) AS month, SUM(quantity) AS total
  FROM sales GROUP BY month
) m WHERE m.month >= '2026-02-01' ORDER BY m.month;

All three return the same two rows (Feb 13, Mar 9). Prefer #1: the other two aggregate rows you are about to discard. To see how PostgreSQL executes any of the three, read the plan with EXPLAIN ANALYZE query plans. Whether the subquery or CTE in #3 is inlined or materialized is covered in CTEs: inlined or MATERIALIZED.

If the column is timestamptz, buckets depend on your session timezone

DATE_TRUNC on a timestamptz is evaluated in the session’s TimeZone, per the PostgreSQL documentation on date_trunc, so the same instant can land in different months:

SET TimeZone = 'UTC';
SELECT DATE_TRUNC('month', TIMESTAMPTZ '2026-02-01 03:00:00+00');
 2026-02-01 00:00:00+00

SET TimeZone = 'America/Chicago';
SELECT DATE_TRUNC('month', TIMESTAMPTZ '2026-02-01 03:00:00+00');
 2026-01-01 00:00:00-06

If a monthly report has to agree between a cron job and a web request, set the timezone explicitly in the query rather than inheriting it: DATE_TRUNC('month', sold_at AT TIME ZONE 'UTC').


Verified 2026-08-09 on PostgreSQL 17.10 (aarch64-apple-darwin25.6.0). Every command above was executed and the output pasted unedited, including the errors. Reproduce all of it with this script, which builds a throwaway cluster in a temp directory, checks each claim, and deletes it afterwards. The group-by-day block, which the script does not cover yet, was run separately on PostgreSQL 17.11 on 23 October 2026 with the same table and SET TimeZone = 'UTC';.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.