Oracle Varchar2 column with multiple date formats - oracle

I have a table (my table ) with a varchar2 column (my_column) , this column inculdes data that may be dates, in almost every known date format. like
dd/mm/yyyy
mm/dd/yyyy
ddMONyyyy
ddmmyyyyy
yymmdd
mm.dd.yy
dd/mm/yyyy hh:24:ss
mm-dd-yyyy
and so many .
Also it could contains a free text data that may be numbers or text.
I need the possible fastest way to retrieve it as a date , and if it's cannot match any date format to retrieve null

Said that this is really a bad and dangerous way to store dates, you could try with something like the following:
select myColumn,
coalesce(
to_date(myColumn default null on conversion error, 'dd/mm/yyyy' ),
to_date(myColumn default null on conversion error, 'yyyy mm dd' ),
... /* all the known formats */
to_date(myColumn default null on conversion error ) /* dangerous */
)
from myTable
Here I would list all the possiblly expected formats, in the right order and trying to avoid the to_date without format mask, which can be really dangerous and give you unexpected results.

The simple answer is: You cannot convert the strings to dates.
You say that possible formats include 'dd/mm/yyyy' and 'mm/dd/yyyy'. So what date would '01/02/2000' be? February 1 or January 2? You cannot know this, so a conversion is impossible.
Having said that, you may want to write a stored procedure where you parse the text yourself and only convert unambiguous strings.
E.g.: Is there a substring containing colons? Then this may be the time part. In the rest of the string: Is there a four-digit number? Then this may be the year. And so on until you are either 100% sure what date/time this is or you cannot unambiguously determine the date (in which case you want to return null).
Example: '13/01/21' looks very much like January 13, 2021. Or do you allow the year 2013 in your table or even 2001 or even 1921 or ...? If you know there can be no year less then, say, 2019 in the table and no year greater than 2021, then the year must be 2021. 13 cannot be the month, so it must be the day, which leaves 01 for the month. If you cannot rule out all other options, then you would have to return null.

Related

How to make a constraint on DATE FORMAT in ORACLE

say my usual Date format is '14-jan-2019' and i want my date to only be accepted as 'YYYY-MM-DD' how do i do that? and can i change jan to an actual number?
In my opinion, the right / correct way to do that is to declare your date column (or variable or whatever it is) as DATE, e.g.
create table test (date_column date);
or
declare
l_date_variable date;
begin
...
Doing so, you'd let the database take care about valid values.
You'd then be able to enter data any way you want, using any valid date format mask, e.g.
to_date('06.01.2020', 'dd.mm.yyyy')
date '2020-01-06'
to_date('2020-06-01', 'yyyy-dd-mm')
etc. - all those values would be valid.
A DATE data type has no format - it is stored internally as 7-bytes representing year (2 bytes) and month, day, hour, minute and second (1 byte each).
'14-JAN-2019' is not a date - it is a text literal.
If you want to store date values then use a DATE data type.
If you want to only accept strings of a specific format as input then in whatever user interface you use to talk to the database then accept only that format. If you are converting strings to DATEs and wanting an exact format then you can use:
TO_DATE( '2019-01-14', 'fxYYYY-MM-DD' )
Note: the fx format model will mean that the exact format is expected and the typical string-to-date conversion rules will not be applied.

Oracle date comparison as string and as date

1) Why is that this doesn't works
select * from table where trunc(field1)=to_date('25-AUG-15','DD-MON-YY');
select * from table where trunc(field1)=to_date('25/Aug/15','DD/MON/YY');
row is returned in above cases.
So, does this mean that no matter what format the date is there in field1, if it is the valid date and matches with 25th August, it will be returned ( it won't care what format specifier we specify at the right side of the query i.e. DD-MON-YY or DD/MON/YY or anything else) ?
2) but comparsion as string exactly works:
select * from table where to_char(field1)=to_char(to_date
('25/AUG/15','DD/MON/YY'), 'DD/MON/YY');
no row is returned as the comparison is performed exactly.
I have field1 as '25-AUG-15' ( although it can be viewed differently doing alter session NLS_DATE_FORMAT...)
field1 is of DATE type
Any help in understanding this is appreciated specifically with respect to point 1
The DATE data type does not have format -- it's simply a number. So, a DATE 25-Aug-2015 is the same as DATE 25/AUG/15, as well as DATE 2015-08-15, because it's the same DATE.
Strings, on the other hand, are collections of characters, so '25-Aug-2015' is obviously different from '25/AUG/15'.
In the first example you are comparing DATE values. In the second example you are comparing strings.
So you have a field of type DATE with value of The 25th of August 2015,
but it could be visualized in different ways, what in fact is named format.
The DATE has format!
The DATE has implicit format defined by Oracle, in your case it is DD-MON-YY, because you see your field as 25-AUG-15.
You can select your data without TO_DATE conversion, just matching this default format like this:
select * from table where trunc(field1)='25-AUG-15';
In fact, it's not recommended, because if someone will change the default format, Oracle will not be able to understand that you are going to tell him a DATE.
So the to_date conversion in this case:
select * from table where
trunc(field1)=to_date('25/AUG/15','DD/MON/YY');
is used to specify that you wanna tell to Oracle a DATE type with value of 25th of August 2015, using a diffrent format, specified as second parameter. (DD/MM/YY in this case).

Confusion using to_date function to confirm date format

