1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
38

Understanding SQL Date Formats and Functions

Updated on 19/06/202465 Views

Introduction:

Understanding SQL date format is crucial for the effective management and manipulation of date and time data. Let’s delve into the intricacies of SQL date formats, covering functions, types, and conversion methods with practical examples and illustrations. In database management, handling dates and times is crucial for various operations, such as data analysis, reporting, and application development. Let’s dig deeper into this format.

Overview:

Managing date and time data is a fundamental aspect of database management, and SQL offers robust tools to handle these values effectively. The SQL Date Format encompasses a range of functions, formats, and types, which are tailored to manipulate date and time data within databases.

This overview provides insights into the core components of SQL Date Format, including:

  • Date Functions: SQL offers a suite of built-in functions to perform calculations, comparisons, and conversions with date and time data.
  • Date Formats: SQL supports various formats to store and display date and time values, such as DATE, DATETIME, TIMESTAMP, and more.
  • Data Types: SQL accommodates different data types dedicated to date and time values, each with its characteristics and use cases.

SQL Date Format Basics:

SQL Date Functions:

SQL provides numerous built-in functions to manipulate date and time data. Example of using the GETDATE() function to retrieve the current date and time:

Code:- SELECT GETDATE() AS CurrentDateTime;

This query will return the current date and time:

Output:

CurrentDateTime

-----------------------

2024-03-05 10:30:45.000

In SQL, the GETDATE() function is commonly used to retrieve the current system date and time. Internally, GETDATE() typically relies on the system clock of the database server to fetch this information.

-  Internal Process: In the above example, when you call GETDATE() in an SQL query, the database engine accesses the server's system clock where the database is running. It retrieves the current date and time information from the system.

This SQL query selects the current date and time, using the GETDATE() function, and assigns an alias CurrentDateTime to the returned value.

The output reveals the current date and time, in the default format used by the SQL Server. The server includes the date in 'YYYY-MM-DD' format, followed by the time in 'HH:MM:SS' format, and fractional seconds if available.

In summary, GETDATE() in SQL retrieves the current system date and time from the server's clock and returns it as a datetime value. It allows you to work with the current date and time information within your SQL queries.

SQL Date Formats:

SQL supports various date and time formats for storing and displaying date values. For example, the DATETIME format displays both date and time components:

Code: SELECT CAST('2024-03-05 10:30:45.123' AS DATETIME) AS DateTimeValue;

This query will return the datetime value in the specified format:

Output:

DateTimeValue

-----------------------

2024-03-05 10:30:45.123

SQL Date Types:

SQL offers different data types for representing date and time values. For instance, the DATE type stores only the date component without the time:

Code- SELECT CAST('2024-03-05' AS DATE) AS DateValue;

This query will return the date value without the time component:

Output:

DateValue

------------

2024-03-05

In this representation of the SQL Date Functions, Formats, and Types:

  • The first section demonstrates SQL Date Functions, such as GETDATE().
  • The second section showcases SQL Date Formats, including DATETIME.
  • The third section illustrates SQL Date Types, such as DATE.

SQL Date Format Functions:

SQL Convert Date Format (or Date format convert in SQL)

SQL's CONVERT() function converts a date or time value from one format to another. For example, imagine a date stored in a DATETIME format ('2024-03-05 10:30:45.123'), which you want to change the format for:

Code - SELECT CONVERT(VARCHAR, '2024-03-05 10:30:45.123', 101) AS ConvertedDate;

This query will convert the datetime value to the format 'MM/DD/YYYY':

Output:

ConvertedDate

--------------

03/05/2024

SQL Get Date From Datetime

Sometimes, you might need to extract only the date part from a datetime value. SQL provides functions like CAST() or CONVERT(). For example:

Code- SELECT CAST('2024-03-05 10:30:45.123' AS DATE) AS DateOnly;

This query will return only the date part from the datetime value:

Output:

DateOnly

------------

2024-03-05

SQL DateTime Format (or Datetime in SQL format)

SQL supports various datetime formats, which allow you to specify how date and time values are displayed. For instance, you might want to display the datetime value in the format 'YYYY-MM-DD HH:MI:SS':

