The Wayback Machine - https://web.archive.org/web/20240930183340/https://www.geeksforgeeks.org/useful-date-and-time-functions-in-pl-sql/
Open In App

Date and Time Functions in PL/SQL

Last Updated : 17 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Date and Time Functions in PL/SQL are useful for date and time operations like extracting date components, performing date arithmetic, and converting between date formats.

Date and Time Functions in PL/SQL

There are many useful Date and Time functions in PL/SQL. A table of such functions along with their description is given below:

S.noFunctionDescription
1SYSDATEReturns the current date and time. Example: SELECT SYSDATE FROM DUAL;
2EXTRACTExtracts a specific field (year, month, day, hour, minute, second) from a date or timestamp. Example: SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL;
3ADD_MONTHS(date, n)Adds a specified number of months to a date. Example: SELECT ADD_MONTHS(SYSDATE, 3) FROM DUAL;
4LAST_DAY(date)Returns the last day of the month for a given date. Example: SELECT LAST_DAY(SYSDATE) FROM DUAL;
5MONTHS_BETWEEN(date1, date2)Returns the number of months between two dates. Example: SELECT MONTHS_BETWEEN(SYSDATE, ’01-JAN-2019′) FROM DUAL;
6NEXT_DAY(date, day_of_week)Returns the date of the first weekday that is later than the given date. Example: SELECT NEXT_DAY(SYSDATE, ‘MONDAY’) FROM DUAL;

Let’s understand each of the PL/SQL Date and Time functions with examples.

SYSDATE Function

The SQL SYSDATE function returns the current date and time set for operating system on which the database resides.

The function SYSDATE returns 7 bytes of data, which includes:

  • Century
  • Year
  • Month
  • Day
  • Hour
  • Minute
  • Second

EXTRACT() Function

Oracle helps you to extract Year, Month, and Day from a date using the Extract() Function.

EXTRACT() Function Example for Extracting year

Query:

SELECT SYSDATE AS CURRENT_DATE_TIME, 
EXTRACT(Year FROM SYSDATE) AS ONLY_CURRENT_YEAR
FROM Dual

Output:

CURRENT_DATE_TIMEONLY_CURRENT_YEAR
05.Feb.2019 07:29:242019

Explanation: Useful to retrieve only the year from the System date/Current date or particular specified date.

EXTRACT() Function Example for Extracting Month

Query:

SELECT SYSDATE AS CURRENT_DATE_TIME, 
EXTRACT(Month FROM SYSDATE) AS ONLY_CURRENT_MONTH
FROM Dual

Output:

CURRENT_DATE_TIMEONLY_CURRENT_MONTH
05.Feb.2019 07:29:24Feb

Explanation: Useful to retrieve only a month from the System date/Current date or particular specified date.

ADD_MONTHS () Function

Using this method in PL/SQL you can add as well as subtract a number of months(n) to a date. Here ‘n’ can be both negative or positive.

ADD_MONTHS (date, n) Example

Query:

SELECT ADD_MONTHS(SYSDATE, -1) AS PREV_MONTH, SYSDATE AS CURRENT_DATE,                                 
ADD_MONTHS(SYSDATE, 1) AS NEXT_MONTH
FROM Dual

Output:

PREV_MONTHCURRENT_DATENEXT_MONTH
02.Jan.2019 09:15:4602.Feb.2019 09:15:4602.Mar.2019 09:15:46

Explanation: ADD_MONTHS function has two parameters one is a date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date.

LAST_DAY() Function

Using this method in PL/SQL you can get the last day in the month of specified date.

LAST_DAY() Function Example

Query:

SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) AS LAST_DAY_OF_MONTH,                                 
LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTH
FROM Dual

Output:

CURRENT_DATELAST_DAY_OF_MONTHFIRST_DAY_OF_NEXT_MONTH
02.Feb.2019 09:32:0028.Feb.2019 09:32:0001.Mar.2019 09:32:00

Explanation: In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month.

MONTHS_BETWEEN () Function

Using this method in PL/SQL you can calculate the number of months between two entered dates date1 and date2. if date1 is later than date2 then the result would be positive and if date1 is earlier than date2 then result is negative.

Note: If a fractional month is calculated, the MONTHS_BETWEEN function calculates the fraction based on a 31-day month.

MONTHS_BETWEEN () Function Example

Query :

SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'),
TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHS
FROM Dual
SQL
SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'), 
                       TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHS
FROM Dual

Output:

NUMBER_OF_MONTHS
3.58

Explanation: Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers. Entered date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function. Let’s select the number of months an employee has worked for the company.

NEXT_DAY() Function

