In SQL, DATEPART function is used to extract the specific part from a given date and time such as year, month, day and hour etc.
DATEPART(datepart, date)
• Specify the 'datepart' of the date or time value that you want to extract. i.e. year, month, day etc.
• Specify the 'date or time value' or 'column' from which you want to extract the specified part.
1. Let's assume we have a table named "[Employees]".
2. Let's assume you want to extract 'Year' from the Joining_Date column.
3. Run below SQL statement :
SELECT *, DATEPART(YEAR, Joining_Date) AS Joining_Year FROM [Employees];
4. In above statement, DATEPART function extracts 'Year' from Joining_Date column and returns it as an integer value in a column named 'Joining_Year'.
Using this function in a select statement won't modify the [Employees] table directly, but it will only be reflected in the select statement's output.
The DATEPART function in SQL extracts a specific part of a date or time, such as year, month, day, etc.
DATEPART DW function in SQL extracts the day of the week (Sunday = 1, Monday = 2, etc.) from a date.
To get only the date part in SQL, you can use functions like CAST or CONVERT to strip off the time portion.
To extract MM (month) and YYYY (year) from a date in SQL, you can use functions like MONTH() and YEAR().