oracle date sequence? - sql

I have an oracle db and I need a table containing all the dates spanning 2 years;
for example from 01/01/2011 to 01/01/2013.
First I thought of a sequence but apparently the only supported type is number, so now I am looking for an efficient way to do this
cheers hoax

If what you want is to populate a block of records with sequential dates, that is easy enough to do. The following query generates ten dates. All you need to do is adjust the seed date to give you your starting point and the level in the connect by clause to fit your end point, and then plug it into an insert statement.
SQL> select (trunc(sysdate, 'MM')-1) + level
2 from dual
3 connect by level <= 10
4 /
(TRUNC(SY
---------
01-JAN-10
02-JAN-10
03-JAN-10
04-JAN-10
05-JAN-10
06-JAN-10
07-JAN-10
08-JAN-10
09-JAN-10
10-JAN-10
10 rows selected.
SQL>

Say for example we have a table named: datums, with the column datum(date type)
table contains:
21-01-2010
22-01-2010
01-12-2009
06-10-2008
03-07-2007
then you could use:
SELECT *
FROM datums
WHERE datum
BETWEEN to_date('01/01/2009','mm/dd/yyyy')
AND to_date('12/31/2010','mm/dd/yyyy')
result:
21-01-2010
22-01-2010
01-12-2009

Related

Timestamp filter in PLSQL

Let's say I have an table containing a user rating of movies like IMDB movie database.
ID
USER_REVIEW
USER_RATING
USER_ID
1
blub
10
1
2
blob
9
2
3
blab
7
3
These table inserts have been taken yesterday.
The entries with the id 1 and 2 have been taken between 16:00 and 16:10. The third entry with id 3 have been taken between 16:10 and 16:15 How can I find a select statement that filters me the first two entries between 16:00 and 16:10?
Or is it possible to find out which are the exact timestamps of the inserts from yesterday?
is it possible to find the exact timestamp of the inserts from yesterday?
Sure, if there's a timestamp column in the table.
As it looks as if such a column doesn't exist, a simple option to add it is
alter table movies add date_insert date default sysdate;
Oracle will auto-populate that column with SYSDATE (unless you explicitly insert it), which means that your current INSERT statement remains "as is", you don't have to change it a bit.
Then you'd - for example - select rows inserted yesterday as
select *
from movies
where trunc(date_insert) = trunc(sysdate - 1)
Or, as you asked, rows inserted yesterday (10th of August 2021) between 16:00 and 16:10:
select *
from movies
where date_insert between to_date('10.08.2021 16:00', 'dd.mm.yyyy hh24:mi')
and to_date('10.08.2021 16:10', 'dd.mm.yyyy hh24:mi')
try the GETDATE() function.
here is something to help you:
https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/

12 future numbers required in Oracle SQL

I have one requirement in SQL where
We have couple of market ids
Let say 20,30,40
And here for each market using one plsql function we are getting one campaign number let's say for market 20 I got 20210306,for mrkt 30 we got 20210307, and for 40 mrkt id 20210308.
Now what I want to achieve for each market we should have current campaign no as 20210306 as well as 12 future campaign should be produced by SQL query based on each current campaign of the market.
I am doing it using union all and campaign+1,2,3 and so on which is taking time . Do we have some brief logic for it.
Please suggest
Thanks,
Vijay
You can generate series of data (numbers or dates or even characters) using the LEVEL pseudo column with a CONNECT BY clause.
In your case, it sounds like you want generate the next 10 numbers starting from 20210306.
That could be done like this:
WITH current_campaign ( nr ) AS
( SELECT 20210306 FROM dual )
SELECT
nr + level
FROM
current_campaign
CONNECT BY
level < 13;
20210307
20210308
20210309
20210310
20210311
20210312
20210313
20210314
20210315
20210316
20210317
20210318
The 20210306 could also represent the date March, 6, 2021. If you want to generate those numbers date based numbers you could do that too. For example (starting from 0629 so the result shows the month change, only showing 5 rows)
WITH current_campaign ( cdate ) AS
( SELECT DATE'2021-06-29' FROM dual ) SELECT
TO_CHAR(cdate + level,'YYYYDDMM')
FROM
current_campaign
CONNECT BY
level < 6;
20213006
20210107
20210207
20210307
20210407

Changing date in Str format to Datetime format in SQL

Really basic question but i have zero experience with SQL. I'm using Tableau to do visualisation with data stored in my company's Oracle server, which contains multiple sheets. The primary table i am working with is named YQ005. One of the fields in the primary table I'm working with contains dates but stored as a String in YYYYMMDD format.
I have to convert this to Date format but doing it through Tableau raises the error "ORA-01843: Not a valid month". How can i do a custom SQL query to select this field, convert it to Date-time format and place this new data in a new column?
Littlefoot has a solid answer but it is definitely not for the inexperienced.
The basic function to convert the string to a date is:
select to_date(yyyymmdd, 'yyyymmdd')
If you are having problems with the month, you can just extract it out to check it:
select (case when substr(yyyymmdd, 5, 2) between '01' and '12'
then to_date(yyyymmdd, 'yyyymmdd')
end)
You can also add a check that the value is all numbers:
select (case when regexp_like(yyyymmdd, '^[0-9]{8}') and
substr(yyyymmdd, 5, 2) between '01' and '12'
then to_date(yyyymmdd, 'yyyymmdd')
end)
Validating dates in Oracle gets much more complicated if you have to validate the whole date -- each month has a different number of days and leap years further complicate matters. But months should always be between 01 and 12.
Error you got means that some values in that table - on 5th and 6th place - don't have a valid month value. For example, it might be 20191823 (there's no 18th month, is there?).
Unfortunately, that's what happens when people store dates as strings. There's no easy way out. If you want to do it with SQL only, you might fail or succeed (if you're VERY lucky). For example, have a look at this example:
SQL> desc yq005
Name Null? Type
----------------------------------------- -------- ----------------
DATUM VARCHAR2(8)
SQL> select * From yq005;
DATUM
--------
20191221
13000815
00010101
19302533 -- 25th month and 33rd day
2013Ab12 -- Ab month
2ooo0513 -- year with letters "o" instead of digits "0"
6 rows selected.
SQL>
A query whose where clause tries to identify invalid values:
SQL> alter session set nls_date_format = 'dd.mm.yyyy.';
Session altered.
SQL> select to_date(datum, 'yyyymmdd') result
2 from yq005
3 where substr(datum, 1, 4) between '0000' and '9999'
4 and substr(datum, 5, 2) between '00' and '12'
5 and substr(datum, 7, 2) between '01' and '31'
6 and regexp_like(datum, '^\d+$');
RESULT
-----------
21.12.2019.
15.08.1300.
01.01.0001.
SQL>
lines #3, 4 and 5 are trying to identify valid year/month/day. The first two are OK, more or less, but - it'll miserably fail on at least half of all months because e.g. 20191131 is "valid", but there are no 31 days in November
line #6 eliminates values that aren't all digits
Just to check that 20191131:
SQL> insert into yq005 values ('20191131');
1 row created.
SQL> select to_date(datum, 'yyyymmdd') result
2 from yq005
3 where substr(datum, 1, 4) between '0000' and '9999'
4 and substr(datum, 5, 2) between '00' and '12'
5 and substr(datum, 7, 2) between '01' and '31'
6 and regexp_like(datum, '^\d+$');
ERROR:
ORA-01839: date not valid for month specified
no rows selected
SQL>
As I said, it won't work; the same goes for other 30-days months, as well as February.
You could try to create a function which converts string to date; if it succeeds, fine. If not, skip that value:
SQL> create or replace function f_valid_date_01 (par_datum in varchar2)
2 return number
3 is
4 -- return 1 if PAR_DATUM is a valid date; return 0 if it is not
5 l_date date;
6 begin
7 -- yyyymmdd is format you expect
8 l_date := to_date(par_datum, 'yyyymmdd');
9 return 1;
10 exception
11 when others then
12 return 0;
13 end;
14 /
Function created.
SQL>
Let's use it:
SQL> select datum original_value,
2 to_char(to_date(datum, 'yyyymmdd'), 'dd.mm.yyyy') modified_value
3 from yq005
4 where f_valid_date_01 (datum) = 1;
ORIGINAL MODIFIED_V
-------- ----------
20191221 21.12.2019
13000815 15.08.1300
00010101 01.01.0001
SQL>
Just the opposite - fetch invalid dates:
SQL> select datum
2 from yq005
3 where f_valid_date_01 (datum) = 0;
DATUM
--------
19302533
2013Ab12
2ooo0513
20191131
SQL>
This is just one option you might use; there certainly are others, just Google for them. The bottom line is: always store dates into a DATE datatype column and let the database take care about (in)valid values.
[EDIT: how to populate a new column with a valid date]
If there's no date datatype column in the table, add it:
SQL> alter table yq005 add new_datum date;
Table altered.
Now run the update; mind the where clause:
SQL> update yq005 set
2 new_datum = to_date(datum, 'yyyymmdd')
3 where f_valid_date_01(datum) = 1;
3 rows updated.
SQL> select * From yq005;
DATUM NEW_DATUM
-------- -----------
20191221 21.12.2019.
13000815 15.08.1300.
00010101 01.01.0001.
19302533
2013Ab12
2ooo0513
20191131
7 rows selected.
SQL>
The best solution would be to have whoever maintains your database alter the table definition to store dates using the DATE datatype instead of some form of string.
But if you can't or don't wish to alter the Oracle schema, then I would try using the DATEPARSE() function in Tableau, as follows (assuming your date field is named XXX_DATE)
In Tableau, rename XXX_DATE to XXX_DATE_ORGINAL
Define a calculated field called XXX_DATE as DATEPARSE("YYYYMMdd", [XXX_DATE_ORIGINAL])
Hide the original field XXX_DATE_ORIGINAL
Now you can use your XXX_DATE field as a date in Tableau
The renaming and hiding of the original field is not strictly necessary. I just find it helps keep the data source understandable. For more info, see the Tableau online help for DateParse

oracle query to extract all the dates within given periods and range

Consider if there is a table with two column
TABLE TIME_FRAME
------------------------
|FROM |TO |
|2013-12-13 |2014-01-06|
|2011-12-05 |2011-12-31|
|2014-01-23 |2014-02-22|
|2011-11-21 |2011-12-17|
........
FROM and TO from each row defines a period of time. Also there can be overlap between the periods (here row 2 and row 4) or cover multiple periods
if give a start_date and end_date as parameters here the requirement is about return all the dates falls within the parameters and also within any of the periods in the columns
for example
if start_date is 2013-12-25 and end_date is 2014-02-10
so from above data it should return all dates between
`2013-12-25` and `2014-01-06`
plus
`2014-01-23` and `2014-02-10`
is it possible to create a query for above requirement (not by PL/SQL)?
It's possible by creating set of days using LEVEL recursion operator and then filtering this set by comparing it to your table data. Here is the working Oracle SQL query for you:
select day
from (select to_date('25-DEC-2013', 'dd-mon-yyyy') - 1 + level day
from dual
connect by level <= to_date('10-FEB-2014', 'dd-mon-yyyy') -
to_date('25-DEC-2013', 'dd-mon-yyyy') + 1)
where exists
(select 1 from TIME_FRAME p where day between p.FROM and p.TO);
Hope this helps!

Oracle Database Temporal Query Implementation - Collapse Date Ranges

This is the result of one of my queries:
SURGERY_D
---------
01-APR-05
02-APR-05
03-APR-05
04-APR-05
05-APR-05
06-APR-05
07-APR-05
11-APR-05
12-APR-05
13-APR-05
14-APR-05
15-APR-05
16-APR-05
19-APR-05
20-APR-05
21-APR-05
22-APR-05
23-APR-05
24-APR-05
26-APR-05
27-APR-05
28-APR-05
29-APR-05
30-APR-05
I want to collapse the date ranges which are continuous, into intervals. For examples,
[01-APR-05, 07-APR-05], [11-APR-05, 16-APR-05] and so on.
In terms of temporal databases, I want to 'collapse' the dates. Any idea how to do that on Oracle? I am using version 11. I searched for it and read a book but couldn't find/understand how to do it. It might be simple, but everyone has their own flaws and Oracle is mine. Also, I am new to SO so my apologies if I have violated any rules. Thank You!
You can take advantage of the ROW_NUMBER analytical function to generate a unique, sequential number for each of the records (we'll assign that number to the dates in ascending order).
Then, you group the dates by difference between the date and the generated number - the consecutive dates will have the same difference:
Date Number Difference
01-APR-05 1 1 -- MIN(date_val) in group with diff. = 1
02-APR-05 2 1
03-APR-05 3 1
04-APR-05 4 1
05-APR-05 5 1
06-APR-05 6 1
07-APR-05 7 1 -- MAX(date_val) in group with diff. = 1
11-APR-05 8 3 -- MIN(date_val) in group with diff. = 3
12-APR-05 9 3
13-APR-05 10 3
14-APR-05 11 3
15-APR-05 12 3
16-APR-05 13 3 -- MAX(date_val) in group with diff. = 3
Finally, you select the minimal and maximal date in each of the groups to get the beginning and ending of each range.
Here's the query:
SELECT
MIN(date_val) start_date,
MAX(date_val) end_date
FROM (
SELECT
date_val,
row_number() OVER (ORDER BY date_val) AS rn
FROM date_tab
)
GROUP BY date_val - rn
ORDER BY 1
;
Output:
START_DATE END_DATE
------------ ----------
01-04-2005 07-04-2005
11-04-2005 16-04-2005
19-04-2005 24-04-2005
26-04-2005 30-04-2005
You can check how that works on SQLFidlle: Dates ranges example