SQL Cookbook Lesson

How to format a date with SQL

Learn how to format a date with SQL with examples and explanations from SQLPad.

Problem

You have a date in your SQL database but it's not in the format you want. You need to change the format of the date.

Sample Data

Let's assume we have a table named Orders with the following data:

OrderID Product OrderDate
1 Apple 2020-11-02
2 Banana 2020-11-03
3 Cherry 2020-11-04

MySQL Solution

SELECT OrderID, Product, DATE_FORMAT(OrderDate, '%d-%m-%Y') as FormattedDate
FROM Orders;

Explanation (MySQL)

In MySQL, the DATE_FORMAT() function is used to format the date. The format specifiers for the date are %d (day), %m (month), and %Y (year). In the above query, we are changing the format of the OrderDate to 'day-month-year'.

PostgreSQL Solution

SELECT OrderID, Product, TO_CHAR(OrderDate, 'DD-MM-YYYY') as FormattedDate
FROM Orders;

Explanation (PostgreSQL)

In PostgreSQL, the TO_CHAR() function is used to format the date. Similar to MySQL, the format specifiers for the date are 'DD' (day), 'MM' (month), and 'YYYY' (year). In the above query, we are changing the format of the OrderDate to 'day-month-year'.

Keep Practicing

Related Cookbook Lessons

View all lessons

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.