DATEPART() Function in SQL

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

The DATEPART in SQL is a function that takes two inputs: a 'part of the date' such as year, month, or day and a 'date', and it returns that specific part of the date. The datepart in SQL is used to filter dates based on a certain attribute. This is mainly used in cases where we have multiple dates stored in our database and we want to filter queries based on a particular month.

introduction to Datepart in SQL

Syntax

The datepart in SQL takes two arguments:

  • datePart: The datePart refers to the part of the date that has to be found.
  • inputDate: The inputDate refers to the date that we are inputting whose part we will display.

Valid inputs for datePart:

datePartabbreviation
yearyy, yyyy
quarterqq, q
monthmm, m
dayofyeardy, y
daydd, d
weekwk, ww
hourhh
minutemi, n
secondss, s
millisecondms
microsecondmcs
nanosecondns

Examples for Datepart in SQL

Example 1: Displaying the day from the given Date

Code:

Output:

Explanation of the example:

In the above example, we have passed the date 2022-04-22 to the datepart function in SQL, and the value of datePart is day. Thus the datepart in SQL outputs 22.

Example 2: Displaying the Month from the given Date

Code:

Output:

Explanation of the example:

In the above example, we have passed the date 2022-04-22 to the datepart function in SQL, and the value of datePart is month. Thus the datepart in SQL outputs 04.

Example 3: Displaying the year from the given Date

Code:

Output:

Explanation of the example:

In the above example, we have passed the date 2022-04-22 to the datepart function in SQL, and the value of datePart is year. Thus the datepart in SQL outputs 2022.

Example 4: Displaying the time from the given Date

Code:

Output:

Explanation of the example:

In the above example, we have passed the date 2022-04-22 to the datepart function in SQL, and the value of datePart is minute. Thus the datepart in SQL outputs 5.

Learn more about Advanced Concepts of SQL

In order to learn more about advanced concepts of SQL visit this link.

Conclusion

  • The datepart in SQL returns a specific part of the date.
  • The datepart in SQL takes two parameters.
  • The datepart in SQL takes a date whose specific part is to be returned.
  • The datepart in SQL also takes the denotation for the part to be returned (i.e. day, month, year, minute, second, hour etc).