select to_date('07/09/14','yyyy-mm-dd') from dual;
is returning 14-SEP-07
I was expecting it to thrown an exception as the date and the format requested are not the same. Secondly we have slashes in the input date and hypen in the format.
Can someone tell me how to confirm if the input value is of the provided format.
to_date is relatively liberal in attempting to convert the input string using the provided format mask. It generally doesn't concern itself with the specific separator character in the string or in the format mask-- your string could use dashes or slashes or, heck, asterixes if you wanted. Of course, that can mean that you get unexpected results. In this case, for example, the date that is created is in the year 7 (i.e. 2007 years ago). That is a valid date in Oracle but it is highly unlikely to be the date you expect unless you're storing data about ancient Rome.
What, exactly, does it mean to you to "confirm if the input value is of the provided format"? Depending on what you are looking for, you may want to use regular expressions.
REGEXP_LIKE can somewhat do this. Note, this is basic, since it would accept values like 2014-0-32. However, those insane values would fail in whatever you do next in your code, such as to_date().
SELECT 'Yes, valid boss.' is_valid FROM DUAL
WHERE regexp_like('07/09/14','^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$');
no rows selected
.
SELECT 'Yes, valid boss.' is_valid FROM DUAL
WHERE regexp_like('2014-07-09','^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$');
IS_VALID
----------------
Yes, valid boss.
.
SELECT 'Yes, valid boss.' is_valid FROM DUAL
WHERE regexp_like('2014-7-9','^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$');
IS_VALID
----------------
Yes, valid boss.
EDIT: and if you're into PL/SQL, you can do a regex match and throw your own exception ...
DECLARE
v_is_valid INTEGER;
BEGIN
SELECT count(*) INTO v_is_valid FROM DUAL
WHERE regexp_like('07/09/14','^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$');
IF v_is_valid = 0 THEN
raise_application_error (-20400, 'Exception: date was given in the wrong format.');
END IF;
END;
/
*
ORA-20400: Exception: date was given in the wrong format.
TO_DATE() only takes a string and convert it to a date/time in respect to the given format your provided. If it can't find the exact format, it will do its best to determine what could it be. Given your 'yyyy-mm-dd' format, Oracle deduces that the 07 is the year, and the 14 is the day.
You have to write your own function to throw an expected exception or the like to handle the issue, if there is any based on your functional requirements.
So when you select the resulting date, the format that is displayed is actually based on your NLS_DATE_FORMAT system parameter, which gives your resulting date.

Convert time stored as hh24miss to hh24:mi:ss

I have a column in my table which will store the time as hh24miss format, i.e it stores as 091315 which is 09 hrs 13 min 15 sec. I need to convert it into HH24:MI:SS AND concatenate it with the date column which is in YYYYMMDD format.
Simply, the following columns Date: 19940601 and Time: 091315 need to be converted to
01-Jan-94 09:13:15.
You should not store dates as strings, and there is no need to store the time in a separate field. Oracle's DATE data type includes times down the to the second. (You'd need TIMESTAMP for fractions of a second).
If you are really stuck with this schema then you need to convert the two strings into a DATE:
to_date(date_column || time_column, 'YYYYMMDDHH24MISS')
You can then display that in whatever format you want; what you showed would be:
to_char(to_date(date_column || time_column, 'YYYYMMDDHH24MISS'),
'DD-Mon-RR HH24:MI:SS')
Although the data you have is June, not January.
SQL Fiddle demo.
But really, please revisit your schema and use the appropriate data type for this, don't store the values as strings. You have no validation and no easy way to check that the values you have stored actually represent valid dates and times.

Oracle - Converting Date value TO_CHAR()

Ok, so I want to convert a date value to properly format my date for comparison, however, will converting my "DATE" data type to char affect indexing when comparing on that field? Can I resolve this by doing to_date(tochar())? Any advice on this would be greatly appreciated Thanks!
EDIT - Sorry for the lack of specifics.... basically I need to eliminate the time stamp from my date, I used the following and it appears to work TO_DATE(TO_CHAR, 'YYYY-MM-DD'),'YYYY-MM-DD'), mind you I don't know if this is good practice or not, but at least (or so I think) now it's comparing a DATE against a DATE, and not a string.
If you are doing a comparison, you should not be converting the date to a string. You should be comparing to another date. Otherwise, Oracle won't be able to use a non function-based index on the date column.
In general, that is, you're much better off coding
WHERE some_indexed_date_column = to_date( :string_bind_variable,
<<format mask>> )
rather than
WHERE to_char( some_indexed_date_column,
<<format mask>> ) = :string_bind_variable
Of course, if your bind variable can be a DATE rather than a VARCHAR2, that's even better because then you don't have to do any data type conversion and the optimizer has a much easier time of estimating cardinalities.
If you are trying to do some manipulation of the date-- for example, if you want to compare the day portion while omitting the time portion of the date-- you may want to use function-based indexes. For example, if you wanted to find all the rows that were created some time today
WHERE trunc( some_date_column ) = date '2011-11-04'
you could either create a function-based index on the date column
CREATE INDEX idx_trunc_dt
ON table_name( trunc( some_date_column ) )
or you could rewrite the query to do something like
WHERE some_date_column >= date '2011-11-04'
AND some_date_column < date '2011-11-05'
You should compare dates as dates, not as strings. If comparing a date to a string, convert the string to a date to compare.
IMO, you should convert your comparison value to the format stored in the database. Otherwise, you will need to create a function based index on the DATE column to take advantage of indexing. So, if you have an input character date of, say, 11/4/2011, you could compare it in a where clause thusly:
SELECT ...
FROM your_table
WHERE the_date_column = TO_DATE('11/4/2011','MM/DD/YYYY');

Resources