SQL DATENAME()

The DATENAME function in SQL is used to retrieve a specific part of a date, such as the year, month, day, or weekday. It returns the result as a string. This function is particularly useful when you need to format or extract meaningful date information for reporting and analysis.

In this tutorial, we will explore the DATENAME function, its syntax, and practical examples to demonstrate its usage.


Syntax of SQL DATENAME Function

The basic syntax of the DATENAME function is as follows:

</>
Copy
DATENAME(datepart, date)

Where:

  • datepart: Specifies the part of the date to extract (e.g., year, month, weekday).
  • date: The date value from which the information will be retrieved.

List of Date Parts in SQL DATENAME

Date PartDescriptionExample Output
yearReturns the year2025
monthReturns the full name of the monthFebruary
dayReturns the day of the month12
weekdayReturns the full name of the weekdayTuesday
hourReturns the hour14
minuteReturns the minute30
secondReturns the second45

Step-by-Step Examples Using SQL DATENAME

1. Extracting the Month and Weekday from a Date

Let’s retrieve the month and weekday from a given date:

</>
Copy
SELECT 
    DATENAME(month, '2025-02-12') AS Month_Name,
    DATENAME(weekday, '2025-02-12') AS Weekday_Name;

Explanation:

  • The DATENAME(month, '2025-02-12') function returns February.
  • The DATENAME(weekday, '2025-02-12') function returns Tuesday.

2. Using DATENAME with a Table

Consider a employees table that stores employee details, including their joining date.

</>
Copy
CREATE TABLE employees (
    id INT PRIMARY KEY IDENTITY(1,1),
    name VARCHAR(50),
    joining_date DATE
);

Insert some sample data:

</>
Copy
INSERT INTO employees (name, joining_date)
VALUES 
('Arjun', '2024-06-15'),
('Ram', '2023-11-25'),
('Priya', '2022-09-10');

Now, retrieve the joining month and weekday for each employee:

</>
Copy
SELECT 
    name, 
    joining_date, 
    DATENAME(month, joining_date) AS Joining_Month,
    DATENAME(weekday, joining_date) AS Joining_Weekday
FROM employees;

Explanation:

  • DATENAME(month, joining_date) extracts the month from the joining_date.
  • DATENAME(weekday, joining_date) extracts the weekday from the joining_date.
  • The result shows each employee’s name, joining date, joining month, and joining weekday.

Conclusion

The DATENAME() function in SQL is used for retrieving specific parts of a date as strings. In this tutorial, we covered:

  1. The syntax and supported date parts.
  2. Using DATENAME with static and table-based examples.
  3. How to extract meaningful date information like months and weekdays.