How to Group by Month in SQLite Database: SQLite Operators: STRFTIME() Table of Contents Problem: Example: Solution: Discussion: Problem: You'd like to group records by month in an SQLite database. Example: Our database has a table named notebooks with data in the columns id, color, and production_timestamp. idcolorproduction_timestamp 1Burgundy2022-02-01 11:45:23 2Gray2022-02-01 11:46:13 3Orange2022-01-22 17:22:05 Solution: You can use the STRFTIME() function to get the month and year value from the date. You can also use it to group these values. Here's the query you would write: SELECT STRFTIME('%m-%Y', production_timestamp) AS production_month, COUNT(id) AS count FROM notebooks GROUP BY STRFTIME('%m-%Y', production_timestamp); Here’s the result of the query: production_monthcount 01-20221 02-20222 Discussion: Grouping records by month is a very common operation in SQLite. In our example, the number of notebooks produced is totaled for each month. You usually want to take into account both the year and the month, i.e. you want to group notebooks produced in January 2022 separately from notebooks produced in January 2021. We use the STRFTIME() function to get the month and year from the date. This function returns the date formatted according to the format string specified as the first argument. Here, we use the '%m-%Y' format: %m stands for the numeric month (01 through12), and %Y stands for the 4-digit year. The second argument is the date (here, the production_timestamp column). In our database, the Orange notebook has the production date 2022-01-22 17:22:05; after it's been truncated to month precision, it becomes 01-2022. We use STRFTIME() in the GROUP BY clause to group by the year and month and in the SELECT clause to display the label for each month. Recommended courses: SQL Basics Standard SQL Functions Recommended articles: Standard SQL Functions Cheat Sheet How Does SQL GROUP BY Work? 5 Examples of GROUP BY SQL Date and Time Functions in 5 Popular SQL Dialects GROUP BY and Aggregate Functions: A Complete Overview Top 9 SQL GROUP BY Interview Questions See also: How to Add a Month to a Date in SQLite How to Order by Month Name in SQLite How to Format a Datetime in SQLite How to Calculate the Difference Between Two Dates in SQLite Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query