Code- SELECT FORMAT('2024-03-05 10:30:45.123', 'YYYY-MM-DD HH24:MI:SS') AS FormattedDateTime;

This query will format the datetime value according to the specified format:

Output:

FormattedDateTime

-------------------

2024-03-05 10:30:45

SQL Date Functions

Let's dive into SQL date functions with examples and their corresponding outputs:

1. GETDATE(): This function returns the current system date and time.Example:

Code- SELECT GETDATE() AS CurrentDateTime;

Output:

CurrentDateTime

--------------------------

2024-03-05 10:30:45.123

2. DATEADD(): This function adds a specified interval to a given date.Example:

Code- SELECT DATEADD(DAY, 7, '2024-03-05') AS SevenDaysLater;

Output:

SevenDaysLater

---------------

2024-03-12

3. DATEDIFF(): This function analyses the difference between two different dates, in terms of a specified interval.

Example:

Code- SELECT DATEDIFF(DAY, '2024-03-01', '2024-03-10') AS DaysDifference;

Output:

DaysDifference

---------------

9

4. DATEPART(): This function extracts a specific part (e.g., year, month, day) from a given date.Example:

Code- SELECT DATEPART(YEAR, '2024-03-05') AS YearPart;

Output:

YearPart

--------

2024

5. YEAR(), MONTH(), DAY(): These functions extract the year, month, and day components from a given date, respectively.Example:

Code- SELECT YEAR('2024-03-05') AS Year;

Output:

Year

----

2024

Datetime Function in SQL

In SQL, the DATETIME function isn't a specific function like the ones mentioned earlier. Instead, it refers to a data type or a combination of functions and expressions, which are further used to work with date and time values. SQL databases typically provide data types such as DATETIME, TIMESTAMP, DATE, and TIME to store date and time information.

DATETIME Data Type:

The DATETIME data type represents a specific point in time, including both date and time components. Let’s understand how it works with the help of an example:

Code- CREATE TABLE ExampleTable (

    Id INT PRIMARY KEY,

    DateTimeValue DATETIME

);

INSERT INTO ExampleTable (Id, DateTimeValue) VALUES (1, '2024-03-05 10:30:45');

In this example:- We create a table named ‘ExampleTable’ with a column named ‘DateTimeValue’ of type DATETIME.- Then, we insert a record with an ID of 1 and a DATETIME value '2024-03-05 10:30:45' in the ‘ExampleTable’.

Functions That Manipulate DateTime Values:

SQL provides various functions to manipulate datetime values. Here are some common ones:

GETDATE(), DATEADD(), DATEDIFF().

I have explained these functions with examples above.

SQL Formats:

These formats have been explained under the header: ‘SQL Date Format Functions’.

Time Format:

HH:MI:SS: This format represents the time values in a sequence of hour:minute:second.

Example:

Code- SELECT CAST('10:30:45' AS TIME) AS TimeValue;

Output:

TimeValue

----------

10:30:45

Date Type in SQL:

In SQL, ‘Date Type’ refers to a specifically designed data type to store date values without any associated time information. As the name goes, this type is useful when you only need to work with dates and not with times. Let's explore the date type in SQL with examples and their outputs:

Date Type:

DATE: The DATE type is used to save dates without any time component. It typically represents a specific day in the format ‘YYYY-MM-DD’.

Examples:

1. Creating a Table with a Date Column:

Code- CREATE TABLE Orders (

    OrderID INT PRIMARY KEY,

    OrderDate DATE

);

In this example, we create a table named ‘Orders’ with a column named ‘OrderDate’ of type DATE. This column will store only the date component of the order.

2. Inserting Data into the Table:

Code- 

INSERT INTO Orders (OrderID, OrderDate) VALUES 

(1, '2024-03-05'),

(2, '2024-03-06'),

(3, '2024-03-07');

We insert three records into the ‘Orders’ table, each with an ‘OrderDate’ specified in the ‘YYYY-MM-DD’ format.

3. Querying Data from the Table:

Code- SELECT * FROM Orders;

Output:

OrderID   OrderDate

