Group By Year And Month Sql

4 min read

Grouping records by year and month in SQL is one of the most practical skills you can develop for reporting, analytics, and business intelligence. Whether you need monthly sales totals, yearly user signups, or seasonal trends, the group by year and month SQL pattern helps you transform raw dates into meaningful summaries. But the challenge is that SQL dialects handle date extraction differently, so the exact syntax changes across MySQL, PostgreSQL, SQL Server, Oracle, and SQLite. This guide walks through the core concepts, provides working examples for each major database, and highlights performance and accuracy pitfalls that often trip up beginners And it works..

Why Grouping by Year and Month Matters

Dates in a database are usually stored as full timestamps or DATE values, such as 2024-03-15. If you group only by the raw date column, you get one row per day, which is rarely useful for high-level reporting. By extracting the year and month, you can collapse thousands of daily records into a clean monthly summary Most people skip this — try not to..

Common use cases include:

  • Monthly revenue reports for finance and accounting.
  • Year-over-year comparisons of sales, signups, or traffic.
  • Seasonal trend analysis to identify peak months.
  • Cohort analysis based on the month a customer first purchased.
  • Inventory and staffing forecasts driven by historical monthly demand.

The key idea is simple: derive a year part and a month part from the date column, then use those parts in the GROUP BY clause alongside aggregate functions such as SUM(), COUNT(), or AVG().

The Standard Pattern

Most SQL databases support a pattern like this:

SELECT
  YEAR(order_date) AS order_year,
  MONTH(order_date) AS order_month,
  SUM(total_amount) AS monthly_revenue
FROM orders
GROUP BY
  YEAR(order_date),
  MONTH(order_date)
ORDER BY
  order_year,
  order_month;

This query returns one row per year-month combination, with the total revenue for that period. So the ORDER BY clause is important because SQL does not guarantee sorted output unless you explicitly request it. Without ordering, your monthly report may appear in an arbitrary sequence Which is the point..

Worth pausing on this one.

Some databases allow you to group by column aliases, which can make the query shorter:

SELECT
  YEAR(order_date) AS order_year,
  MONTH(order_date) AS order_month,
  SUM(total_amount) AS monthly_revenue
FROM orders
GROUP BY order_year, order_month
ORDER BY order_year, order_month;

On the flip side, alias support in GROUP BY is not universal. MySQL and SQLite are generally permissive, while PostgreSQL and SQL Server have stricter rules. For portable SQL, repeat the expressions in the GROUP BY clause That's the part that actually makes a difference..

Database-Specific Syntax

MySQL

MySQL provides the YEAR() and MONTH() functions directly:

SELECT
  YEAR(sale_date) AS sale_year,
  MONTH(sale_date) AS sale_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY
  YEAR(sale_date),
  MONTH(sale_date)
ORDER BY
  sale_year,
  sale_month;

You can also use DATE_FORMAT() to produce a single YYYY-MM label:

SELECT
  DATE_FORMAT(sale_date, '%Y-%m') AS year_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY year_month
ORDER BY year_month;

The DATE_FORMAT() approach is convenient for display, but grouping by a string can be slightly slower than grouping by numeric year and month columns Easy to understand, harder to ignore. That's the whole idea..

PostgreSQL

PostgreSQL offers several options. The most readable is DATE_TRUNC():

SELECT
  DATE_TRUNC('month', sale_date) AS sale_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY DATE_TRUNC('month', sale_date)
ORDER BY sale_month;

DATE_TRUNC('month', sale_date) returns the first day of the month as a timestamp, such as 2024-03-01 00:00:00. This is excellent for sorting and charting because the result remains a date-like value.

You can also use EXTRACT():

SELECT
  EXTRACT(YEAR FROM sale_date) AS sale_year,
  EXTRACT(MONTH FROM sale_date) AS sale_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY
  EXTRACT(YEAR FROM sale_date),
  EXTRACT(MONTH FROM sale_date)
ORDER BY
  sale_year,
  sale_month;

For a formatted string, use TO_CHAR():

SELECT
  TO_CHAR(sale_date, '%Y-M') AS year_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY TO_CHAR(sale_date, '%Y-%M')
ORDER BY year_month;

SQL Server

SQL Server uses YEAR(), MONTH(), and DATEPART():

SELECT
  YEAR(sale_date) AS sale_year,
  MONON(sale_date) AS sale_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY
  YEAR(sale_date),
  MONTH(sale_date)
ORDER BY
  sale_year,
  sale_month;

Alternatively, DATEPART() can extract both parts:

SELECT
  DATEPART(YEAR, sale_date) AS sale_year,
  DATEPART(MONTH, sale_date) AS sale_month,
  SUM(amount) AS total_sales
FROM sales
GROUP BY
  DATEPART(YEAR, sale_date),
  DATEPART(MONTH, sale_date)
ORDER BY
  sale_year,
  sale_month;

For a single formatted column, use FORMAT():

Freshly Posted

What People Are Reading

Keep the Thread Going

More That Fits the Theme

Thank you for reading about Group By Year And Month Sql. 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