trunc / sysdate... funny syntax need explanation - sql

I believe this outputs the date of Sunday of the current week but I don't know why.
Can someone please break down what's going on here.
SELECT trunc(sysdate+1,'DAY') FROM DUAL;

The TRUNC function will return the starting day of the week when the second parameter is DAY. Today Sysdate returns Thursday, +1 returns Friday etc. So when you add 3 it gives you next Sunday which marks the start of a new week.

Run this to understand what trunc does
SELECT to_char(trunc(sysdate+1, 'DAY'),'dd/mon/yyyy hh:mi:ss') FROM DUAL;
DAY does returns starting day of the week but trunc will also cut off the hours, minutes, seconds of that date. Sysdate will have some hours and minutes, but after trunc it is defaulted to 00.00.00.000
By calling this
trunc(sysdate+1,'DAY')
you may see 16-FEB-14. You can't see the real result because Oracle doesn't display the minutes for you. If you call this
SELECT to_char(sysdate+1,'dd/mon/yyyy hh:mi:ss') FROM DUAL;
you will see all the time details. Trunk takes that off.
In other words, you have 3 effects here - sysdate + 1 - next date, Day - first day of the week, Trunc - hours, minutes, seconds, etc. off

see http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions230.htm
'DAY' truncates the date provided to the starting day of the week.
Note that depending on your locale this can also be Monday instead of Sunday.
sysdate + 1 just adds one day to the current date, this is probably done to make sure if you are sunday you get back the current sunday and not the previous one.

select to_char(sysdate+1,'dd-mon-yy hh24:mi:ss') from dual;----22-feb-14 02:10:03
select to_char(trunc(sysdate+1,'year'),'dd-mon-yy hh24:mi:ss') from dual;-----01-jan-14 00:00:00
select to_char(trunc(sysdate+1,'month'),'dd-mon-yy hh24:mi:ss') from dual; ---01-feb-14 00:00:00
select to_char(trunc(sysdate+1,'day'),'dd-mon-yy hh24:mi:ss') from dual; ---16-feb-14 00:00:00
Compare above queries outputs, hope this will help you.

Related

Identify the day and get the previous date in Oracle SQL

