Adding one month to saved date(oracle) - oracle

I have a table A which contains a Date type attribute. I want to write a query to select the date in another table B with value one month after the value in A.Any one know how to do it in oracle?

uhm... This was the first hit on google:
http://psoug.org/reference/date_func.html
It seems you're looking for the "add_months" function.

You need to use the ADD_MONTHS function in Oracle.
http://www.techonthenet.com/oracle/functions/add_months.php
Additional info: If you want to use this function with today's date you can use ADD_MONTHS(SYSDATE, 1) to get one month from now.

The question is to select a date_field from table b where date_field of table b is one month ahead of a date_field in table a.
An additional requirement must be taken into consideration which is currently unspecified in the question. Are we interested in whole months (days of month not taken into consideration) or do we want to include the days which might disqualify dates that are one month ahead but only by a couple of days (example: a=2011-04-30 and b=2011-05-01, b is 1 month ahead but only by 1 day).
In the first case, we must truncate both dates to their year and month values:
SELECT TRUNC( TO_DATE('2011-04-22','yyyy-mm-dd'), 'mm') as trunc_date
FROM dual;
gives:
trunc_date
----------
2011-04-01
In the second case we don't have to modify the dates.
At least two approaches can be used to solve the initial problem:
First one revolves around adding one month to the date_field in table a and finding a row in table b with a matching date.
SELECT b.date_field
FROM tab_a as a
,tab_b as b
WHERE ADD_MONTHS( TRUNC( a.date_field, 'mm' ), 1) = TRUNC( b.date_field, 'mm' )
;
Note the truncated dates. Leaving this out will require a perfect day to day match between dates.
The second approaches is based on calculating the difference in months between two dates and picking a calculation that gives a 1 month difference.
SELECT b.date_field
FROM tab_a as a
,tab_b as b
WHERE months_between( TRUNC( b.date_field, 'mm') , TRUNC(a.date_field, 'mm') ) = 1
The order of the fields in months_between is important here. In the provided example:
for b.date_field one month ahead of a.date_field the value is 1
for b.date_field one month before a.date_field the value is -1 (negative one)
Reversing the order will also reverse the results.
Hope this answers your question.

Related

Is it possible to use multiple conditions in a check constraint in Oracle?

