Sysdate Oracle to Run Based on Day - sql

This is probably an easy question for most of you but how can I get this mask to run based on just the day?
If anyone knows Crystal Reports syntax, we have this and it works {PO_RECEIPTS.DATE_RECEIVED} = currentdate
However, when converting to Oracle SQL, how can I the standard: TO_CHAR
(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') to become range so we can selected everything during the day, not just what matched the second in which the report was ran which it never will.
So something like Today from 00:00:00 to 23:59:59 ?
Thank you!

If PO_RECEIPTS.DATE_RECEIVED is a date column where all the times are set to midnight then you can do:
WHERE PO_RECEIPTS.DATE_RECEIVED = TRUNC(sysdate)
If the values have other times then you can use a range:
WHERE PO_RECEIPTS.DATE_RECEIVED >= TRUNC(sysdate)
AND PO_RECEIPTS.DATE_RECEIVED < TRUNC(sysdate) + 1
Truncating a date sets the time to midnight, by default, so TRUNC(sysdate) is midnight this morning. For the range you get all records equal to or later than midnight this morning, and less than midnight tomorrow - which is what TRUNC(sysdate) + 1 gives you, using normal Oracle datetime arithmetic.
You don't really want to convert it to a string with TO_CHAR(); you'd either have to convert all the column values to strings too (which is inefficient and prevents an index being used), or let the string be (implicitly) converted back to a date anyway. It's better to compare a column value with the same data type to reduce or avoid confusion.

Related

Best way to handle between in two dates in postgresql on timestamp

i am having date field in my table in the format of yyyy-mm-dd HH:MM:SS wanted to get records between 11-july-2020 inclusive 14-july-2020 but records are missing on 14th. Tries >= && < SYMMETRIC but non of them is working.
currently using select .... from employee where ... and created_on in between ?1 and ?2 . It is excluding record created on 14th.
I think you want:
where col >= '2020-07-11' and col < '2020-7-15'
Or, to express this using timestamps:
where col::timestamp >= '2020-07-11'::timestamp and
col::timestamp < '2020-07-14'::timestamp + interval '1 day'
Note that the higher end is one day later than 2020-07-14, so you can get all times on that day.
You can also use between as:
where col::date between '2020-07-11'::date and '2020-07-14'::date
But I discourage the use of between with date/time data types -- precisely because of the problem that you are having with the time component.
If your field has format yyyy-mm-dd HH:MM:SS it is a timestamp field not a date field. That makes a big difference in the comparison that needs to be done as #Gordon shows. If you compare a timestamp to a date(14-july-2020) the date will be turned into a timestamp with a time of 00:00:00:
select '07/14/2020'::timestamp;
timestamp
---------------------
2020-07-14 00:00:00
That means you will miss the timestamps on the 14th that fall after Midnight of 13/14th.

SQL - how to change the format of a current_timestamp to have 'mm ss' as zeros?

I want to check if a metric is still missing 4 hours later and return a single record if it exists. I wrote a query that checks if there were metrics in the last 4 hours. But I need to check if there is a metric for a certain hour that was expected to load 4 hours before.
-- Returns records that appeared within the last 4 hours
select * from main.basic_metrics
where metric_name = 'common_metric'
and transaction_time > current_timestamp - interval 4 hours
The problem is that transaction_timeis in the following format 2019-10-30T12:00:00.000+0000 where mm ss are always zeros. So when I check it like transaction_time = current_timestamp - interval 4 hours it returns nothing since current_timestamp contains mm ss data.
How should I format timestamp to the format similar to transaction_time - 2019-10-30T12:00:00.000+0000 ?
UPD: There was a typo, mentioned in the comments below. fixed it
That should be very simple: cast the string to timestamp with time zone:
WHERE CAST(transaction_time AS timestamp with time zone)
> current_timestamp - INTERVAL '4 hours'
Try the following:
select * from main.basic_metrics
where metric_name = 'common_metric'
and transaction_time = date_trunc('hour',current_timestamp) - interval 4 hours
This is not necessarily the best query for what you're doing, but it does solve the problem you're having. My guess is that some version of "between" or > and < would solve it, however without knowing exactly how the "transaction time" is populated, I'm could only venture guesses.
The trick in my example is to "truncate" everything after the "hours" off of the current_timestamp using date_trunc()
Note: It helps a lot to realize that timestamps are NOT formatted. Timestamps are a single long integer field that happens to get formatted on your screen so you can make sense of it. Text comparisons are nearly always the wrong way to do things, and datetime aware functions are the preferred method of doing any comparison.

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;

How to transform Oracle DateTime to Date

For instance, I have a datetime like this '2016-04-02 00:00:00' and another like this '2016-04-02 15:10:00'. I don't care about the time-part, I want them to match just by the date-part.
I have tried with date(), to_date, datepart, nothing works.
Do it like this:
where yourField >= the start of your date range
and yourField < the day after the end of your date range
Edit starts here:
While you could use trunc, as suggested by others, bear in mind that filtering on function results tends to be slow.
Truncating the date to day should do the trick. Documentation here:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions201.htm
For example
SELECT TRUNC(SYSDATE, 'DAY') FROM DUAL;
As others have said - there is no separate "date" data type in Oracle. A pure "date" is stored as a date with the time portion set to 00:00:00 (midnight at the beginning of the day), and TRUNC(date) will take any date and truncate the time to 00:00:00, so if you need to compare two dates you can write
where trunc(date_1) = trunc(date_2)
If your tables are very large and you need to do these comparisons often, this is not ideal, because wrapping column values within function calls (like date_1 within a TRUNC) prevents the use of an index you may have on the date_1 column. If you need to compare dates in two columns you may not have much of a choice, but if you compare to a fixed date (or something like SYSDATE) you may be better off with something like
where date_1 >= trunc(sysdate) and date_1 < trunc(sysdate) + 1
Here you are not using trunc on the column value, so if there's an index on the column, Oracle is free to use it - and trunc(sysdate) is computed only once, not for every single row. "+1" by the way means "add one day".
TO_DATE converts a string to a date; if you apply TO_DATE to a value that is already a legitimate date, you will get unexpected results because Oracle will first convert your true date to a string and then back to date again, and since these conversions require a date FORMAT for strings, and the formats Oracle assumes for conversion from date to string and from string to date may not match, .... you get the idea. As far as I know, DATE() (a FUNCTION) and DATEPART do not exist in Oracle; when you use a new language, keep Google close by and use it often.
If you input a date with no time component, for example TO_DATE('04-apr-2016, 'dd-mon-yyyy'), then the implicit time is 00:00:00 so you don't need to apply TRUNC() to it.
Good luck!

Issue with date formatting SQL

SELECT LISTING_EOD.LOCATION, LISTING_EOD.APPTTIME, LISTING_EOD.PERSON_ID,
LISTING_EOD.FORENAME, LISTING_EOD.SURNAME, LISTING_EODS.STATUS,
LISTING_EOD.DBDATE
FROM DBNAME.LISTING_EOD LISTING_EOD;
This query returns a list of data processed today, I need to modify to check yesterday's data. I have tried add the below line of code, but it doesn't return anything. Does anyone know how I can achieve this?
where LISTING_EOD.DBDATE = '18-OCT-2012';
If you always want yesterday's data, rather than hard-coding the date you can use:
WHERE LISTING_EOD.DBDATE >= TRUNC(SYSDATE) - 1
AND LISTING_EOD.DBDATE < TRUNC(SYSDATE)
TRUNC(SYSDATE) gives you midnight this morning, so if run today it would give a range between 18-Oct-2010 00:00:00 and 18-Oct-2012 23:59:59.
It's generally not a good idea to use implicit date format masks; your original code assumes your NLS_DATE_FORMAT is set to DD-MON-YYYY, but that might not be correct now (if you're seeing the time in the existing select then it probably isn't), and may well not be in the future. Always use an explicit date format mask, like TO_DATE('18-OCT-2012', 'DD-MON-YYY'), to avoid ambiguity and unexpected behaviour.
If the field is actually VARCHAR2 rather than a DATE - which is bad - then you'll need to convert the date range to a string to get a match:
WHERE LISTING_EOD.DBDATE >= TO_CHAR(TRUNC(SYSDATE) - INTERVAL '1' DAY, 'DD-MON-YYYY HH24:MI:SS')
AND LISTING_EOD.DBDATE <= TO_CHAR(TRUNC(SYSDATE) - INTERVAL '1' SECOND, 'DD-MON-YYYY HH24:MI:SS')
That will work for a single day, just, but you'd have problems looking for a date range. It's much better and safer to store data in a column of the appropriate type.
Dates in Oracle by default contain time as well. If you just specify '18-OCT-2012', it will only match 18-OCT-2012 00:00:00'. One way to get around this is to format your database date to what you are comparing it to, e.g. to_char(LISTING_EOD.DBDATE, 'DD-MON-YYYY') and compare this to '18-OCT-2012'. This comparison will disregard time completely.
If you had a date variable to compare with instead of a string, format this using the same date mask used for the database date. This also gets around any assumptions abut default date format on the database in question.
I realised the 'table' I was querying was a view, examined it inside sqldeveloper, and added '-1' to the sysdate. This query then returned the previous days results.
I successfully retrieved the correct data, thanks for all help received.