Oracle - Date substraction in where clause - oracle

I'm trying to figure out how to compare the result of a date substraction in a where clause.
Clients subscribed to a service and therefore are linked to a subscription that has an end date. I want to display the list of subscriptions that will come to an end within the next 2 weeks.
I did not designed the databse but noticed that the End_Date column type is a varchar and not a date.. I can't change that.
My problem is the following:
If I try to select the result of the substraction for example with this request:
SELECT(TO_DATE(s.end_date,'YYYY-MM-DD') - TRUNC(SYSDATE)) , s.name
from SUBSCRIPTION s WHERE s.id_acces = 15
This will work and give me the number of days between the end of the subscription and the current date.
BUT now, if I try to include the exact same request in a clause where for comparison:
SELECT s.name
from SUBSCRIPTION S
WHERE (TO_DATE(s.end_date,'YYYY-MM-DD') - TRUNC(SYSDATE)) between 0 and 16
I will get an error: "ORA-01839 : date not valid for month specified".
Any help would be appreciated..

Somewhere in the table you have your date formatted in a different way from YYYY-MM-DD. In your first query you check a certain row (or a set of rows, s.id_acces = 15), which is probably ok, but in the second you scan through all the table.
Try finding these rows with something like,
select end_date from subscription
where not regexp_like(end_date, '[0-9]{4}-[0-9]{2}-[0-9]{2}')

Check your DD value (ie: day of the month). This value must be between 1 and the number of days in the month.
January - 1 to 31
February - 1 to 28 (1 to 29, if a leap year)
March - 1 to 31
April - 1 to 30
May - 1 to 31
June - 1 to 30
July - 1 to 31
August - 1 to 31
September - 1 to 30
October - 1 to 31
November - 1 to 30
December - 1 to 31

" the End_Date column type is a varchar and not a date.. I can't
change that."
If you can't change the date you'll have to chang3 the data. You can identify the rogue values with this function:
create or replace check_date_format (p_str in varchar2) return varchar2
is
d date;
begin
d := to_date(p_str,'YYYY-MM-DD');
return 'VALID';
exception
when others then
return 'INVALID';
end;
You can use this function in a query:
select sid, end_date
from SUBSCRIPTION
where check_date_format(end_date) != 'VALID';
Your choices are:
fix the data so all the dates are in the same format
fix the data and apply a check constraint to enforce future validity
write a bespoke MY_TO_DATE() function which takes a string and applies lots of different date format masks to it in the hope of getting a successful conversion.

Related

I need to filter an Oracle SQL query on persons who turned age 21 during the calendar year of 2019

I need to filter an Oracle SQL query on persons who turned age 13 during the calendar year of 2019 - in other words, persons who had their 13th birthday sometime in 2019. Anyone know the code for that? Thanks in advance.
Assuming your table has a date_of_birth column this would work (2006 being 2019-13):
select *
from your_table
where to_number(extract(year from date_of_birth)) = 2006;
I notice your question title has a different year value from its body, so perhaps we need to hand over the troublesome maths to SQL:
select *
from your_table
where date '2019-01-01' = trunc(date_of_birth, 'yyyy') + interval '21' year
/
Truncating the DOB with a format mask converts all the dates to the first of January for that year. We then add an interval of 21 years. Comparing that value to the first of January 2019 will give you everybody who turned 21 last year.
I would use between clause with date_of_birth + 21 year to let oracle use index on date_of_birth, if any as following:
select *
from your_table
where date_of_birth + interval '21' year between date '2019-01-01' and date '2019-12-31';
Cheers!!

select unique trunc(sysdate-370 + level, 'IW') AS datetime from dual connect by level <= 360 order by datetime

Can someone explain me what does the below oracle query do and what is it's output?
select unique trunc(sysdate-370 + level, 'IW') AS datetime from dual
connect by level <= 360 order by datetime;
select sysdate-370 + level AS datetime
from dual
connect by level <= 360;
Will generate 360 rows starting with the current date/time minus 370 days plus one day per row. So rows between 369 and 10 days before the current date/time.
TRUNC( datetime, 'IW' ) will truncate the date to the start of the ISO week (midnight on Monday of that week - irrespective of the NLS settings for date language and/or territory that affect some other options for truncating dates). So you will end up with duplicate rows for each generated row that is in the same week.
The UNIQUE keyword will get rid of those duplicate rows.
The order by datetime will order the results in ascending date order - however, the rows are generated in ascending order so this clause is unnecessary.
So the output will be 52 or 53 rows (depending on what the current day of the week is) starting with Monday midnight of each week containing the date 369 days before the current day up until the week containing 10 days before the current date.
The output (when run on 13th September 2017) is 52 rows (I skipped a few):
05-SEP-2016
12-SEP-2016
19-SEP-2016
26-SEP-2016
03-OCT-2016
...
31-JUL-2017
07-AUG-2017
14-AUG-2017
21-AUG-2017
28-AUG-2017
According to documentation trunc(dateval, 'IW') truncates to:
Same day of the week as the first day of the calendar week as defined by the ISO 8601 standard, which is Monday
connect by level <= N is a trick for producing a set of N rows with level values from 1 to N.

Oracle DB: calculate age from strings

I need to calculate age for the people and their birthdates are saved in varchar2 like 19900130, and some people don't have their birthdates recorded and default value is 00000000.
Here is my code:
SELECT
e.id_number,
e.birth_dt,
(CASE WHEN SUBSTR(e.birth_dt, 1, 4) = '0000' THEN 0
WHEN SUBSTR(e.birth_dt, 1, 4) <> '0000' THEN
ROUND(MONTHS_BETWEEN(SYSDATE, TO_DATE(e.birth_dt, 'YYYYMMDD')) / 12)
ELSE -1
END) age
FROM employee e
The error is:
ORA-01843: Not a valid month
Is anything wrong? I couldn't figure out.
Is anything wrong? Yes, your case is not covering the possibility that some strings have something other than 01, 02, ..., 12 in character positions 5 and 6. Likewise, your case is not covering the possibility that the day of the month character positions are something other than 01, 02, ... 31 (and the covering of the possibility that a day of the month is not valid for a particular month).
If I were you, I'd add a proper date column, modify the app to populate both columns, fix the app so that it stops putting bad data into the table, decide what to do with the bad data, modify the app to stop populating the varchar2 column, and then drop the varchar2 column.

MONTHS_BETWEEN Function

Can someone help me understand the working of Oracle Months_Between Function?
If I query select MONTHS_BETWEEN('02-28-2015', '01-28-2015')
I get an integer value of 1 but if I query
select MONTHS_BETWEEN('02-28-2015', '01-29-2015') I get 0.96.
Refer to the documentation. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions089.htm
Note - the "31 day month" convention may cause weird results around month-ends. Consider:
select months_between(date '2016-07-02', date '2016-07-01') as one_day,
months_between(date '2016-07-01', date '2016-06-30') as another_day
from dual;
ONE_DAY ANOTHER_DAY
---------- -----------
.032258065 .064516129
1 row selected.
As if June had 31 days. It doesn't, but months_between treats it as though it did.
If you're working with just trying to determine the number of months in a set of months and don't care about the days. I find myself in this situation often... You can do a bit of date manipulation which is rather reliable for determining the number of months in a set of months. Say for instance Jul - Sep while starting with dates.
Thusly:
WITH MONTHS AS (
SELECT
SYSDATE DATE_ONE
, SYSDATE+57 DATE_TWO
FROM DUAL
)
SELECT
m.*
,TO_CHAR(m.DATE_ONE,'MON') START_MONTH
,TO_CHAR(m.DATE_TWO,'MON') END_MONTH
,MONTHS_BETWEEN(m.DATE_TWO,m.DATE_ONE) UNEXPECTED_RESULT
,MONTHS_BETWEEN(LAST_DAY(m.DATE_TWO),LAST_DAY(ADD_MONTHS(m.DATE_ONE,-1))) EXPECTED_RESULT
FROM MONTHS m
;

Select Month in Oracle Query

I tried the below query in oracle
select cast(TO_DATE (cal.MONTH,'MM') AS varchar2(30)) as result
FROM JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999)
it gives result in dd-mon-yy format. Now I want only mon from the result, how can I achieve this without using to_char()?
If you're avoiding Oracle functions and the month number is stored on its own as a varchar2 field, then you could brute-force it:
select case cast(month as number)
when 1 then 'Jan'
when 2 then 'Feb'
when 3 then 'Mar'
when 4 then 'Apr'
when 5 then 'May'
when 6 then 'Jun'
when 7 then 'Jul'
when 8 then 'Aug'
when 9 then 'Sep'
when 10 then 'Oct'
when 11 then 'Nov'
when 12 then 'Dec'
end as mon
from ods_calendar_weeks cal
where cal.year not in (0, 9999);
But you're having to specify the language; you don't get Oracle's conversion of the month to the NLS date language. Which might be a bonus or a problem depending on your context.
I'd be tempted to put the conversions into a look-up table instead and join to that; or to add the month name as a separate column on the table, as a virtual column in 11g.
You can try somthing like this:-
SELECT EXTRACT(MONTH FROM CAST(TO_DATE (cal.MONTH,'MM') AS varchar2(30))) as RESULT
FROM JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999)
Hope this will help you.
select to_char(cal.Month,'month')
) AS result
FROM JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999);
This will gives month. the to_char() is a function which has two arguments 1. Column name ans 2. Month. Column name is of date data type so we have to convert the date into character data type and we required only the month so the second column will describes what will be extracted from the date. Finally the result is displayed as a character datatype. This query will returns the months name if year neither 0 nor 9999.

Resources