How to get DATE from DATETIME Column in SQL?
To extract the date from a DATETIME
, use SQL's CAST
function:
This code transforms 2023-01-01 10:00:00
into 2023-01-01
, removing the time component. It's essential to structure your queries correctly when dealing with other operations like summing values or filtering by specific criteria.
Tackling diverse scenarios
Working with DATETIME
can vary across different SQL platforms. Here are some tailored solutions for popular SQL flavours:
SQL Server
CONVERT
is another method employed in SQL Server:
MySQL and PostgreSQL
In MySQL and PostgreSQL, CAST
functions as outlined in the fast answer.
Oracle
Oracle tends to utilize the TRUNC
function for this:
TimeZone Concerns
Beware of those timezones! They might impact your date values:
You can then cast the adjusted datetime_col
as a date.
Arithmetic on dates
Here’s how to conduct summing operations based on today's date:
This query conveniently rolls up all transactions made today for a specific card number.
Performance considerations
To boost performance, remember to index your datetime_col
, especially if it’s a frequently queried field.
Deep dive: Advanced date extraction techniques
Formatting dates
Different formats? No problem. SQL Server 2012+ introduced the FORMAT
function:
Note that its performance might lag behind CAST
or CONVERT
.
Subqueries and CTEs
Use subqueries or Common Table Expressions (CTEs) for handling more complex scenarios involving filtering and summation:
Was this article helpful?