-------------------

1         2024-03-05

2         2024-03-06

3         2024-03-07

This query retrieves all records from the ‘Orders’ table, displaying the columns titled ‘OrderID’ and ‘OrderDate’.

4. Performing Date Calculations:

Code- 

SELECT 

    OrderID, 

    OrderDate, 

    DATEADD(DAY, 7, OrderDate) AS SevenDaysLater 

FROM Orders;

Output:

OrderID   OrderDate    SevenDaysLater

-------------------------------------------------------

1         2024-03-05   2024-03-12

2         2024-03-06   2024-03-13

3         2024-03-07   2024-03-14

In this query, we use the DATEADD() function to add 7 days to each ‘OrderDate’, resulting in a new date value, stored in the column titled ‘SevenDaysLater’.

The DATE type in SQL is specifically designed to store date values without any time component. 

Cast Date Format in SQL:

In SQL, casting date formats involve converting date values from one data type to another. This is commonly used when you need to change the data type of a date column or display dates in a specific format. 

Example:Suppose there is a table named ‘Orders’ with a column ‘OrderDate’ storing dates in the format 'YYYY-MM-DD'. You want to display these dates in the format 'MM/DD/YYYY'. You can achieve this by casting the ‘OrderDate’ column to a VARCHAR data type and formatting it accordingly.

Code- 

SELECT 

    OrderID, 

    CAST(OrderDate AS VARCHAR(10)) AS FormattedDate 

FROM Orders;

Output:

OrderID   FormattedDate

---------------------------------

1         2024-03-05

2         2024-03-06

3         2024-03-07

The output displays the ‘OrderID’ and the ‘FormattedDate’ columns. However, the ‘FormattedDate’ column represents the dates in the 'YYYY-MM-DD' format due to the casting operation performed.

Date Format in SQL Server:

In SQL Server, date formats determine how date and time values are displayed and interpreted. SQL Server provides various options to format dates, according to different styles and preferences. Example:Suppose there is a table named ‘Orders’ with a column for ‘OrderDate’ storing dates in the format 'YYYY-MM-DD’, which you want to retrieve the orders and their dates formatted as 'MM/DD/YYYY' from. You can achieve this using the CONVERT() function in SQL Server:

Code- 

SELECT 

    OrderID, 

    CONVERT(VARCHAR, OrderDate, 101) AS FormattedDate 

FROM Orders;

Output:

OrderID   FormattedDate

--------------------------------

1         03/05/2024

2         03/06/2024

3         03/07/2024

The output displays the columns listed as ‘OrderID’ and the ‘FormattedDate’. The column for ‘FormattedDate’ represents the dates in the 'MM/DD/YYYY' format, as specified in the CONVERT() function.

Date Format in MS SQL:

In Microsoft SQL Server (MS SQL), date formats determine how date and time values are displayed and interpreted. SQL Server provides various options to format dates, on the basis of different styles and preferences. 

Example:

Suppose you have a table titled as ‘Orders’ with a column ‘OrderDate’ storing dates in the format 'YYYY-MM-DD'. You want to retrieve the orders along with their dates formatted as 'MM/DD/YYYY'. You can achieve this using the FORMAT() function in MS SQL:

Code- 

SELECT 

    OrderID, 

    FORMAT(OrderDate, 'MM/dd/yyyy') AS FormattedDate 

FROM Orders;

In this example:- We use the FORMAT() function to format the ‘OrderDate’ column according to the 'MM/DD/YYYY' format.- The column named ‘FormattedDate’ now represents the ‘OrderDate’ values in the desired format.

Output:

OrderID   FormattedDate

----------------------------------

1         03/05/2024

2         03/06/2024

3         03/07/2024

The output displays columns for ‘OrderID’ and the ‘FormattedDate’. The ‘FormattedDate’ column represents the dates in the 'MM/DD/YYYY' format, as specified in the FORMAT() function.

Change Date Format in SQL:

Changing the date format in SQL involves altering the representation of date values, without modifying the actual data stored in the database. This is particularly useful when you need to standardize the display of date values or match a specific format for reporting or integration purposes. 

