How to Get the Previous Month in SQL

To get the previous month in SQL, use the DATEADD function. This function takes three arguments: the date part, the number of units to add, and the date to start from. To get the previous month, you would use the following SQL query:


This query will return the date of the previous month. For example, if the current date is 2020-05-01, the query will return 2020-04-01.


Let's look at a few examples of how this function can be used. Suppose you have a table called orders with the following data:


If you wanted to get the total number of orders in the previous month, you would use the following query:

SELECT COUNT(*) FROM orders WHERE order_date >= DATEADD(month, -1, GETDATE()) AND order_date < GETDATE();

This query would return the result 3, since there are three orders in the previous month (2020-04-01, 2020-05-01, and 2020-05-02).

Additional Info

The DATEADD function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database.

Want to build your own LLM Apps with AirOps👇👇