It will return the upcoming date of the first weekday that is later than the entered date.It has two parameters first date where, system date or specified date can be entered; second day of week which should be in character form.

NEXT_DAY() Function Example 

Query:

SELECT NEXT_DAY(SYSDATE, 'SUNDAY') AS NEXT_SUNDAY
FROM Dual

Output:

NEXT_SUNDAY
17-FEB-2019

Explanation: It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated.



Similar Reads

Functions in MySQL | Numeric, String and Date Time Functions in MySQL
In MySQL, functions play a crucial role in performing various operations on data, such as calculations, string manipulations, and date handling. These built-in functions simplify complex queries and data transformations, making it easier to manage and analyze data within a database. In this article, we will look at these different categories of MyS
4 min read
How to Write a SQL Query For a Specific Date Range and Date Time?
In SQL, some problems require us to retrieve rows based on their dates and times. For such cases, we use the DATETIME2 datatype present in SQL. For this article, we will be using the Microsoft SQL Server as our database. Note - Here, we will use the WHERE and BETWEEN clauses along with the query to limit our rows to the given time. The pattern of s
2 min read
SQL Date and Time Functions
In SQL, dates are complicated for newbies, since while working with a database, the format of the data in the table must be matched with the input data to insert. In various scenarios instead of date, datetime (time is also involved with date) is used. For storing a date or a date and time value in a database,MySQL offers the following data types:
3 min read
Load .CSV Data into MySQL and Combine Date and Time
Prerequisite - How To Import Timestamp From a CSV File in MySQL? A CSV (comma-separated values) file is a text file with commas separating information. They are most commonly found in spreadsheets and databases and are now primarily used for datasets in data science and machine learning. They assist businesses in exporting large amounts of data to
4 min read
Date manipulating functions in SQL
To manipulate and fetch date values from the table, oracle has inbuilt date functions. Here, we are going to cover Date manipulating functions in SQL. ADD_MONTHS : It will add the total number of months specified in n to the date parameter and Returns date. Syntax : ADD_MONTHS(d, n) Example - Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Ou
2 min read
SQL | Date Functions (Set-1)
SQL Date Functions are essential for managing and manipulating date and time values in SQL databases. They provide tools to perform operations such as calculating date differences, retrieving current dates and times and formatting dates. In this article, We will learn about the various SQL Date Functions with the help of examples and so on. SQL Dat
5 min read
SQL | Date Functions (Set-2)
SQL Date Functions are powerful tools that allow users to manipulate, extract, and format date and time values within SQL databases. In this article, We will learn about What are SQL Date Functions along with various examples and so on. What are SQL Date Functions?SQL Date Functions are built-in functions that help manipulate, extract, and format d
4 min read
Numeric and Date-time data types in SQL Server
MS SQL Server supports a wide range of data types. There are a few more important data types that are included in the article. In this article, we will cover numeric SQL server data types and different date-time data types. Let’s discuss one by one. bit : A bit is the smallest unit of a computer system. A bit can be either 0 or 1. The bit datatype
3 min read
How to Get Current Date and Time in SQL?
There are many built-in functions to get the current date and time in SQL. In this article, we will discuss how to get the current date and time in SQL with examples. SQL Get Current Date and TimeThree in-built SQL functions to fetch current date and time are: SQL GETDATE() FunctionSQL CURRENT_TIMESTAMP() FunctionSQL SYSDATETIME() FunctionSQL GETDA
2 min read
How To Get the Current Date Without Time in T-SQL?
To get the current date in T-SQL use the GETDATE() function. The result of the function is DateTime data type meaning, it contains both the date and the time, e.g. 2022-07-10 10:32:04. However, to get the current date without time in T-SQL use the CAST() function. This function takes any expression or any column name as the first argument. Then you
1 min read
How to Convert Epoch Time to Date in SQL?
To convert Epoch Time to Date in SQL use the DATEADD() function. DATEADD() function in SQL Server is used to add a time or date interval to a specified date and return the modified date. Some features of the SQL DATEADD() function are: This function is used to sum up a time or a date interval to a date specified.This function comes under Date Funct
2 min read
DATE() and DATE_ADD() Function in MariaDB
1. DATE() Function : In MariaDB, the DATE() function is used to return extracts the date value from a date or datetime expression. In this function, the first parameter will be a date or DateTime. This function will return extracts the date value from the expression. If the expression is not date or DateTime then this function will return the NULL
2 min read
How to Specify a Date Format on Creating a Table and Fill it in SQL?
Whenever we work with databases, we find that almost every single table contains a Date column. After all, the date of the data plays an important role while analyzing it. Storing dates in a specific or understandable format is very important. In this article, we are going to learn how we can specify a Date format on SQL Server. Let's create our de
4 min read
Date() and DateAdd() Function in MS Access
In Microsoft Access, two important date-related functions are frequently used such as Date() and DateAdd(). The Date() function is used to return the current system date without the time component, while the DateAdd() function allows users to add or subtract a specified time interval from a given date. In this article, we will learn about Date() an
3 min read
MySQL - Queries on Date Manipulation
In MySQL date is a data type and by default follows the format 'YYYY-MM-DD' but by using date formatting functions we can format date and can get the required format of date in the tables and can even manipulate the date by using different date functions. In this article let us execute some queries on date formatting in detail step-by-step: Creatin
2 min read
SQL - SELECT DATE
In Microsoft SQL Server, SELECT DATE is used to get the data from the table related to the date, the default format of date is 'YYYY-MM-DD'. Syntax: SELECT * FROM table_name WHERE condition1, condition2,..; Now we will execute queries on SELECT DATE on database student in detail step-by-step: Step 1: Creating a database university: CREATE DATABASE
1 min read
SQL Query to Check Given Format of a Date
Here, we are going to see how to find the SQL Query to check whether the date passed to query is the date of the given format or not. In this article, we will be making use of the Microsoft SQL Server as our database. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will e
2 min read
SQL Query to Get a Financial Year Using a Given Date
Here, we are going to Get a Financial Year Using a Given Date in SQL. In this article, we will be making use of the Microsoft SQL Server as our database. For example, finding the Financial year for the give dates in the table. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that
2 min read
SQL Query to Convert Date Range to Per Day Records
In this article, we are going to see how we can convert the date range to per day records, but before that, we need to have a clear idea of where it is going to be helpful for us. Suppose, We have a database where we want to store all the project details records of the students of a particular class. There we can see how long it took a student to c
5 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
Update Date Field in SQL Server
The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we will be making use of the Microsoft SQL Server as o
2 min read
SQL Query to Convert Date to Datetime
In this article, we will look at how to convert Date to Datetime. We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type.Convert() function is used to convert a value of any ty
1 min read
SQL Query to Convert Date Field to UTC
In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. In this article, we will discuss how to convert Date Field to UTC in SQL. For this art
2 min read
How to Retrieve the Records Based on a Date from Oracle Database?
DATE is a SQL-defined data type that is used to store dates in a column, different database management systems store dates in different formats. MySQL uses 3 bytes to store dates. It stores DATE in a format like 'YYYY-MM-DD'. The DATE value ranges from 1000-01-01 to 9999-12-31. Oracle database management system stores DATE in a format like 'MM-DD-Y
2 min read
SQL Query to Delete a Data From a Table Based on Date
Many of the time we have to delete data based on the date. These dates can be some older dates. For this purpose, we can use delete query along with where clause. This approach helps us to delete some old data in our database. In this article, we are going to delete the data of employees based on their birth dates. Step 1: Creating the database Que
2 min read
How to Pull Data From Two Tables SQL Based on Date?
In this article, we will see, How to write SQL queries to pull data from two tables based on date. We can perform the above function by performing the UNION operation on the tables. UNION operation appends the results of two queries and returns the result as a single set. Ways to use the UNION keyword: UNION ALL: Includes duplicates.UNION: Excludes
2 min read
Comparing Timestamp Dates With Date-Only Parameter in SQL
In this article, we are going to learn a SQL query to compare timestamp dates with date-only parameters. To do this, we will first create a table in a database and add timestamp values to it. After that, we use the SELECT command in SQL with a condition(using WHERE command) to get some values from the table. For comparison, will convert DateTime va
2 min read
How To Get Current Date in Power Query?
Power query is a analysis tool in excel.From 2016 version onwards it was inbuilted in the Excel . Power Query helps us to perform all type of tasks regarding to transformation.  In this article is we will see how to get current date in power query . Getting Current Date in Power QueryTo get the current date in Power Query,we use the function "=Date
2 min read
MySQL DATE Data Type
MySQL DATE Data Type stores date values in the format 'YYYY-MM-DD' and has a valid range of values from '1000-01-01' to '9999-12-31'. DATE Data Type in MySQLThe Data data type in MySQL is used to store date values in a column. During later data analysis, it is necessary to perform date-time operations on the data. Dates are displayed in the format
2 min read
SQL Query to Compare Results With Today's Date
To compare query results with today's date, use the CASE() function with the SQL GETDATE() function. SQL GETDATE() function is used to return the present date and time of the database system and the CASE() function can used to compare two dates in SQL. Query to check the current date in SQL: SELECT GETDATE();Output: SQL Compare Results With Today's
1 min read
Article Tags :