ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL

For Complete YouTube Video: Click Here

In this class, we will understand the ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL.

We have already discussed the concepts of Difference in Dates.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL

To understand this, we will consider the holiday table as shown below.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 1
ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 1

ADD_MONTHS

Using ADD_MONTHS, we can get the date after months.

ADD_MONTHS(Date value, Months to be added)

The use of ADD_MONTHS in the query is as shown below.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 2
ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 2

GREATEST and LEAST

GREATEST and LEAST Used to find the latest and earliest date from the given dates.

GREATEST(value1, value2)
LEAST(value1, value2)

The use of GREATEST and LEAST in the query is as shown below.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 3
ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 3
ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 4
ADD_MONTHS GREATEST LEAST TO_DATE Functions 4

TO_DATE

TO_DATE is used to convert the string into date format.

To understand this, we will consider the query as shown below.

SELECT LEAST(’19-JAN-04′, ’06-SEP-04′) FROM DUAL;

The LEAST among these dates is ’19-JAN-04′, but the query produces an output of ’06-SEP-04′ as shown below.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 5
ADD_MONTHS GREATEST LEAST TO_DATE Functions 5

This output is because the SQL considers the date as a string.

To convert the string into date format, we have the TO_DATE function.

The use of TO_DATE in the query and the output is as shown below.

ADD_MONTHS GREATEST LEAST TO_DATE Functions in SQL 6
ADD_MONTHS GREATEST LEAST TO_DATE Functions 6