Next week in Oracle - oracle

I'm using oracle dbms and I have in Employe table a column Birthdate. I want to write a query that shows the employees who has a birthday next week.
Is this correct ?
select name
from employe
where to_char(birthdate,'DD-MM')=to_char(next_day(sysdate,1)+7,'DD-MM');

That is not the correct usage of next_day(): that function returns the date of the the next instance of a day. For example, to find the date of next Friday:
select next_day(sysdate, 'FRIDAY') from dual;
To find employees whose birthday is seven days from now, you need to just tweak your query a bit:
select name
from employe
where to_char(birthdate,'DD-MM') = to_char(sysdate+7,'DD-MM');

The correct solution would be
SELECT name
FROM employe
WHERE to_char(birthdate
/* "move" the birthdate to the current year
to get a reliable week number */
+ CAST((EXTRACT(year FROM current_date)
- EXTRACT(year FROM birthdate)) || '-0'
AS INTERVAL YEAR TO MONTH),
'IW')
= to_char(current_date + 7, 'IW');
The IW format returns the ISO week containing the date, which is probably what you are looking for. If you start your week on Sunday, add one to both dates.

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!!

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;

Calculate the week ending date in oracle using Saturday as the week end date

Given a field in Oracle that contains dates, how would you calculate what the week ending date is using Sun thru Sat as your week. For example, if the date is 1/26/2015 (which is a Monday), the query should return 1/31/2015 (which is a Saturday. If the date is 1/31/2015, then the query should return 1/31/2015.
Given any particular date / time value, this expression will return midnight of the preceding Sunday.
TRUNC(whatever_time,'DAY')
So, you can do stuff like this:
SELECT TRUNC(whatever_time,'DAY') week_starting,
TRUNC(whatever_time,'DAY') + 6 week_ending,
SUM(sales)
FROM table
GROUP BY TRUNC(whatever_time,'DAY')
and you'll get what you need.
Notice that TRUNC(whatever_time,'DAY') honors the Oracle session initialization parameter called “NLS_TERRITORY”. For example, in Europe Monday is considered the first business day of the week. Try this.
ALTER SESSION SET NLS_TERRITORY=GERMANY;
SELECT TRUNC( DATE '2013-12-31', 'DAY'),
TRUNC( DATE '2014-01-03', 'DAY')
FROM DUAL;
A complete writeup of this is here: http://www.plumislandmedia.net/sql-time-processing/using-sql-report-time-intervals-oracle/

"BETWEEN" SQL Keyword for Oracle Dates -- Getting an error in Oracle

I have dates in this format in my database "01-APR-12" and the column is a DATE type.
My SQL statement looks like this:
SELECT DISTINCT c.customerno, c.lname, c.fname
FROM customer c, sales s
WHERE c.customerno = s.customerno AND s.salestype = 1
AND (s.salesdate BETWEEN '01-APR-12' AND '31-APR-12');
When I try to do it that way, I get this error -- ORA-01839: date not valid for month specified.
Can I even use the BETWEEN keyword with how the date is setup in the database?
If not, is there another way I can get the output of data that is in that date range without having to fix the data in the database?
Thanks!
April has 30 days not 31.
Change
SELECT DISTINCT c.customerno, c.lname, c.fname
FROM customer c, sales s
WHERE c.customerno = s.customerno AND s.salestype = 1
AND (s.salesdate BETWEEN '01-APR-12' AND '31-APR-12');
to
SELECT DISTINCT c.customerno, c.lname, c.fname
FROM customer c, sales s
WHERE c.customerno = s.customerno AND s.salestype = 1
AND (s.salesdate BETWEEN '01-APR-12' AND '30-APR-12');
and you should be good to go.
In case the dates you are checking for range from 1st day of a month to the last day of a month then you may modify the query to avoid the case where you have to explicitly check the LAST day of the month
SELECT DISTINCT c.customerno, c.lname, c.fname
FROM customer c, sales s
WHERE c.customerno = s.customerno
AND s.salestype = 1 AND (s.salesdate BETWEEN '01-APR-12' AND LAST_DAY(TO_DATE('APR-12', 'MON-YY'));
The LAST_DAY function will provide the last day of the month.
The other answers are missing out on something important and will not return the correct results. Dates have date and time components. If your salesdate column is in fact a date that includes time, you will miss out on any sales that happened on April 30 unless they occurred exactly at midnight.
Here's an example:
create table date_temp (temp date);
insert into date_temp values(to_date('01-APR-2014 15:12:00', 'DD-MON-YYYY HH24:MI:SS'));
insert into date_temp values(to_date('30-APR-2014 15:12:00', 'DD-MON-YYYY HH24:MI:SS'));
table DATE_TEMP created.
1 rows inserted.
1 rows inserted.
select * from date_temp where temp between '01-APR-2014' and '30-APR-2014';
Query Result: 01-APR-14
If you want to get all records from April that includes those with time-components in the date fields, you should use the first day of the next month as the second side of the between clause:
select * from date_temp where temp between '01-APR-2014' and '01-MAY-2014';
01-APR-14
30-APR-14

Resources