Download presentation
Presentation is loading. Please wait.
1
SQL Dates FdSc in ICT
2
Data and time functions
Usage Purpose HOUR() HOUR(column) Returns the hour value of a stored date MINUTE() MINUTE(column) Returns the minute value of a stored date SECOND() SECOND(column) Returns the second value of a stored date DAYNAME() DAYNAME(column) Returns the name of the day of a stored date DAYOFMONTH() DAYOF MONTH(column) Returns the numerical day value of a stored date MONTHNAME() MONTHNAME(column) Returns the name of the month of a stored date MONTH() MONTH(column) Returns the numerical month value of a stored date YEAR() YEAR(column) Returns the year value of a stored date ADDDATE() ADDDATE(column, INTERVAL x type) Returns the value of x units added to column SUBDATE() SUBDATE(column, INTERVAL x type) Returns the value of x units subtracted from column CURDATE() Returns the current date CURTIME() Returns the current time NOW() Returns the current date and time
3
Obtaining the date and time
SQL Result SELECT curdate( ) SELECT curtime( ) 20:58:08 SELECT now( ) :59:09
4
Selection SQL Result SELECT name from dateexample where month (dateofbirth) = 7 Batman SELECT dayname(dateofbirth) from dateexample where name = "Robin" Wednesday
5
Age (in this example curdate is 2009-02-05)
SELECT YEAR(curdate()) - YEAR(DateOfBirth) - (RIGHT(curdate(),5)<RIGHT(DateOfBirth,5)) AS age from dateexample WHERE name = "Batman“ Analysis: YEAR(curdate()) - YEAR(DateOfBirth) subtracts 1935 from 2009 giving 74 But this is incorrect as Batman will not be 74 until July 24. So RIGHT(Curdate(),5) evaluates to (the first 5 characters from the right side of the current date) and RIGHT(DateOfBirth,5) evaluates to 07-24 02-05 is less than which evaluates to TRUE or 1 So the expression simplifies to 2009 – 1935 – 1 = 73
6
Age (in this example curdate is 2009-02-05)
SQL Result SELECT name, YEAR(curdate()) - YEAR(DateOfBirth) - (RIGHT(curdate(),5)<RIGHT(DateOfBirth,5)) AS age from dateexample
7
Alias (in this example curdate is 2009-02-05)
An alias can be used to make headings and queries more succinct SQL Result SELECT name, YEAR(curdate()) - YEAR(DateOfBirth) - (RIGHT(curdate(),5)<RIGHT(DateOfBirth,5)) AS age from dateexample (RIGHT(curdate(),5)<RIGHT(DateOfBirth,5)) from dateexample
8
Date calculations SQL Result SELECT curdate() 2009-02-06
WRONG! SELECT adddate(curdate(), interval 2 day) SELECT adddate(curdate(), interval 2 month) SELECT subdate(curdate(), interval 2 month)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.