I have below query which gives current date. I want to return the value as String for this reason i used TO_CHAR.
select NVL(TO_CHAR(sysdate,'DD.MM.YYYY'),0) from dual
But i need to identify Day and based on this it should return the previous Date.
For example when the query runs on every Monday it should return the date from last Friday. When the query runs from Tuesday till Friday it should return the date from previous day.
For example when the query runs today it should return the date from last Friday i.e 18.02.2022. When the query runs tommorow it should return the date from Today 21.02.2022.
I want to avoid dates from every Saturday and Sunday. Can we do this in one query ?
If you want to do it so that the query will work in any language and/or territory then you can compare the date to the start of the ISO week:
SELECT TO_CHAR(SYSDATE, 'DD.MM.YYYY') AS today,
CASE TRUNC(SYSDATE) - TRUNC(SYSDATE, 'IW')
WHEN 0 THEN TO_CHAR(SYSDATE - 3, 'DD.MM.YYYY') -- Monday
WHEN 6 THEN TO_CHAR(SYSDATE - 2, 'DD.MM.YYYY') -- Sunday
ELSE TO_CHAR(SYSDATE - 1, 'DD.MM.YYYY') -- Any other day
END AS previous_weekday
FROM DUAL;
db<>fiddle here
As a slight variation on MTO's answer, just to perhaps make it clearer to a future maintainer, you could use day names or abbreviations instead - but would need to specify the date language (which maybe assumes the hypothetical future maintainer uses, or at least understands, that language):
select to_char(sysdate
- case to_char(sysdate, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH')
when 'MON' then 3
when 'SUN' then 2
else 1
end, 'DD.MM.YYYY') as result
from dual
RESULT
----------
18.02.2022
db<>fiddle, including what you see for a range of 14 days, not just today.

What does TO_DATE('235959', 'HH24MISS') mean?

I came across a SQL query with below conditional clause
To_Char(CRTE_TMS, 'YYYYmmddHH24MISS') between To_Char (TO_DATE(:endDtTime,'YYYYmmddHH24MISS')-TO_DATE('235959', 'HH24MISS')) and :endDtTime
My high level understanding is that create time stamp should be between some time before end time and end time.
Not sure what does TO_DATE('235959', 'HH24MISS') mean.
If I run the below query on 5th Feb it returns 1st Feb
SELECT TO_DATE('235959', 'HH24MISS') FROM DUAl
Please help me understand what exactly this condition mean.
TO_DATE('235959', 'HH24MISS') creates a DATE value. Note, in Oracle data type DATE always contains date and time part.
If you don't provide any date value then Oracle defaults it to the first day of current months, so TO_DATE('235959', 'HH24MISS') returns "2018-02-01 23:59:59"
I don't think this condition makes sense:
To_Char(CRTE_TMS, 'YYYYmmddHH24MISS')
between To_Char (TO_DATE(:endDtTime,'YYYYmmddHH24MISS')-TO_DATE('235959', 'HH24MISS'))
and :endDtTime
First, you should compare DATE values, not strings.
I assume TO_DATE(:endDtTime,'YYYYmmddHH24MISS')-TO_DATE('235959', 'HH24MISS')) is wrong. I think you mean TO_DATE(:endDtTime,'YYYYmmddHH24MISS') - 1 + (1/24/60/60)
This will subtract 1 day plus 1 Second (1/24/60/60), i.e. subtract 23:59:59.
Another possibility would be TO_DATE(:endDtTime,'YYYYmmddHH24MISS') - INTERVAL '23:59:59' HOUR TO SECOND.
So, your condition could be
WHERE CRTE_TMS between TO_DATE(:endDtTime,'YYYYmmddHH24MISS') - 1 + (1/24/60/60) AND :endDtTime
This could probably be a comment instead of an answer.. Sorry do not have enough reputation.
HH24 is the 24 hour format of the hours.
235959 is 23 hours 59 minutes 59 second.
In a 12 hour format it means 11:59:59 PM.
The thing you are trying to do is converting date format into character and comparing it with other dates by converting them to character format using To_char. I do not suggest that.
The below would give the first of the month
SELECT TO_DATE('235959', 'HH24MISS') FROM DUAl;
I am not able to understand what you are trying to achieve here.
The below syntax gives in the character format which is the difference between two dates. for example 4 days and 10 hours.
To_Char (TO_DATE(:endDtTime,'YYYYmmddHH24MISS')-TO_DATE('235959', 'HH24MISS'))
and then you are trying to do a comparision like date between (4 days and 10 hours) and :endtime. This is incorrect.
You could use the below to convert to date format.
to_date('01012018 23:59:59','MMDDYYYY HH24:MI:SS')
select case when to_date('01012018 23:59:59','MMDDYYYY HH24:MI:SS') between :begindate and :enddate then 1
else null
from dual;

Last date with time of the month

