SQL Oracle table blank when trying to query date data stored as varchar - sql

I have a column called received_dt_key in Varchar in the format DD-MM-YYYY (e.g. 30-07-2021).
I would like to select all from the table for dates between 31-12-2021 and 01-01-2022. I have tried version of the below query and a blank table is the output.
SELECT *
FROM SD_BDAY
WHERE to_char(to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY')) > to_char(to_date('31-12-2021', 'DD-MM-YYYY'))
and to_char(to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY')) < to_char(to_date('01-01-2022', 'DD-MM-YYYY'));

Don't compare dates as strings. Compare them as dates:
SELECT *
FROM SD_BDAY
WHERE to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY') > to_date('31-12-2021', 'DD-MM-YYYY')
and to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY') < to_date('01-01-2022', 'DD-MM-YYYY');
If you try to compare them as strings then you are looking for string that is greater than '31-12-2021' and less than '01-01-2022' and the string comparison will look at the first character and see if it can find a match which is greater than '3' and less than '0'; there can never be such a match so it is quite correct that when comparing as strings nothing is returned.
As pointed out by #AlexPoole in comments, even if you compare the values as dates (rather than strings) you will still never return a result as finding values that are greater than DATE '2021-12-31' and less than DATE '2022-01-01' would return all dates from 2021-12-31 00:00:01 to 2021-12-31 23:59:59; however, your values will always be converted with a midnight time component and, therefore, will never fall into that range so cannot be returned.
What you probably want is to use >= rather than > and then it would match values on 2021-12-31.

The best thing would be to store calendar dates in date data type column. Why else do you think Oracle designed that data type? This way you may create normal indexes on data data type columns, or, if needed, partition the table by that date column.
Still, if you insist in having the calendar dates stored like that, I think the below should work:
SELECT *
FROM SD_BDAY
WHERE to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY') >
to_date('31-12-2021', 'DD-MM-YYYY')
and to_date(RECEIVED_DT_KEY, 'DD-MM-YYYY') <
to_date('01-01-2022', 'DD-MM-YYYY');
Thus you compare calandar dates with calendar dates, not varchar with varchar, as it results from the code you have written.
And what if in the varchar2 column there is somethibng that can't be converted to date? That is why it is best to use the date data type.

Related

Comparing two dates in Oracle after using TO_DATE function

I have the following Oracle Query that is converting todays date and the date field from the table into the same format. However, when trying to compare the two they aren't coming up as equal.
CAST(dstamp As Date), TO_DATE(CURRENT_DATE,'dd-MON-YY HH24.MI.SS','NLS_DATE_LANGUAGE = American')
The cast is used on the field in my table, both these return.
However, when adding the following where statement no rows are returned. I can't work out why these wouldn't be classed as equal?
WHERE CAST(dstamp As Date) = TO_DATE(CURRENT_DATE,'dd-MON-YY HH24.MI.SS','NLS_DATE_LANGUAGE = American');
Any help appreciated.
If you are trying to check if dstamp belongs to the current day, I would suggest:
where dstamp >= trunc(sysdate) and dstamp < trunc(sysdate) + 1
Athough a bit more verbose, this will be more efficient than applying a date function on the column being compared. Using a function on a column in a predicate makes the query non-SARGable, ie it cannot take advantage of an existing index.
The date is ALREADY a date. You don't need to convert it. You may need to remove the time component. Does this do what you want?
WHERE TRUNC(dstamp) = TRUNC(sysdate)

Comparing text type date and select the greater than dates

I have a table with column(last_update_date) of data type is text.So I need to pass a date and select the greater than dates from the table.
I tried with below query,
select batch_uuid,result
from #this
where extract_status = 'success'
and last_update_date > '02/21/2019'
But above query is not working.
Any advice please.
You would need to convert both strings to dates to compare them:
select batch_uuid,result
from mytable
where
extract_status = 'success'
and to_date(last_update_date, 'mm/dd/yyyy') > to_date('02/21/2019', 'mm/dd/yyyy')
Note:
#this is not a valid table, I changed it to mytable
do consider storing dates in a date-like datatype; using a string datatype will bite you in many ways (to start with, using a function like to_date() defeats an existing index on the column)

Date difference = 0 in where clause Oracle?

I have the same problem as this. The only difference is that I use Oracle. I want to select the rows which has insertion_date='20.11.2018'. So my query was
select * from table where insertion_date='20.11.2018'
In that question they suggested datediff, so I looked at its equivalent in oracle and I learned that I can do date arithmetic. So I tried somethings like these:
select * from table where insertion_date -'20.11.2018'=0;
It gave ora-00932 inconsistent datatypes expected date got number.
So, then I tried;
select * from table where insertion_date - to_date('20.11.2018', 'dd.MM.YYYY') = 0;
It does not give error but also does not display the results which I know there must be. What am I doing wrong here? Thanks.
Update: Sorry I forgot to mention that insertion_date is type date. But it also has time(hour, minutes, seconds) info in it.
What is INSERTION_DATE's datatype?
If it is DATE, then comparing it to another date (note: this is date literal; value you used is a string!)
select * from table where insertion_date = date '2018-11-20'
might work, unless INSERTION_DATE contains time component (hours and minutes). Then, the simplest option is to truncate its value (so that you get date itself, at midnight):
select * from table where trunc(insertion_date) = date '2018-11-20'
but it'll ruin index you have on that column (unless it is a function-based one). For small tables, it won't make any difference. For large amount of data, it would so convert it to
select * from table where insertion_date >= date '2018-11-20'
and insertion_date < date '2018-11-21'
If, on the other hand, INSERTION_DATE is a string (VARCHAR2 or CHAR) datatype (which is a really bad idea; consider switching to DATE datatype), then you have to know its format, convert it to DATE first and then compare to another date. For example, if it was a string that contains date values in format dd.mm.yyyy, then
select * from table where to_date(insertion_date, 'dd.mm.yyyy') = date '2018-11-20'
This will certainly fail if any string in that column doesn't match such a format or contains invalid values (such as "date" 53.67.Bx48).

Oracle SQL - convert a varchar2 into a date

I have a problem with converting a varchar2 fields into a date format.
I got 2 columns with the datatyp varchar2, one is called qtime the other is called ztime. Both fields contain strings in this format (f.e. 152015 -> would be a timestamp 15:20:15).
For reporting reasons I need to convert this fields into a date format, afterwards I want to substract (qtime-ztime) the fields an convert them into the format [hh] (f.e. after the operation 01:20:00 would be -> 01). Is it possible to to this within Oracle SQL 12c? The biggest problem for me right now is that I don't get those Strings converted into a date format.
select TO_DATE(qtime,'MM/DD/YYYY hh24:mi:ss') just gives me
ORA-01861:"literal does not match format string"
select TO_DATE(qtime,'hh24mmss') gives me a wrong Date
01.03.2018
select TO_TIMESTAMP(qtime,'hh24mmss') gives me a wrong Date
01.03.2018 BUT the correct time with f.e. 15:20:15,0000000
Thank you in advance, any help is appreciated
Note: I only have reading rights on the database Oracle 12c, so I need to to this within Statements
"The Database contains another column with the correct date for each time"
The missing piece of the puzzle! Concatenate the two columns to get something which can be converted to an Oracle DATE:
select to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
Once you have done that you can perform arithmetic of the dates e.g.
select id
, zdatetime - qdatetime as time_diff
from ( select id
, to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
)
If you want the number of hours in the difference you can include this expression in the projection of the outer query:
, extract( hour from (zdatetime - qdatetime) day to second) as hrs_ela
First off, if you are trying to convert a varchar2 into a date without specifying neither day nor month, it will default to the first day of the current month:
If you specify a date value without a date, then the default date is the first day of the current month.
You can read up more here
Also in 2nd and 3rd your example, you are using 'hh24mmss' for specifying hour, minute and second components, but do note that correct format for minutes is 'mi' and not 'mm', which is used for months.
So the solution is to concatenate both date and time component when creating the date as the other answer suggested, tho I would recommend using a single date field as it can store the information you need.

Difference in dates in Oracle

I am writing the following query
SELECT
TO_CHAR(TO_DATE(data_elaborazione, 'YYYYMMDD') -
TO_DATE(DATA_INS_AGG_SDS, 'YYYYMMDD') )AS DateDiff
FROM
dual
I want to calculate the difference between the two dates, in days, but I get an error:
ORA-00904: "DATA_INS_AGG_SDS": invalid identifier
The same goes for data_elaborazione too. Data_elaborazione, DATA_INS_AGG_SDS are both varchar types that contain dates as varchar
The error you are getting is cause by you referencing columns on dual that do not exist. You'll need to select these columns from the tables they actually exist in. As for your date arithmetic, it should return a number, which does not require TO_CHAR to display, unless you have some specific formatting concerns. Here is an example of date arithmetic. The second date value has a time component. So, the two columns due the date arithmetic and display the result, the second essentially rounds down to just get the number of days to an even integer value.
Please read the comments about data types. You should always work with values in their correct data types. Avoid storing either dates or numbers as strings in the DB.
-- start test_data
with some_data(begin_date, end_date) as
(select to_date('02/15/2017','MM/DD/YYYY'), to_date('04/03/2017 09:34:12','MM/DD/YYYY HH24:MI:SS') from dual)
-- end test data
select end_date - begin_date as num_days_diff_w_time,
FLOOR(end_date - begin_date) as num_days_diff_wo_time
from some_data;