The Wayback Machine - https://web.archive.org/web/20240616184818/https://www.geeksforgeeks.org/sql-date-functions/
Open In App

SQL Date and Time Functions

Last Updated : 22 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

DATE format YYYY-MM-DD
DATETIME  format: YYYY-MM-DD HH:MI: SS
TIMESTAMP  format: YYYY-MM-DD HH:MI: SS
YEAR  format YYYY or YY

Now, come to some popular functions in SQL date functions.

NOW()

Returns the current date and time. 

Query:

SELECT NOW();

Output:

now method output image

CURDATE()

 Returns the current date. 

Query:

SELECT CURDATE();

Output: 

OUTPUT2

CURTIME()

 Returns the current time. 

Query:

SELECT CURTIME();

Output: 

OUTPUT3

DATE()

Extracts the date part of a date or date/time expression. Example: For the below table named ‘Test’

Id Name BirthTime
4120 Pratik 1996-09-26 16:44:15.581

Query:

SELECT Name, DATE(BirthTime) 
AS BirthDate FROM Test;

Output:

Name BirthDate
Pratik 1996-09-26

EXTRACT()

Returns a single part of a date/time. 

Syntax

EXTRACT(unit FROM date);

Several units can be considered but only some are used such as MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc. And ‘date’ is a valid date expression. Example: For the below table named ‘Test’

Id Name BirthTime
4120 Pratik 1996-09-26 16:44:15.581

Query:

SELECT Name, Extract(DAY FROM 
BirthTime) AS BirthDay FROM Test;

Output: 

Name Birthday
Pratik 26

Query:

SELECT Name, Extract(YEAR FROM BirthTime)
AS BirthYear FROM Test;

Output: 

Name BirthYear
Pratik 1996

Query:

SELECT Name, Extract(SECOND FROM 
BirthTime) AS BirthSecond FROM Test;

Output:

Name BirthSecond
Pratik 581

DATE_ADD() 

 Adds a specified time interval to a date.

Syntax:

DATE_ADD(date, INTERVAL expr type);

Where,  date – valid date expression, and expr is the number of intervals we want to add. and type can be one of the following: MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc. Example: For the below table named ‘Test’

Id Name BirthTime
4120 Pratik 1996-09-26 16:44:15.581

Query:

SELECT Name, DATE_ADD(BirthTime, INTERVAL 
1 YEAR) AS BirthTimeModified FROM Test;

Output:

Name BirthTimeModified
Pratik 1997-09-26 16:44:15.581

Query:

SELECT Name, DATE_ADD(BirthTime, 
INTERVAL 30 DAY) AS BirthDayModified FROM Test;

Output:

Name BirthDayModified
Pratik 1996-10-26 16:44:15.581

Query:

SELECT Name, DATE_ADD(BirthTime, INTERVAL
4 HOUR) AS BirthHourModified FROM Test;

Output: 

Name BirthSecond
Pratik 1996-10-26 20:44:15.581

DATE_SUB()

 Subtracts a specified time interval from a date. The syntax for DATE_SUB is the same as DATE_ADD just the difference is that DATE_SUB is used to subtract a given interval of date.

DATEDIFF()

 Returns the number of days between two dates. 

Syntax:

DATEDIFF(date1, date2);

date1 & date2- date/time expression

Query:

SELECT DATEDIFF('2017-01-13','2017-01-03') AS DateDiff;

Output: 

DateDiff
10

DATE_FORMAT()

 Displays date/time data in different formats.

Syntax:

DATE_FORMAT(date,format);