Example:

Suppose there is a table named ‘Orders’ with a column named ‘OrderDate’ storing dates in the format 'YYYY-MM-DD'. You want to retrieve the orders along with their dates formatted in a different format. You can achieve this using the appropriate functions to convert and format date values.

Code- 

SELECT 

    OrderID, 

    FORMAT(OrderDate, 'MM/dd/yyyy') AS FormattedDate 

FROM Orders;

In this example:- We use the FORMAT() function to format the ‘OrderDate’ column according to the 'MM/DD/YYYY' format.- The column for ‘FormattedDate’ now represents the values of ‘OrderDate’ in the desired format.

Output:

OrderID   FormattedDate

---------------------------------

1         03/05/2024

2         03/06/2024

3         03/07/2024

In SQL, you can use functions like FORMAT() to change the date format according to different styles and preferences.

Convert String to Date in SQL:

Conversion of a string into a date in SQL involves transforming a character string, representing a date into a date data type. This conversion is crucial for ensuring accurate date operations and comparisons within the database. 

Example:

Suppose you have a string column named ‘DateString’ in a table named ‘Orders’, containing dates in the format 'YYYY-MM-DD'. You want to convert these string dates into the date data type. You can achieve this using the CONVERT() function or the CAST() function.

  • Using CONVERT() function:

Code- 

SELECT 

    OrderID, 

    CONVERT(DATE, DateString, 23) AS OrderDate

FROM Orders;

  • Using CAST() function:

Code- 

SELECT 

    OrderID, 

    CAST(DateString AS DATE) AS OrderDate

FROM Orders;

In both examples:- We use either the CONVERT() function or the CAST() function to convert the column for ‘DateString’ from a string to the date data type.- The 23 in the CONVERT() function represents the style code for 'YYYY-MM-DD' format.

Output:

OrderID   OrderDate

-------------------------------

1         2024-03-05

2         2024-03-06

3         2024-03-07

The output displays the columns for ‘OrderID’ and ‘OrderDate’. ‘OrderDate’ represents the dates converted from string to date format, allowing for accurate date operations and comparisons within the SQL queries.In SQL, you can use the CONVERT() function or the CAST() function to convert a string to a date data type.

Cast() Function:

In SQL, the CAST() function is used to convert data from one data type to another. When dealing with dates and times, CAST() can be particularly useful to convert different date and time data types or formats.

Here's a brief explanation of how CAST() works with SQL date formats, along with an example and its output:

Internal Process: When you use CAST() to convert a date or time value, the database engine internally handles the conversion according to the specified target data type. For example, if you're converting a string to a date, the engine parses the string according to the specified date format and creates a date object.

SELECT CAST('2024-03-07' AS DATE) AS ConvertedDate;

In this example, we're converting a string '2024-03-07' to a DATE data type using CAST(). This assumes that the string follows the 'YYYY-MM-DD' format, as it's a standard date format in SQL.

The output of the above SQL query would be:

ConvertedDate

-------------

2024-03-07

In this, the string '2024-03-07' has been successfully converted to a date format and is displayed in the result set.

The exact behavior of CAST() can vary slightly depending on the database system you're using (e.g., SQL Server, MySQL, PostgreSQL). Also, the success of the conversion depends on the compatibility between the source and target data types, and the accuracy of the input data.

Wrapping Up:

Mastering SQL date formats is essential for effective date manipulation and presentation in database queries. Understanding how to format, convert, and manipulate date values allows for accurate data representation and analysis. By leveraging SQL date functions and expressions, developers can ensure consistency in date handling across database applications, which enable efficient data management and reporting.

FAQs:

Q1. What is the format of To_date in SQL?

A.  The TO_DATE function is specific to Oracle SQL. It is used to convert a character string representing a date in a specified format into a date data type. Its format is: TO_DATE(string, format)

Q2. What is the date format for TO_CHAR?

A. In Oracle SQL, the TO_CHAR function converts a date or timestamp value into a character string with a specified format. Its format is: 

TO_CHAR(date_value, format_mask)

Pavan Vadapalli

Pavan Vadapalli

Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and l… Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...