Explain Codes LogoExplain Codes Logo

Add days Oracle SQL

sql
date-manipulation
intervals
precision
Anton ShumikhinbyAnton Shumikhin·Aug 6, 2024
TLDR

For a swift computation, add days to a date in Oracle SQL using the + operator:

-- Like adding sugar to coffee, add 10 to SYSDATE for a sweeter date. SELECT SYSDATE + 10 FROM dual;

Simply swap SYSDATE with your date column and 10 with the number of days you want to add.

Add days with precision

In some cases, you need higher precision and more dynamic control. This is possible with the NUMTODSINTERVAL function:

-- Just like adding precision guided missiles to your SQL artillery. SELECT SYSDATE + NUMTODSINTERVAL(:number_of_days, 'DAY') FROM dual;

Here, replace :number_of_days with your desired value or variable. Stand back and watch the accurate calculations fire away!

Playing with time intervals

Oracle SQL provides the INTERVAL keyword. This gives you the freedom to add not only days, but also different time units:

-- Add 15 minutes and watch the world change (or maybe just the order date). SELECT ORDER_DATE + INTERVAL '15' MINUTE FROM orders;

Think of INTERVAL as your personal time machine, capable of minutely adjusting Oracle's time dimension.

Robust addition with dynamic date calculations

To ensure exactness with user inputs or variable date increments, blending TRUNC with NUMTODSINTERVAL is a smart idea:

-- Precision cut operation without the surgeon's knife. SELECT TRUNC(SYSDATE) + NUMTODSINTERVAL(:days_to_add, 'DAY') FROM dual;

The result? A precise date value with no unexpected hours, minutes, or seconds. Just the date and the exact number of days added.

Version compatibility considerations

While the + operator and INTERVAL are universally supported, it's wise to check your Oracle version compatibility. Certain date manipulation methods may perform differently in older versions.

Adventurous addition of INTERVALS

Far beyond days, the INTERVAL keyword unleashes the ability to add hours, minutes, and seconds:

-- Spicing up the time game by adding hours, minutes, and seconds to your date. SELECT start_date + INTERVAL '5' HOUR FROM your_table; -- Adds 5 hours SELECT start_date + INTERVAL '30' MINUTE FROM your_table; -- Adds 30 minutes SELECT start_date + INTERVAL '10' SECOND FROM your_table; -- Adds 10 seconds

Time travel has never been easier with INTERVAL in your SQL toolkit.