how to use substr function with to_date in sql? - sql

query is :
select substr(to_date('01-02-2018','mm-dd-yyyy'),4,3) from dual;
output is :
JAN
can anyone explain how the output came ?

When you apply a text function directly to something that's of DATE datatype, you force an implicit conversion of the date into a string. This conversion uses the NLS_DATE_FORMAT parameter to decide the format of the output string.
In effect,
substr(to_date('01-02-2018','mm-dd-yyyy'),4,3)
is the same as
substr(to_char(to_date('01-02-2018','mm-dd-yyyy'), <NLS_DATE_FORMAT>),4,3)
The usual default value (for English-language versions of the database) of the NLS_DATE_FORMAT parameter is DD-MON-RR - which it sounds like the value of your NLS_DATE_FORMAT parameter is set to, which means your query is doing:
substr(to_char(to_date('01-02-2018','mm-dd-yyyy'), 'DD-MON-RR'),4,3)
Therefore, the substr is working on the string 02-JAN-18, and the 3 characters starting from the 4th character is JAN.
Rather than use substr on a date, you would do better to use to_char instead, e.g.:
to_char(to_date('01-02-2018', 'mm-dd-yyyy'), 'MON')

Related

How do you convert YYYY_MM to date in Oracle SQL?

I have a column which has dates as texts. Like: '2021_01' (I will reefer this column as TextDate)
I convert it to '2021-01' with this code:
SELECT REPLACE(at.TextDate,'_','-') as DataFormat FROM tableName at
But when I try to cast it to date, or convert it to date, I always get 'Missing expression' errors. I tried this:
SELECT REPLACE(CONVERT(VARCHAR(7), at.TextDate, 126, '_', '-') as date FROM tableName at
But it will give me errors. Any suggestion?
convert means something completely different in Oracle than it does elsewhere. You need the to_date() function:
SELECT TO_DATE(at.textDate, 'YYYY_MM') as DataFormat FROM tableName at
If you want to display it in a particular format then you can either let your client/application do that - most clients by default will use your session's NLS_DATE_FORMAT setting - or explicitly convert it back to a string with the complementary to_char() function.
db<>fiddle
The valid date elements are also in the documentation. You should only convert to a string for display though; while you are manipulating or storing it you should treat it as a date.
How can I filter last 3 months with it?
You need to use Oracle syntax, not SQL Server or other syntax. You also can't refer to a column alias in the same level of query. SO you can recalculate the date value; or as your string format is relatively sane you can convert the target date to a string and compare that, which might allow an index to be used. Something like:
SELECT TO_DATE(at.textDate, 'YYYY_MM') as DataFormat
FROM tableName at
WHERE at.textDate >= TO_CHAR(ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -3), 'YYYY_MM')
db<>fiddle
TO_DATE with appropriate format mask.
Just to know what's what:
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';
Session altered.
Code:
SQL> select to_date('2021-01', 'yyyy_mm') from dual;
TO_DATE('2021-01','
-------------------
01.01.2021 00:00:00
SQL>

Oracle PL/SQL : to_date() format not considered

When I execute this in PL/SQL Developer :
SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI') FROM dual;
Here's what I get :
3/29/2017 2:05:00 PM
How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.
What you are doing with the to_date method is parsing the string into a date object. If you then want to output the date object as string with a different format you should use the to_char method.
Example:
SELECT to_char(
to_date('29/03/17 14:05','DD/MM/RR HH24:MI'),
'DD/MM/RR HH24:MI'
) FROM dual;
Ok, conceptual excercise coming up
Which of these dates represents the 1st January 2017?
01/01/2017
2017-01-01
01-JAN-2017
That's right, all of them. The date datatype is not a format, it stores the value of the date, not how it appears.
If using Oracle, adjust your NLS_DATE_FORMAT to match your expectation, but again, this is just how the system will display the date, not how it stores it.
(N.B. This answer is more to give more clarity to the other answers but it's too long for a comment.)
Oracle stores DATEs (and TIMESTAMPs etc) in its own specific format. Us humans represent dates in a variety of different formats and we deal with strings. Even us humans can get confused over what a date string represents, given no context - e.g. 03/09/2017 - is that the 3rd of September, 2017 or the 9th of March 2017?
So, when you pass a date into Oracle, you need to convert it into Oracle's date format by passing a string in and telling Oracle what the date format of that string is. This can be done using to_date() or via the DATE literal (which is always in yyyy-mm-dd format).
Conversely, when you want to read something that's stored in Oracle's DATE datatype, you need to tell Oracle how you want it to be displayed, which you can do by using to_char() with the appropriate format mask.
If you fail to explicitly convert the string-to-a-date or date-to-a-string, then Oracle uses the format specified in the NLS_DATE_FORMAT to decide how to do the conversion.
In your case, you didn't specify how you wanted your date to be displayed, so Oracle has to use to_char() along with the format contained in your NLS_DATE_FORMAT in order to display the date as a string, and clearly that's different to the format you passed the date-string in as.

SQL Date Format Conversion

I have a question regarding SQL dates.
The table I am working with has a date field in the following format: "22-SEP-08". The field is a date column.
I am trying to figure out how to output records from 1/1/2000 to present day.
The code below is not filtering the date field:
Select distinct entity.lt_date
from feed.entitytable entity
where entity.lt_date >= '2000-01-01'
Any help regarding this issue is much appreciated. Thanks!
Edit: I am using Oracle SQL Developer to write my code.
DATEs do not have "a format". Any format you see is applied by the application displaying the date value.
You can either change the configuration of SQL Developer to display dates in a different format, or you can use to_char() to format the date the way you want.
The reason your statement does not work, is most probably because of the implicit data type conversion that you are relying on.
'2000-01-01' is a string value, not a date. And the string is converted using the NLS settings of your session. Given the fact that you see dates displayed as DD-MON-YY means that that is the format that is used by the evil implicit data type conversion. You should supply date values always as real date literals.
There are two ways of specifying a real date literal. The first is ANSI SQL and simple uses the keyword DATE in front of an ISO formatted string:
where entity.lt_date >= DATE '2000-01-01'
Note the DATE keyword in front of the string, wich makes it a real date literal not a string expression.
The other option is to use to_date() to convert a character value into a date:
where entity.lt_date >= to_date('2000-01-01', 'yyyy-mm-dd');
More details about specifying date literals can be found in the manual:
Date literals
to_date function
My guess is the data type isn't a Date. Just in case its a char type, try to convert it using the Oracle TO_DATE() function. The Oracle documentation below should help you with parameters.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm
An implicit datatype conversion bites once again.
You're right. The predicate is not doing the comparison you are expecting,
Oracle is performing an implicit datatype conversion, from DATE to VARCHAR, so that it can do a comparison to the string literal.
If lt_date column is DATE datatype, then Oracle is seeing your where clause:
where entity.lt_date >= '2000-01-01'
Oracle is actually seeing it as if it's written like this:
where TO_CHAR(entity.lt_date) >= '2000-01-01'
And that's where the "format" problem comes in. The column itself does not have a "format". Because the second argument to the TO_CHAR function is not supplied, Oracle is using the value of the NLS_DATE_FORMAT parameter (from your session). And that's probably set to DD-MON-YY. Which is why that's the "format" you're seeing when you a run a SELECT statement in SQL*Plus. Because the DATE value is (again) being run through a TO_CHAR function to get a string that can be displayed.
To get the "filtering" you want, don't do a comparison to a string literal. Instead, do the comparison to an expression that has DATE datatype.
You can use the Oracle TO_DATE function. And you don't want to rely on setting of NLS_DATE_FORMAT, explicitly specify the format model as the second argument to the function. For example:
DO THIS
where entity.lt_date >= TO_DATE('2000-01-01','YYYY-MM-DD')
DON'T DO THIS
It's also possible to specify the format model as the second argument to the TO_CHAR function.
where TO_CHAR(entity.lt_date,'YYYY-MM-DD') >= '2001-01-01'
But you don't want to do that because that's going to force Oracle to evaluate that expression on the left side for every flipping row in the table, so it has a string value to do the comparison. (That's true unless someone created a function-based index for you.) If you do the comparison on the bare column, using the TO_DATE on the literal side, Oracle can make effective use of an appropriate index (with lt_date as the leading column) to satisfy the predicate.

Modify an existing to_char date format

Oracle SQL automatically converts my field D.START_DT to the following format:
TO_CHAR(D.START_DT,'YYYY-MM-DD')
Which makes it difficult for me to modify my own date format.
I've tried wrapping another TO_CHAR around it with no luck.
TO_CHAR(TO_CHAR(D.START_DT,'YYYY-MM-DD'), 'MM/DD')
And I've tried SUBSTR to select certain characters, with no luck. I think the hyphen is getting int he way.
SUBSTR(TO_CHAR(D.START_DT,'YYYY-MM-DD'), 6, 7) || '/' || SUBSTR(TO_CHAR(D.START_DT,'YYYY-MM-DD'), 9, 10)
What is the work around for this?
I agree with RMAN Express and see no problems converting dates to any format you need...
In case you still have problems try this (first to_char() in outer query is optional):
SELECT to_char(to_date(some_date, 'YYYY-MM-DD'), 'MM/DD') final_date
FROM
(
SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') some_date -- this is your "auto converted" date
FROM dual
)
/
A DATE datatype has no format. When you see a date printed on a screen, there was something that APPLIED the format you see. Could be a "default" in the program you are using (like SQL Developer) or your NLS setting, etc. But, a DATE datatype has no format. So, you have complete control over the format you see on screen.
The simplest is to use the TO_CHAR function:
select TO_CHAR(D.START_DT,'YYYY') from dual;
returns just the four digit year.
See TO_CHAR date format options.
http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements004.htm#CDEHIFJA
You should always supply the format in your code and not rely on some other "default" to supply it.

Oracle to_date() incorrect output

There must be a very simple answer, but I can't find it anywhere.
I have the following which is a section of my select statement:
case when q.renewal_date is not null then
to_date(q._renewal_date, 'DD/MM/YYYY')
else
to_date(w.END_DATE, 'DD/MM/YYYY')
end END_DATE,
according to all of the docs I can find the MM should give the month in numbers however I'm getting results such as:
30-SEP-12
26-JUN-11
30-SEP-12
It's also interesting that they're hyphenated (-) and not with slashes (/).
So what's the reason for this and how do I achieve what I want?
Assuming w.end_Date and q._renewal_date are actual dates, you want to to_char them, not to_date. At present I would say you are seeing the dates in the format specified by your NLS settings. (If they are not dates, you are converting them to dates, but still letting your NLS settings choose the format you view it in)
As you are TO_DATEing the value it is stored by Oracle internally as a date. It is displayed back to you using your NLS_DATE settings value which i would assume are set to DD-MON-YY by default.
You can check with
SELECT *
FROM v$parameter
WHERE name = 'nls_date_format';
You'll need to either alter your NLS_DATE_FORMAT setting (either for your session or for the DB) or TO_CHAR the output to the format you want to see.
to_date converts a string to a date. The code you have is taking a string (q._renewal_date) in 'DD/MM/YYYY' format and converting it to a date. What you are seeing is the default rendering of the date field.
Depending on what type q._renewal_date is, you probably need to use a different conversion/formatting function.