How to Get the Year and Month from a Date in SQL

How to Get the Year and Month from a Date in SQL

Do you need to extract the year and month from a date in SQL? You're in luck! SQL has a few handy functions that can help you get the information you need.

The Solution

The solution is to use the YEAR() and MONTH() functions. These functions take a single argument, which is the date you want to extract the year and month from. For example, if you wanted to extract the year and month from the date 2020-03-15, you would use the following query:

SELECT YEAR('2020-03-15'), MONTH('2020-03-15');

This query would return the result 2020, 3, since the year is 2020 and the month is 3.

Examples

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


order_id  order_date
--------------------
1         2020-03-15
2         2020-04-20
3         2020-05-01

If you wanted to extract the year and month from the order_date column, you would use the following query:

SELECT YEAR(order_date), MONTH(order_date) FROM orders;

This query would return the following result:


YEAR(order_date)  MONTH(order_date)
----------------------------------
2020              3
2020              4
2020              5

Additional Info

The YEAR() and MONTH() functions are 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👇👇