How do you extract only the date portion from a SQL Server DateTime column? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How do you extract only the date portion from a SQL Server DateTime column?

message-square
0

To extract only the date portion from a DATETIME or DATETIME2 column in SQL Server, use CAST(column_name AS DATE) or CONVERT(DATE, column_name). Both return a DATE data type (YYYY-MM-DD) without the time component (00:00:00.000). Use CONVERT(VARCHAR(10), column_name, 23) or FORMAT() only when you specifically need a formatted string output rather than a DATE value.


1. Recommended: CAST(... AS DATE) and CONVERT(DATE, ...)

These approaches return a true DATE data type, which works best for date comparisons, grouping by day, and joining on calendar dates.

SELECT
    order_id,
    created_at,
    CAST(created_at AS DATE) AS order_date_cast,
    CONVERT(DATE, created_at) AS order_date_convert
FROM orders;
  • Input (DATETIME): 2026-11-30 15:12:00.000
  • Output (DATE): 2026-11-30

2. Grouping and Filtering by Date

Group Rows by Calendar Day

SELECT
    CAST(created_at AS DATE) AS order_date,
    COUNT(*) AS total_orders,
    SUM(order_amount) AS daily_revenue
FROM orders
GROUP BY CAST(created_at AS DATE)
ORDER BY order_date DESC;

Filter for a Specific Date (Index-Friendly Range)

Wrapping an indexed column in a conversion function inside a WHERE clause (such as WHERE CAST(created_at AS DATE) = '2026-11-30') can prevent SQL Server from seeking an index on created_at. Use a half-open range filter on large tables instead:

SELECT order_id, created_at, order_amount
FROM orders
WHERE created_at >= '2026-11-30T00:00:00'
  AND created_at <  '2026-12-01T00:00:00';

3. Returning a Formatted String Instead of a DATE Type

If you need a text representation rather than a DATE type:

SELECT
    created_at,
    CONVERT(VARCHAR(10), created_at, 23)  AS iso_date_str,   -- 2026-11-30
    CONVERT(VARCHAR(10), created_at, 101) AS us_date_str     -- 11/30/2026
FROM orders;
  • Avoid FORMAT(created_at, 'yyyy-MM-dd') on large rowsets when CAST or CONVERT does the job, because FORMAT() uses .NET formatting and runs slower.

Quick Summary

  1. Use CAST(col AS DATE) or CONVERT(DATE, col) for date math, sorting, and GROUP BY.
  2. Use CONVERT(VARCHAR(10), col, style) when you need a formatted string.
  3. Use range predicates (>= and <) in WHERE clauses on large tables to keep queries index-friendly.