Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server DAY Function: How to Extract Day from Date

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The SQL Server DAY function returns the day of the month as an integer from 1 to 31 for a given date. You call it as DAY(date_expression), and it is a shorthand for DATEPART(day, date_expression). Nothing needs to be installed beyond SQL Server itself and a client such as SQL Server Management Studio (SSMS) or Azure Data Studio to run queries. This guide walks through syntax, practical examples, common pitfalls, and troubleshooting so you can use DAY confidently in SELECT lists, WHERE clauses, and reports.

What You'll Need

  • Access to a SQL Server instance (any recent version) and permission to run SELECT queries.
  • A client tool: SQL Server Management Studio (SSMS), Azure Data Studio, or the sqlcmd utility. Menu labels and connection dialogs can differ slightly by version and edition.
  • A database with a date, datetime, or string column to test against, or you can use literal values and GETDATE() as shown below.

Step-by-Step

  1. Connect to your database. Open SSMS or Azure Data Studio, connect to your SQL Server instance, and open a new query window. If you are using sqlcmd, start a session with sqlcmd -S your_server -d your_database -E (Windows authentication) and press Enter after each statement.
  2. Run the simplest form. Execute SELECT DAY('2024-03-15') AS DayOfMonth;. The result is 15. The string is implicitly converted to a date because it is in an unambiguous format (yyyy-mm-dd).
  3. Use a datetime column. If you have a table with a column such as OrderDate, run SELECT OrderDate, DAY(OrderDate) AS OrderDay FROM Orders;. DAY ignores the time portion and returns only the day number.
  4. Apply it to the current date. SELECT DAY(GETDATE()) AS TodayDay; returns today's day of the month. GETDATE() returns the server's local datetime; if you need UTC, use GETUTCDATE() or SYSUTCDATETIME() and be aware of the time zone difference.
  5. Filter rows by day. To find all orders placed on the 15th of any month, use SELECT * FROM Orders WHERE DAY(OrderDate) = 15;. This works but can prevent index usage; see the Tips section for a sargable alternative.
  6. Handle NULLs. If the input is NULL, DAY returns NULL. Test with SELECT DAY(NULL) AS Result; and you will get NULL. Use ISNULL(DAY(OrderDate), 0) or a CASE expression if you need a default value in reports.
  7. Combine with other date parts. DAY is one of three shorthand functions: YEAR(date), MONTH(date), and DAY(date). To build a full date breakdown, run SELECT YEAR(OrderDate) AS Y, MONTH(OrderDate) AS M, DAY(OrderDate) AS D FROM Orders;.
  8. Format the output. DAY returns an integer, so if you need a two-digit day (for example, 05 instead of 5), use FORMAT(OrderDate, 'dd') or RIGHT('0' + CAST(DAY(OrderDate) AS varchar(2)), 2). FORMAT can be slower on large result sets; the string concatenation approach is often faster.
  9. Test edge cases. Run SELECT DAY('2024-02-29'), DAY('2024-12-31'), DAY('2024-01-01'); to confirm leap-day and month-boundary behavior. All return valid integers between 1 and 31.
  10. Save and reuse. Once your query works, save it as a view or stored procedure if you need the day extraction repeatedly. For example: CREATE VIEW OrderDays AS SELECT OrderID, OrderDate, DAY(OrderDate) AS OrderDay FROM Orders;.

Common Mistakes

  • Passing a time-only value. DAY expects a date or datetime. If you pass a time string like '14:30:00', SQL Server may interpret it with the default date (1900-01-01) and return 1, which is rarely what you want. Always pass a full date.
  • Assuming DAY returns a string. It returns an integer. Concatenating it directly to text can cause implicit conversion surprises; cast explicitly with CAST(DAY(OrderDate) AS varchar(2)).
  • Using DAY in WHERE on an indexed column. WHERE DAY(OrderDate) = 15 forces a scan because the function wraps the column. Use a range instead: WHERE OrderDate >= '2024-03-15' AND OrderDate < '2024-03-16'.
  • Confusing DAY with DATENAME. DATENAME(day, OrderDate) returns the same number as a string (for example, '15'), while DAY returns an integer. Use DATENAME when you need a string result.
  • Ignoring language and dateformat settings. Ambiguous strings like '03/04/2024' can be interpreted as March 4 or April 3 depending on session settings. Use ISO format 'yyyy-mm-dd' or pass a date-typed value.
  • Expecting DAY to work on non-date types. Passing an integer or a float may raise an error or produce unexpected results. Convert explicitly with CAST(value AS date) first.

Tips

  • Prefer DAY(column) over DATEPART(day, column) for readability; they are functionally identical.
  • For grouping by day of month across months, combine with MONTH and YEAR: GROUP BY YEAR(OrderDate), MONTH(OrderDate), DAY(OrderDate).
  • Use EOMONTH(date) to get the last day of the month, then compare with DAY to find month-end dates: WHERE DAY(OrderDate) = DAY(EOMONTH(OrderDate)).
  • When filtering by day number, consider a computed column or a persisted column with an index if the query runs often.
  • Test with SET LANGUAGE and SET DATEFORMAT if your application passes date strings from different locales.
  • Remember that DAY returns NULL for NULL input; wrap with ISNULL or COALESCE in reporting queries to avoid blanks.

Troubleshooting

  • Error: “Argument data type … is invalid for argument 1 of day function.” The value you passed cannot be converted to a date. Cast it explicitly: DAY(CAST(YourColumn AS date)), and check for non-date strings in the column.
  • Unexpected result like 1 for a time value. You passed a time-only string. Include the date portion or convert the value to a datetime first.
  • Query is slow after adding DAY in WHERE. The function prevents index seeks. Rewrite the predicate as a date range (see Common Mistakes) or add a computed column for the day number and index it.
  • NULL results in a report. The source column contains NULLs. Use ISNULL(DAY(OrderDate), 0) or filter with WHERE OrderDate IS NOT NULL.
  • Different results on different servers. Check the session language and dateformat settings, and confirm whether the column stores local time or UTC. Standardize on ISO date literals in your queries.
  • DAY works in SELECT but not in a CHECK constraint or computed column. Some contexts require deterministic expressions; DAY is deterministic for date inputs, but implicit conversions from strings may not be. Cast explicitly to a date type.

Frequently Asked Questions

What is the difference between DAY and DATEPART(day, …)?

They return the same integer. DAY is a shorthand for DATEPART(day, date) and is easier to read. Use DATEPART when you need other date parts in the same query style.

Does DAY work on datetime2 and datetimeoffset?

Yes. DAY accepts date, datetime, datetime2, smalldatetime, and datetimeoffset. For datetimeoffset, the day is taken from the stored date and offset; convert to a target time zone first if the day boundary matters.

Can I use DAY to get the day name (Monday, Tuesday)?

No. DAY returns a number. Use DATENAME(weekday, date) for the name, or DATEPART(weekday, date) for the weekday number, which depends on SET DATEFIRST.

Why does DAY('2024-13-01') fail?

Because 13 is not a valid month. SQL Server raises a conversion error. Validate the input or use TRY_CONVERT(date, value) to return NULL instead of an error.

Is DAY safe to use in an indexed view?

DAY itself is deterministic, but indexed views have strict requirements. Test in your environment and cast inputs explicitly to a date type to avoid implicit conversion issues.

How do I get a two-digit day like '05'?

Use FORMAT(date, 'dd') or RIGHT('0' + CAST(DAY(date) AS varchar(2)), 2). FORMAT is simpler but can be slower on large datasets.