SQL - Date - Functions
SQL - Date - Functions
DATE
FUNCTIONS
*****************************************************************************************
***********
Date and Time functions are used to handle Date and Time data.
1. GETDATE(): It is used to get current date and time
2. YEAR(<date>): It is used to get four digits of the year
3. MONTH(<date>): It is used to get month in the form of numbers from 1 to 12
4. DAY(<date>) : It is used to get day nmber from 1 to 31
5. DATEADD(<interval>, <Number>, <date>): It is used to add/subtract interval to a date
and return date
interval
---------
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear, dy, y = Day of the year
day, dd, d = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
--7. DATEPART(<interval>, <date>): It is used to get part of the date in the form numbers
--Write a SQL code to get year from the current date
SELECT
YEAR(GETDATE()) AS CurrentYear1,
DATEPART(YEAR, GETDATE()) AS CurrentYear2
--Write a SQL Statement to get current year, current month and current day
SELECT
YEAR(GETDATE()) AS CurrentYear1,
DATEPART(YEAR, GETDATE()) AS CurrentYear2,
MONTH(GETDATE()) AS CurrentMonth1,
DATEPART(MONTH, GETDATE()) AS CurrentMonth2,
DAY(GETDATE()) AS CurrentDay1,
DATEPART(DAY, GETDATE()) AS CurrentDay2,
DATEPART(WEEK, GETDATE()) AS CurrentWeek
--8. DATENAME(<interval>, <date>): It is used to get part of the date in the form text
--Write a SQL Statement to get current year, current month and current day, Current day
name
SELECT
DATENAME(YEAR, GETDATE()) AS CurrentYear,
DATENAME(MONTH, GETDATE()) AS CurrentMonth,
DATENAME(DAY, GETDATE()) AS CurrentDay,
DATENAME(WEEKDAY, GETDATE()) AS WeekdayName
--
SELECT * FROM employee
--Write a SQL statement to get year, quarter, month, weeknumber from Hiredate
SELECT
YEAR(Hiredate) AS Year,
DATEPART(QUARTER, Hiredate) AS Quarter,
DATENAME(MONTH, Hiredate) AS Month,
DATEPART(WEEK, Hiredate) AS WeekNbr
FROM employee
--Write a SQL statent to dispay employeeno, ename, hiredate and short month name (Jan,
Feb...)
SELECT
EmployeeNo,
Ename,
Hiredate,
LEFT(DATENAME(MONTH, Hiredate),3) AS ShortMonth
FROM employee
--Write a SQL Statement to get How many number of days are completed by every employee
SELECT
EmployeeNo,
Ename,
Hiredate,
DATEDIFF(DAY, Hiredate, GETDATE()) AS DayCompleted
FROM employee
SELECT
DATEPART(DY, GETDATE()) AS DayOfYear
SELECT
Salary,
Commission,
ISNULL(Commission,0) + Salary AS Gross_Salary1,
COALESCE(Commission,0) + Salary AS Gross_Salary2,
CASE
WHEN Commission IS NULL THEN Salary
ELSE Commission+Salary
END AS Gross_Salary3
FROM employee