How to Format a DateTime in SQL

Formatting a datetime in SQL is quite simple, and can be done with the DATE_FORMAT function. This function takes two arguments: the datetime you want to format, and the format you want to use. The syntax for the DATE_FORMAT function is as follows:

SELECT DATE_FORMAT(datetime, format) FROM table_name;

The datetime argument is the datetime you want to format, and the format argument is the format you want to use. The format argument is a string of characters that specify how the datetime should be formatted. For example, the string '%Y-%m-%d' will format the datetime as a four-digit year, followed by a two-digit month, followed by a two-digit day.

Examples

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:

orders
order_idorder_date
12020-01-01
22020-02-15
32020-03-31


If you wanted to format the order_date column as a four-digit year, followed by a two-digit month, followed by a two-digit day, you would use the following query:

SELECT DATE_FORMAT(order_date, '%Y-%m-%d') FROM orders;

This query would return the following result:


2020-01-01
2020-02-15
2020-03-31

Additional Info

The DATE_FORMAT 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👇👇