Explain Codes LogoExplain Codes Logo

Oracle SQL how to remove time from date

sql
date-manipulation
sql-functions
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 26, 2024
TLDR

Here's the one-liner magic wand to strip time from a date in Oracle SQL using TRUNC:

-- and... bam! Time disapparates. SELECT TRUNC(date_col) FROM table;

Now TRUNC sends the time portion on a trip to 00:00:00, leaving behind a cleansed date_col.

TRUNC: the date-time butcher

Our hero function TRUNC comes to rescue. This Oracle SQL function is a workhorse. When it encounters a date, TRUNC cleanly slices off the time, reducing it to the Cinderella hour - 00:00:00. What's left is a neat date, ready for comparison, aggregation, or simply decluttering your life. Adios, time clutter!

Date masquerading as a VARCHAR2

Sometimes, dates dress up as VARCHAR2 strings. In such impostor situations, a two-step process is required. First, unmask the date using TO_DATE and the correct format mask**. Then apply **TRUNC`:

-- Unmasking the date in disguise SELECT TRUNC(TO_DATE(varchar_date_col, 'YYYY-MM-DD HH24:MI:SS')) FROM table;

Remember, strings posing as dates are controversial in SQL society. Such masquerades can lead to complex date operations and a significant performance hit parade. So avoid them when you can!

Dealing with format landmines

Stepping on an unexpected date format can cause your precious SQL script to blow up. NLS_DATE_FORMAT setting impacts how your TO_CHAR formatted dates look and behave. So before you step on a rake, make sure the field is clear:

-- Cleaning up the field ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD';

What if you still step on a formatting landmine? Enter VALIDATE_CONVERSION(), Oracle 12c's bomb disposal squad. Save yourself from head-banging runtime errors:

-- Bomb disposal squad to the rescue SELECT date_col FROM table WHERE VALIDATE_CONVERSION(date_col AS DATE, 'YYYY-MM-DD') = 1;

Mastering the date manipulation

While working with TRUNC and TO_DATE, train your eyes on your data types. Even a flyweight data type mismatch can pack a heavyweight punch. So keep it tidy, folks. Before you go and share your brilliant work, pass it through the filter of sample data tests. Keep your script tight. Suit it up for your date column requirements and business logic.