Need your help to conclude the query to fetch last date time of the sysdate month.
select to_char(last_day(sysdate),'DD-Mon-YYYY HH24:MI:SS') from dual
it gives last date as expected, but I need time as 23:59:00 which is not possible thru above query.
You could use TRUNC on next day i.e. SYSDATE + 1, and then subtract 60 seconds i.e. 60/86400 to get the desired output.
SQL> SELECT to_char((trunc(last_day(sysdate)) +1) - 60/86400,'DD-Mon-YYYY HH24:MI:SS') dt
2 FROM dual;
DT
--------------------
29-Feb-2016 23:59:00
SQL>
You could also use interval '1' minute or interval '60' second instead of 60/86400.
If you just want it for display for some reason you can hard-code the time into the format mask:
select to_char(last_day(sysdate), 'DD-Mon-YYYY "23:59:00"') from dual;
But you probably really want it as a date object, in which case you can add 23 hours and 59 minutes to the truncated (midnight) date, wchi is 1439 of the 1440 minutes in a day:
select to_char(trunc(last_day(sysdate)) + 1439/1440, 'DD-Mon-YYYY HH24:MI:SS')
from dual;
Or you can go to the next day and remove a minute, either with fractional days or with intervals:
select to_char(trunc(last_day(sysdate)) + interval '1' day - interval '1' minute,
'DD-Mon-YYYY HH24:MI:SS') from dual;
Generally if you're working with time periods you want to include up to 23:59:59, which you can also do with any of those methods, but as Damien_The_Unbeliever said in a comment, it's easier to compare against the start of the next period (e.g. < add_months(trunc(sysdate, 'MM'), 1). It's easy to accidentally miss part of a day by not taking the time into account properly, particularly if you actually have a timestamp rather than a date.

DB2 to Oracle Conversion For Basic Date Time Column Between Clause

What this is doing is selecting all columns from TABLE where a specific date time column is between last Sunday and this coming Saturday, 7 days total (no matter what day of the week you are running the query on)
I would like to have help converting the below statement into Oracle since I found out that it will not work on Oracle.
SELECT *
FROM TABLE
WHERE DATE_TIME_COLUMN
BETWEEN
current date - ((dayofweek(current date))-1) DAYS
AND
current date + (7-(dayofweek(current date))) DAYS
After poking around a bit more I was able to find something that worked for my specific problem with no administrator restrictions for whatever reason:
SELECT *
FROM TABLE
WHERE DATE_TIME_COLUMN
BETWEEN
TIMESTAMPADD(SQL_TSI_DAY, DayOfWeek(Current_Date)*(-1) + 1, Current_Date)
AND
TIMESTAMPADD(SQL_TSI_DAY, 7 - DayOfWeek(Current_Date), Current_Date)
Use TRUNC() to truncate to the start of the week:
SELECT *
FROM TABLE
WHERE DATE_TIME_COLUMN
BETWEEN trunc(sysdate, 'WW')
and
trunc(sysdate + 7, 'WW');
sysdate is the current system date, trunc truncates a data, and WW tells it to truncate to the week (rather than day, year, etc.).
Assuming DATE_TIME_COLUMN is - as it should be - of datatype date, I think this gets what you want.
where DATE_TIME_COLUMN between
next_day(sysdate,'SUNDAY')-7 and next_day(sysdate,'SATURDAY')
You may need to tweak it a bit. Please follow up studying the official docs on the NEXT_DAY function in the relevant docs at http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions106.htm#SQLRF00672
The proposed TRUNC does not guarantee you get the date of a particular day of the week:
SQL> alter session set nls_date_format='day dd-mon-yyyy';
Session altered.
SQL> select trunc(sysdate,'WW') from dual;
TRUNC(SYSDATE,'WW')
---------------------
friday 22-jan-2016
SQL> select trunc(sysdate+7,'WW') from dual;
TRUNC(SYSDATE+7,'WW')
---------------------
friday 29-jan-2016

In oracle SQL, how would you obtain the timestamp representing the start of the week?

I'm using an Oracle 9i database and want to obtain, within a function, the timestamp representing the start of the week, i.e. The most recent monday, at 00:00:00.
I am aware that the timestamp representing the start of the current day is TO_TIMESTAMP(SYSDATE).
You can use the function next_day to get that:
SQL> select next_day(sysdate-7, 'MONDAY') FROM DUAL;
NEXT_DAY
---------
29-APR-13
Getting the start of the week should work with trunc (see docs).
So,
select to_timestamp(trunc(sysdate, 'D')) from dual
should work.
However, depending on your NLS settings, the first day of the week for oracle may well be Sunday.
this appears to return Monday before the day of week in question at midnight. to prove out just play around with sysdate and subtract days...
select case when to_Char(sysdate,'d') = 1 then
trunc(sysdate-6)
else
trunc(sysdate - (to_Char(sysdate,'d')-2))
END
from dual;
You can truncate a date to Monday with:
select trunc(sysdate, 'IW') FROM DUAL;