Skip to content
Advertisement

SQL – How to print calculated datetime result

If a.modified_datetime is '2021/10/01 13:00:00' and b.modified_datetime is '2021/10/01 12:30:00‘, the result of this query would be:

However, I run this query via sqlplus, it returns

What’s wrong with this query, or need to set some options to sqlplus?

Advertisement

Answer

it is stored in a date column

As @a_horse_with_no_name pointed out in a comment, calling to_date() on a value that is already a date is incorrect, and is causing your apparent problem.

When you do:

you are implicitly converting the date to a string using the current session NLS settings; with the still-default DD-MON-RR for example, that is really doing:

As both values end up as midnight, the difference between them is calculated as zero minutes.

You could change the NLS settings, which is fragile; or explicitly convert the the date to a string in the right format – but neither is necessary or useful.

You should not have the to_date() calls at all, and can just subtract the date values directly from each other:

or using ANSI joins:

db<>fiddle showing the results of the implicit conversions, and the correct output.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement