Oracle Date - How to add years to date - oracle

I have a date field
DATE = 10/10/2010
sum = 4 (this are number of years by calculation)
is there a way to add four years to 10/10/2010 and make it
10/10/2014?

Try adding months (12 * number of years) instead. Like this-
add_months(date'2010-10-10', 48)

Use add_months
Example:
SELECT add_months( to_date('10-OCT-2010'), 48 ) FROM DUAL;
Warning
add_months, returns the last day of the resulting month if you input the last day of a month to begin with.
So add_months(to_date('28-feb-2011'),12) will return 29-feb-2012 as a result.

I believe you could use the ADD_MONTHS() function. 4 years is 48 months, so:
add_months(DATE,48)
Here is some information on using the function:
http://www.techonthenet.com/oracle/functions/add_months.php
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1157035034361

You can try this:
someDate + interval '4' year
INTERVAL

I am not sure, if I understood Your question correctly, but
select add_months(someDate, numberOfYears * 12) from dual
might do the trick

One more option apart from ADD_MONTHS
SELECT
SYSDATE,
SYSDATE
+ TO_YMINTERVAL ( '1-0' )
FROM
DUAL;
SYSDATE SYSDATE+TO_YMINTERVAL('1-0')
--------- ----------------------------
29-OCT-13 29-OCT-14
1 row selected.
SELECT
SYSDATE,
SYSDATE
+ TO_YMINTERVAL ( '2-0' )
FROM
DUAL;
SYSDATE SYSDATE+TO_YMINTERVAL('2-0')
--------- ----------------------------
29-OCT-13 29-OCT-15
1 row selected.
SELECT
TO_DATE ( '29-FEB-2004',
'DD-MON-YYYY' )
+ TO_YMINTERVAL ( '1-0' )
FROM
DUAL
*
Error at line 4
ORA-01839: date not valid for month specified
But the last one is illegal since there is no 29th day of February in 2005, hence it fails on leap year cases (Feb 29)
Read the documentation for the same

SELECT TO_CHAR(SYSDATE,'YYYY')-2 ANO FROM DUAL

Related

Stored procedure to get one year of data splitted per months

I am relatively new to Oracle so i'd really appreciate some help.
I have a query like:
SELECT * FROM reservations WHERE date between (date1) and (date2).
What I need is to get all the reservations within the interval : today's date and today's date -1 year, so basically 1 year of history.
I want to run the above query with interval of 1 months, and export the query set to excel.
I need some help in the logic of the loop (create a stored procedure or function), as i will think later for the export to excel.
This will give all records from 1 year back to today:
SELECT * FROM reservations
WHERE date >= trunc( sysdate ) - interval '1' year
AND date < trunc( sysdate ) + interval '1' day
I want to run the above query with interval of 1 months,
I understand that you want to run this query 12 times, each time for another monthly period. If yes, then run this query 12 times changing the parameter X (within SELECT 1 As X FROM dual subquery), beginning from 12 to 1 (or 1 to 12):
SELECT * FROM reservations
CROSS JOIN (
SELECT 1 As X FROM dual
) x
WHERE date >= trunc( sysdate ) - x * interval '1' month
AND date < trunc( sysdate ) + interval '1' day - ( x - 1 ) * interval '1' month
Here is the procedure to create the queries month-wise starting from sysdate .
create or replace procedure monthwise_query
as
t_date DATE := TRUNC(SYSDATE) ;
c_date DATE ;
BEGIN
FOR i in 1..12
LOOP
c_date := t_date;
dbms_output.put_line('select * from reservations where rev_date between to_date('''||c_date||''',''DD-MON-YY'') and (select add_months(to_date('''||c_date||''',''DD-MON-YY''),-1) from dual);');
select add_months(c_date,-1)
into t_date
from dual;
END LOOP;
END;
- It can be extended with UTIL_FILE utility inside this procedure to write each query result to single/multiple files.
- SPOOL from SQL*plus for each query will be easy
- UNIX script to loop through each monthwise-query to load to file also possible

Return records from todays month + 6

how can i return records sales from todays + 6 months.
Example:
Today´s month: May-2018.
Today´s month + 6: Nov-2018
So, i want a function to retrieve records from Table_Date, from November (1 to 30).
Thanks.
Use the TRUNC and ADD_MONTHS functions:
SELECT *
FROM sales
WHERE SalesDate >= ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 6 )
AND SalesDate < ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 7 );
You have SQL server and oracle, it cant be both.
This is for SQL Server (though logic would work in ORACLE, but syntax may not)
This is to get 6 months from today
SELECT DATEADD(MM, 6, GETDATE())
Added extra code here for more details after looking at question more:
I am using variables to do the calculations to make it easier to understand but you could do it all inline (but harder to read).
This script gets a date 6 months from now, takes that month and finds the first day of that month, and then the last day of that month so you can use those 2 dates in a where clause logic.
DECLARE #NewMonth AS VARCHAR(10)
DECLARE #NewYear AS VARCHAR(10) -- in case adding months goes to next year
SELECT #NewMonth = DATEPART(MONTH, DATEADD(MM, 6, GETDATE())),
#NewYear = DATEPART(YEAR, DATEADD(MM, 6, GETDATE()))
DECLARE #FirstOfMonth AS DATE = #NewMonth + '/1/' + #NewYear
-- for start of month check we can just hard code one in it, for end of month we cant because we dont know how many days are in it
SELECT #FirstOfMonth, DATEADD(DAY, -1, DATEADD(MONTH, 1, #FirstOfMonth)) AS LastDayOfMontbh

Get date of the previous day in Oracle

I need to bring the day immediately preceding date in Oracle using a truncate but not how. He was using the following line but bring me some records for the current day of execution and should not be. Neceisto only the previous day; investigation found the truncate with dates in Oracle but not how to use it.
and fnxs.FECHA_INGRESO BETWEEN (TO_CHAR (SYSDATE-1, 'DD-MON-YY')) AND (TO_CHAR (SYSDATE, 'DD-MON-YY'));
I appreciate your help
Using BETWEEN with dates in Oracle is generally a bad idea. I see it all the time, and most of the time people get it wrong (like in the accepted answer above). Even when they fully understand that the two dates are included, they still make logical errors because they forget about timestamps.
The OP is asking for yesterday dates. The following sql shows that today falls within "BETWEEN TRUNC( SYSDATE ) - 1 AND TRUNC( SYSDATE )"
with adate as (
select trunc(sysdate) today from dual
) select today from adate where today between trunc(sysdate) -1
and trunc(sysdate);
16-Apr-15 00:00:00
[returns the record for today]
I find it easier to be correct with dates when you're more explicit about the end points:
SELECT * from your_table
WHERE fnxs.FECHA_INGRESO >= TRUMC(SYSDATE) - 1
AND fnxs.FECHA_INGRESO < TRUNC(SYSDATE);
Upon looking closer, the OP's date-like column might be a VARCHAR2 (could still be a date that was implicitly cast in the comparison he gave). If it is a VARCHAR, then it needs to be converted first (using an appropriate format string):
SELECT * FROM your_table
WHERE TO_DATE(fnxs.FECHA_INGRESO, 'DD-MON-YY') >= TRUMC(SYSDATE) - 1
AND TO_DATE(fnxs.FECHA_INGRESO, 'DD-MON-YY') < TRUNC(SYSDATE);
Assuming your column is of type DATE
SELECT *
FROM TABLE_NAME
WHERE FECHA_INGRESO BETWEEN TRUNC( SYSDATE ) - 1
AND TRUNC( SYSDATE );
If it is a character string then:
SELECT *
FROM TABLE_NAME
WHERE TO_DATE( FECHA_INGRESO, 'DD-MON-YY' )
BETWEEN TRUNC( SYSDATE ) - 1
AND TRUNC( SYSDATE );

Getting the previous occurrence and next occurrence in oracle

Hi I am working on oracle DB. The DB has one column date. It consists of the dates of 5 years with the dates model will be refreshed. Ex
DATE_TABLE
DATE
------------
1-jan-2013
15-jan-2013
31-jan-2013
6-feb-2013
etc.........
now for today's date suppose 13th jan 2013. The next refresh date will be 15th jan. and previous refresh date is 1st jan. to retrieve these two dates. Can i have any way without using PL/SQL. using regular select queries?. Thanks in advance
There are two functions LAG() (allows you to reference previous record) and LEAD() allows you to reference next record. Here is an example:
SQL> with t1(col) as(
2 select '1-jan-2013' from dual union all
3 select '15-jan-2013' from dual union all
4 select '31-jan-2013' from dual union all
5 select '6-feb-2013' from dual
6 )
7 select col as current_value
8 , lag(col, 1) over(order by col) as prev_value
9 , lead(col, 1) over(order by col)as next_value
10 from t1
11 ;
Result:
CURRENT_VALUE PREV_VALUE NEXT_VALUE
------------- ----------- -----------
1-jan-2013 NULL 15-jan-2013
15-jan-2013 1-jan-2013 31-jan-2013
31-jan-2013 15-jan-2013 6-feb-2013
6-feb-2013 31-jan-2013 NULL
We can simply use the below query, plain and simple. No need of pl/sql
SELECT MIN(DATE) FROM DATE_TABLE WHERE DATE > SYSDATE ;

Get First Day Of Week From Week Number

In Oracle, is there a straightforward way to get the first day of the week given a week number?
For example, today's date is 12/4/2012. If I run:
select to_char(sysdate,'WW') from dual;
It returns 49 for the week number.
What I would like to do is somehow return 12/2/2012 for the first day...given week 49 (assuming Sunday as first day of the week).
Any ideas? Thanks in advance for any help!
try this:
select next_day(max(d), 'sun') requested_sun
from (select to_date('01-01-2012', 'dd-mm-yyyy') + (rownum-1) d from dual connect by level <= 366)
where to_char(d, 'ww') = 49-1;
just set your year to_date('01-01-2012' and week number-1 49-1 as applicable.
the sunday in the 49th week of 2008?
SQL> select next_day(max(d), 'sun') requested_sun
2 from (select to_date('01-01-2008', 'dd-mm-yyyy') + (rownum-1) d from dual connect by level <= 366)
3 where to_char(d, 'ww') = 49-1;
REQUESTED
---------
07-DEC-08
and 2012
SQL> select next_day(max(d), 'sun') requested_sun
2 from (select to_date('01-01-2012', 'dd-mm-yyyy') + (rownum-1) d from dual connect by level <= 366)
3 where to_char(d, 'ww') = 49-1;
REQUESTED
---------
02-DEC-12
Try this,
select
next_day(trunc(to_date(in_year,'yyyy'),'yyyy') -1,'Mon') + (7 * (in_week - 1))
from dual;
If you have the date, not just the week number, you can try this:
Get the day number of the week of your date with: to_char(theDate, 'D')
substract that number from your date plus 1, and you'll get the Sunday of that week.
Add 7 and you'll get the date of end of the week(Saturday).
Like this:
SELECT theDate - to_char(theDate, 'D') + 1 as BeginOfWeek,
theDate,
theDate - to_char(theDate, 'D') + 7 as EndOfWeek
FROM TableName
I can't comment on questions yet, so I'll add another one. But this is based on #Dazzals answer.
His solution doesn't work for week one and for ISO-weeks. Also it doesn't work, if the first day of the week is not sunday, which can be controlled by NLS_SETTINGS.
This one does:
SELECT MIN(D)
FROM (SELECT TO_DATE('01-01-2013', 'dd-mm-yyyy') + (ROWNUM-10) D, ROWNUM R
FROM DUAL
CONNECT BY LEVEL <= 376)
WHERE TO_CHAR(D,'IYYYIW') = '201301'
Because we are spanning more than one year, we need to check the year too.
Using the trunc function #Justin used, I think this is what you want:
select trunc(to_date('2012-01-01', 'YYYY-MM-DD') + (49 - 1) * 7, 'WW') from dual;
I ended up doing this:
function getFirstDayOfWeek(y in binary_integer, w in binary_integer) return date
is
td date;
begin
td:=TO_DATE(TO_CHAR(y)||'0101', 'YYYYMMDD');
for c in 0..52
loop
if TO_NUMBER(TO_CHAR(td, 'IW'))=w then
return TRUNC(td, 'IW');
end if;
td:=td+7;
end loop;
return null;
end;

Resources