I want to use (between, and, or) conditions in a check constraint at the same time. For example:
Alter table called_no add constraint called_no_chck
check ("call_time" between '01:00:00 AM' and '12:59:59 AM' or
between '01:00:00 PM' and '12:59:59 PM')
You certainly may use multiple conditions in a single check constraint.
Your attempt fails because you wrote an invalid condition. The same condition would fail if it was in the where clause of a query, or in any other place where you need a condition.
The correct way to check that a date-time is between A and B or between C and D looks like this:
...check (call_time between A and B OR call_time between C and D)
^^^^^^^^^
You understand the shorthand, where you don't repeat the column name (call_time) before the second between. I understand it too. A computer does not - they are not human. OR must appear between two conditions. A condition such as between must be applied to something, and you can't leave that "something" out and expect the computer to understand it's the same "something" you already used in another condition.
There are other mistakes in your condition though. 12:59:59 AM is about one hour after midnight; it's not about one hour after noon, as you seem to believe. Nothing is ever between 1 AM and 12:59:59 AM (of the same day), because 1 AM is after 12:59:59 AM.
It's also not clear what the data type of your column is. If it's date (as it almost surely should be), you can't just compare it to strings (as you have in your condition). And, you can't simply compare a date-time to something that's just time-of-day.
All these mistakes, though, are out of the scope of your question as you asked it (which was: Can you use "compound" conditions in a constraint; the answer, again, is YES).
Do not use a string column.
If you just want a time without a date, use an INTERVAL DAY(0) TO SECOND(0) column.
If you want a date-time column with accuracy down to whole seconds (and no time-zone) then use a DATE column (which always has the components year, month, day, hour, minute and seconds).
With either of those two options, you do not need a CHECK constraint as it will not accept invalid times.
If you want to format the value using the 12-hour clock then you can use a virtual column.
CREATE TABLE table_name (
time INTERVAL DAY(0) TO SECOND(0),
datetime DATE,
formatted_time VARCHAR2(11)
GENERATED ALWAYS AS (TO_CHAR(DATE '1970-01-01' + time, 'HH12:MI:SS AM')),
formatted_datetime VARCHAR2(11)
GENERATED ALWAYS AS (TO_CHAR(datetime, 'HH12:MI:SS AM'))
);
INSERT INTO table_name (time, datetime)
SELECT INTERVAL '00:12:34' HOUR TO SECOND, SYSDATE FROM DUAL UNION ALL
SELECT INTERVAL '12:34:56' HOUR TO SECOND, SYSDATE + 0.5 FROM DUAL;
Then:
SELECT * FROM table_name;
Outputs:
TIME
DATETIME
FORMATTED_TIME
FORMATTED_DATETIME
+0 00:12:34
2021-12-18 15:37:34
12:12:34 AM
03:35:47 PM
+0 12:34:56
2021-12-19 03:37:34
12:34:56 PM
03:35:47 AM
If you are storing it in a string (don't) then, yes, you can use multiple conditions in a single constraint:
CREATE TABLE table_name (
time VARCHAR2(11)
CHECK (
SUBSTR(time, 1, 2) BETWEEN '01' AND '12'
AND SUBSTR(time, 4, 2) BETWEEN '00' AND '59'
AND SUBSTR(time, 7, 2) BETWEEN '00' AND '59'
AND SUBSTR(time, 10, 2) IN ('AM', 'PM')
AND time LIKE '__:__:__ __'
)
);
or multiple constraints:
CREATE TABLE table_name (
time VARCHAR2(11)
CONSTRAINT invalid_hours CHECK (SUBSTR(time, 1, 2) BETWEEN '01' AND '12')
CONSTRAINT invalid_minutes CHECK (SUBSTR(time, 4, 2) BETWEEN '00' AND '59')
CONSTRAINT invalid_seconds CHECK (SUBSTR(time, 7, 2) BETWEEN '00' AND '59')
CONSTRAINT invalid_meridian CHECK (SUBSTR(time, 10, 2) IN ('AM', 'PM'))
CONSTRAINT invalid_format CHECK (time LIKE '__:__:__ __')
);
But its much easier to not implement all those constraints and just use either an INTERVAL or a DATE when you won't be allowed to enter invalid data.
db<>fiddle here

Oracle sql how to get the date of a week

I have the following query that gets the week of a date:
SELECT pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww') semana,
SUM (rta.kms_acumulados) kms,
COUNT
(DISTINCT (CASE
WHEN v.secuencia BETWEEN rta.sec_origen AND rta.sec_destino
THEN v.cod_inc
ELSE '0'
END
)
)
- 1 numincidencias
FROM (SELECT ms.tren, ms.fecha_origen_tren, ms.secuencia, ri.cod_inc
FROM r_incidencias ri, mer_sitra ms
WHERE ri.cod_serv = ms.tren
AND ri.fecha_origen_tren = ms.fecha_origen_tren
AND ri.cod_tipoin IN (SELECT cod_tipo_iincidencia
FROM v_tipos_incidencias
WHERE grupo = '45')
AND ri.punto_desde = ms.cod_estacion) v,
r_trenes_asignar rta,
r_maquinas rm,
planificador.pl_dh_material pdm
WHERE rta.fecha BETWEEN TO_DATE ('21/09/2018', 'dd/mm/yyyy') AND TO_DATE ('21/09/2018',
'dd/mm/yyyy'
)
AND rta.serie >= 4000
AND rta.matricula_ant IS NOT NULL
AND rm.matricula_maq = rta.matricula_ant
AND rm.cod_serie = pdm.id_material
AND rta.grafico BETWEEN pdm.desde AND pdm.hasta
AND v.tren(+) = rta.tren
AND v.fecha_origen_tren(+) = rta.fecha
GROUP BY pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww')
ORDER BY pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww')
For example week 1
I want to display
week 1 : 1 january - 7 january
How can I get this?
Oracle offers the TRUNC(datestamp, format) function to manipulate dates this way. You may use a variety of format strings to get the first day of a quarter, year, or even the top of the hour.
Given a particular datestamp value, Oracle returns midnight on the first day of the present week with this expression:
TRUNC(datestamp,'DY')
You can add days to a datestamp. Therefore this expression gives you midnight on the last day of the week
TRUNC(datestamp,'DY') + 6
A WHERE-clause selector for all rows in the present week might be this.
WHERE datestamp >= TRUNC(SYSDATE,'DY')
AND datestamp < TRUNC(SYSDATE,'DY') + 7
Notice that the end of the range is just before (<) midnight on the first day of the next week. You need that because you may have datestamps after midnight on the last day of the week. (Beware using BETWEEN for datestamp ranges.)
And,
SELECT TO_CHAR(TRUNC(SYSDATE,'DY'),'YYYY-MM-DD'),
TO_CHAR(TRUNC(SYSDATE,'DY')+6,'YYYY-MM-DD')
FROM DUAL;
displays the first and last dates of the present week in ISO-like format.
Date arithmetic is cool. It's worth your trouble to study the date-arithmetic functions in your DBMS at least once a year.

How to add a day with a specific date using add_months function

I am trying to add a day with a specific date using add_months in oracle database.
I wrote this line:
SELECT ADD_MONTHS('01-JAN-2018', MONTHS_BETWEEN('02-JAN-2018', '01-JAN-2018')) FROM DUAL;
this returns:
01-JAN-18
Why doesn't it return 02-JAN-18?? Can I add one day to the date using this function?
Why doesn't it return 02-JAN-18??
According to MONTHS_BETWEEN documentation,
The MONTHS_BETWEEN function calculates the number of months between
two dates. When the two dates have the same day component or are both
the last day of the month, then the return value is a whole number.
Otherwise, the return value includes a fraction that considers the
difference in the days based on a 31-day month
So,
select MONTHS_BETWEEN('02-JAN-2018', '01-JAN-2018') FROM DUAL ;
yields
.0322580645161290322580645161290322580645
ADD_MONTHS returns the date date plus integer months.
So, .0322.. is considered as integer 0 and your query is equivalent to
SELECT ADD_MONTHS('01-JAN-2018', 0) FROM DUAL;
In order to add 1 months, simply take the difference of two dates.
SELECT ADD_MONTHS(DATE '2018-01-01', DATE '2018-01-02' - DATE '2018-01-01') FROM DUAL;
Or better, add an INTERVAL of 1 month
SELECT DATE '2018-01-01' + INTERVAL '1' MONTH FROM DUAL;
To answer your question, add 1 day, simply use
SELECT DATE '2018-01-01' + 1 FROM DUAL;

Oracle SQL To compare 1 or 2 or more dates to be within a given period

I have a scenario where I need to compare 2 or more dates for given period.
I'm able to succeed when comparing 1 date to a period using between function. But challenge is when I have 2 dates to compare in parallel, getting single row sub query error
select A
from ORDER
where Date1 between sysdate and (sysdate-10)
Above query works fine for single date, please help to get a solution when I have Date 1 and Date 2 and need to compare against the same period (sysdate and (sysdate-10)) and I may have more than 2 dates as well.
Thanks
Shankar
Not having a proper description of your tables or the data they contain, it is difficult to know what you want.
Perhaps something like:
SELECT A
FROM ORDER
GROUP BY A
HAVING COUNT( CASE WHEN datecolumn BETWEEN SYSDATE - 10 AND SYSDATE THEN 1 ELSE NULL END ) > 0

oracle insert only time [duplicate]

This question already has answers here:
How to store only time; not date and time?
(5 answers)
Closed 8 years ago.
I would like to insert data to db as time, not date. If I use to_date('2012-08-31 07:39:33', 'YYYY-MM-DD HH24:MI:SS') it adds date too.
If I use to_date('09:34:00', 'HH24:MI:SS') it adds year, month, day as well, from nowhere :|
Later I need to get rows where time is between x and y, not taking in account the year, month or day. How do I do that?
thanks
As an alternative to the date solution Dave shows, you could use an interval data type for the column:
create table t42(id number, t interval day to second);
insert into t42 (id, t) values(123, to_dsinterval('0 07:39:33'));
insert into t42 (id, t) values(456, to_dsinterval('0 09:34:00'));
select id
from t42
where t between to_dsinterval('0 07:00:00') and to_dsinterval('0 07:59:59');
ID
----------
123
Displaying intervals is a little awkward as they don't have format models, but see this question for some ideas if needed. If you only use them for filtering then that may not be an issue at all.
A DATE type always includes the date component.
One option is to continue using DATE and write your code to ignore the date component. In order to make queries on the time efficient, you might want to create a function-based index on something like TO_CHAR( date_field, 'HH24:MI:SS' ) and use that expression in your queries.
Alternatively, you could use a NUMBER field to store the number of seconds since midnight, and write your queries in terms of that.
you can use number column type and insert value as
INSERT INTO table_name (nTime)
VALUES (date - trunc(date));
and then select values
select *
from table_name t
where t.nTime between (10 / 24 + 15 / 24 / 60) and (12 / 24 + 30 / 24 / 60) --between 10:15 and 12:30

Resources