the date is a valid date and the format specifies the output format for the date/time. The formats that can be used are:

  • %a-Abbreviated weekday name (Sun-Sat)
  • %b-Abbreviated month name (Jan-Dec)
  • %c-Month, numeric (0-12)
  • %D-Day of month with English suffix (0th, 1st, 2nd, 3rd)
  • %d-Day of the month, numeric (00-31)
  • %e-Day of the month, numeric (0-31)
  • %f-Microseconds (000000-999999)
  • %H-Hour (00-23)
  • %h-Hour (01-12)
  • %I-Hour (01-12)
  • %i-Minutes, numeric (00-59)
  • %j-Day of the year (001-366)
  • %k-Hour (0-23)
  • %l-Hour (1-12)
  • %M-Month name (January-December)
  • %m-Month, numeric (00-12)
  • %p-AM or PM
  • %r-Time, 12-hour (hh:mm: ss followed by AM or PM)
  • %S-Seconds (00-59)
  • %s-Seconds (00-59)
  • %T-Time, 24-hour (hh:mm: ss)
  • %U-Week (00-53) where Sunday is the first day of the week
  • %u-Week (00-53) where Monday is the first day of the week
  • %V-Week (01-53) where Sunday is the first day of the week, used with %X
  • %v-Week (01-53) where Monday is the first day of the week, used with %x
  • %W-Weekday name (Sunday-Saturday)
  • %w-Day of the week (0=Sunday, 6=Saturday)
  • %X-Year for the week where Sunday is the first day of the week, four digits, used with %V
  • %x-Year for the week where Monday is the first day of the week, four digits, used with %v
  • %Y-Year, numeric, four digits
  • %y-Year, numeric, two digits



Previous Article
Next Article

Similar Reads

SQL Functions (Aggregate and Scalar Functions)
SQL Functions are built-in programs that are used to perform different operations on the database. There are two types of functions in SQL: Aggregate FunctionsScalar FunctionsSQL Aggregate FunctionsSQL Aggregate Functions operate on a data group and return a singular output. They are mostly used with the GROUP BY clause to summarize data.  Some com
4 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Python | Working with date and time using Pandas
While working with data, encountering time series data is very usual. Pandas is a very useful tool while working with time series data.  Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Let's try to understand with the examples discussed below. Working with Dates in PandasThe date class i
8 min read
C++ Program to Print Current Day, Date and Time
In order to facilitate finding the current local day, date, and time, C++ has defined several functions in the header file, so functions that will help us in achieving our objective of finding the local day, date, and time are: time(): It is used to find the current calendar time.Its return type is time_t, which is an arithmetic data type capable o
2 min read
Python program to calculate Date, Month and Year from Seconds
Given the number of seconds, the task is to write a Python program to calculate the date, month, and year in the format MM-DD-YYYY that have been passed from 1 January 1947. Examples Input: 0 Output: 01-01-1947 Input: 123456789 Output: 11-29-1950 Input: 9876543210 Output: 12-22-2259Approach to Calculate Date, Month, and Year from SecondsHere is the
4 min read
Java | Date format validation using Regex
We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled. // Java program to check if given date is // valid or not. import java.util.regex.Matcher; import java.util.regex.Pattern; public class GeeksforGeeks { // Returns true if d is in format
1 min read
Queries to find the future closest date
Given an array arr[] consisting of N strings and an array Query[] consisting of Q queries. Each string in arrays arr[] and Query[] is of the form D/M/Y where D, M and Y denotes the date, month and year. For each query, the task is to print the next closest date from the given array arr[]. If no such date exists, print "-1". Examples: Input: arr[]={
12 min read
Python program to count upper and lower case characters without using inbuilt functions
Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case characters : 19 Upper case characters: 3Method 1:
3 min read
Need and Functions of Operating Systems
The fundamental goal of an Operating System is to execute user programs and to make tasks easier. Various application programs along with hardware systems are used to perform this work. Operating System is software that manages and controls the entire set of resources and effectively utilizes every part of a computer. The figure shows how OS acts a
9 min read
std::legendre, std::legendref and std::legendrel functions in C++17
The legendre , legendref and legendrel are built functions in C++ STL that are used to compute the value of unassociated polynomials of degree n and argument x. Value of order-n unassociated Legendre Polynomial of x is given by : [Tex] \[ \ P_{n}(x)= \frac{1}{2^{n}n!}\frac{d^{n}}{dx^{n}}(x^{2}-1)^{n} \] [/Tex] The first few Legendre polynomials are
3 min read
Article Tags :
Practice Tags :