SWAT Blog

Archive for the ‘Oracle’ Category

Generate Date Ranges in Oracle PL/SQL

Tuesday, January 28th, 2014

Here is an easy way to generate date ranges in oracle pl/sql:

WITH t AS
  (SELECT to_date('01-OCT-2012') start_date,
    to_date('30-SEP-2013') end_date
  FROM dual
  )
  SELECT add_months(TRUNC(start_date,'mm'),LEVEL      - 1) START_DATE,
    add_months(add_months(TRUNC(start_date,'mm'),LEVEL - 1),1)-1 END_DATE
  FROM t
    CONNECT BY TRUNC(end_date,'mm') >= add_months(TRUNC(start_date,'mm'),LEVEL - 1)

OUTPUT:

START_DATE  END_DATE  
----------- -----------
01-OCT-2012 31-OCT-2012 
01-NOV-2012 30-NOV-2012 
01-DEC-2012 31-DEC-2012 
01-JAN-2013 31-JAN-2013 
01-FEB-2013 28-FEB-2013 
01-MAR-2013 31-MAR-2013 
01-APR-2013 30-APR-2013 
01-MAY-2013 31-MAY-2013 
01-JUN-2013 30-JUN-2013 
01-JUL-2013 31-JUL-2013 
01-AUG-2013 31-AUG-2013 
01-SEP-2013 30-SEP-2013 

 12 rows selected

How To query contiguous data ranges – Oracle

Saturday, January 22nd, 2011

I recently presented a way of querying contiguous data ranges using SQL Server In this post I am going to tackle the same problem but solving it in Oracle instead.
Often times we are confronted with problems that seem very easy to start with but once you get your teeth into it, you realise it wasn’t as easy as initially thought. In this blog, I am attempting to work with data ranges that are not easily groupable.
Problem Statement: Using the data structure listed below, group the data ranges by dataKey when the dataKey is contigous, when breaks in data key are identified, create a new reporting output line. Query input-

grp dataRange dataKey Comments
A 1000 1
A 1001 1
A 1002 1
A 1003 1
A 1004 1
A 1005 2 — Notice dataKey is not contiguous
A 1006 2
A 1007 1
A 1008 1
A 1009 1
A 1010 1
A 1011 1

Desired Query output-

dataKey DataRangeBreakDown
1 A [1000 .. 1004]
2 A [1005 .. 1006]
1 A [1007 .. 1011]

Approach: This is an interesting puzzle, because we cannot simply group the data by “dataKey” column, doing so would ignore the breaks in data. The key to solving this refreshing problem is by “somehow” introducing a pseudo-column which does the heavy lifting for us. Table below illustrates the new pseudo-column, if we introduce this column using SQL, rest is just simple group by. Before peeking at the final solution, I would encourage you to have a go, but if you can’t for any reason I have presented final solution later in the blog.

grp dataRange dataKey New Column
A 1000 1 0
A 1001 1 0
A 1002 1 0
A 1003 1 0
A 1004 1 0
A 1005 2 1
A 1006 2 1
A 1007 1 2
A 1008 1 2
A 1009 1 2
A 1010 1 2
A 1011 1 2

Setup Data:

 DROP TABLE tmpDataRange; CREATE TABLE
  tmpDataRange AS SELECT 'A' grp, 1000 AS dataRange, 1 AS dataKey FROM Dual UNION ALL
  SELECT 'A', 1001, 1 FROM Dual UNION ALL SELECT 'A', 1002, 1 FROM Dual UNION ALL SELECT
  'A', 1003, 1 FROM Dual UNION ALL SELECT 'A', 1004, 1 FROM Dual UNION ALL SELECT 'A',
  1005, 2 FROM Dual UNION ALL SELECT 'A', 1006, 2 FROM Dual UNION ALL SELECT 'A', 1007, 1
  FROM Dual UNION ALL SELECT 'A', 1008, 1 FROM Dual UNION ALL SELECT 'A', 1009, 1 FROM
  Dual UNION ALL SELECT 'A', 1010, 1 FROM Dual UNION ALL SELECT 'A', 1011, 1 FROM Dual ;
  

Solution:
Welcome to the solution. I have tackled the problem using the aproach above using Common Table Expressions (CTE) feature. I think CTEs are fantastic even for writing daily garden variety queries as they make the query so much more understandable by being written in the way we digest other information, i.e. Top to Bottom. Overview of solution query:
Data0 – Instantiate the problem statement input data
Data1 – Assign incremental row numbers to input data
Data2 – Self join the data to the previous row
Data3 – This is where the “magic” happens – Build a cumulative data column which increments on every dataKey break
Data4 – Is concerned with grouping and presenting the data in format requested Presented below is the final solution:

 WITH data0 AS (SELECT grp, dataRange, dataKey FROM
  tmpDataRange), data1 AS (SELECT grp, dataRange, dataKey, LAG(dataKey) OVER(ORDER BY
  dataRange ASC) lagDataKey FROM data0), data2 AS (SELECT grp, dataRange, dataKey, CASE
  WHEN dataKey=NVL(lagDataKey,dataKey) THEN 0 ELSE 1 END cumu FROM data1), data3 AS
  (SELECT grp, dataRange, dataKey, SUM(cumu) OVER(ORDER BY dataRange) cumulativeWindow
  FROM data2), data4 AS (SELECT cumulativeWindow, dataKey, MAX(grp) || ' [' ||
  TO_CHAR(MIN(dataRange)) ||' .. '|| TO_CHAR(MAX(dataRange)) ||']' DataRangeBreakDown
  FROM data3 GROUP BY cumulativeWindow, dataKey) SELECT dataKey, DataRangeBreakDown FROM
  data4; 

Variations: One of the great things about this solution is that it is data-type agnostic. Feel free to change the data-type of the dataRange column to DATE for example as shown below and it still works.

 DROP TABLE tmpDataRange; CREATE TABLE tmpDataRange AS SELECT 'A' grp,
  SYSDATE AS dataRange, 1 AS dataKey FROM Dual UNION ALL SELECT 'A', SYSDATE+1, 1 FROM
  Dual UNION ALL SELECT 'A', SYSDATE+2, 1 FROM Dual UNION ALL SELECT 'A', SYSDATE+3, 1
  FROM Dual UNION ALL SELECT 'A', SYSDATE+4, 1 FROM Dual UNION ALL SELECT 'A', SYSDATE+5,
  2 FROM Dual UNION ALL SELECT 'A', SYSDATE+6, 2 FROM Dual UNION ALL SELECT 'A',
  SYSDATE+7, 1 FROM Dual UNION ALL SELECT 'A', SYSDATE+8, 1 FROM Dual UNION ALL SELECT
  'A', SYSDATE+9, 1 FROM Dual UNION ALL SELECT 'A', SYSDATE+10, 1 FROM Dual UNION ALL
  SELECT 'A', SYSDATE+11, 1 FROM Dual ; 

Would love to hear your thoughts on this, or if you have a better solution why not share it with everyone.

Oracle 10g Advanced Query Rewrite – Query Equivalence

Friday, June 26th, 2009

Occasionally there are instances where we have very little or no control over the query generated by application layer, especially if it a 3rd party application. If you’ve identified a problematic query originating from such an application, what do do ?

Well if your enterprise is on Oracle 10g, you are in luck.

Oracle 10g introduced Query equivalence, which can be used to substitute any SQL DML statement for another (including use of the new SQL Model clause), and is particularly useful when SQL is generated by an application and cannot be changed, but the DBA or advanced developer knows of a better way to phrase the query, perhaps using new data structures that they might have created.

Lets see step by step

create table dept
as
select * from scott.dept;

Problem Query

select * from dept;

DEPTNO DNAME LOC
———- ————– ————-
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Optimized Query

create or replace view vw_optimised_dept
as
select deptno, LOWER(dname) dname, loc
from dept order by loc;

Query Equivalence

begin


sys.dbms_advanced_rewrite.declare_rewrite_equivalence

( name           => 'test_equivalence',
source_stmt      => 'select * from dept',
destination_stmt => 'select * from vw_optimised_dept',
validate         => FALSE,
rewrite_mode     => 'TEXT_MATCH' );
end;

/

That is it!
Next time Oracle 10g optimiser comes across this query it would rewrite it.

select * from dept;

DEPTNO DNAME LOC
———- ————– ————-
40 operations BOSTON
30 sales CHICAGO
20 research DALLAS
10 accounting NEW YORK

Note the DNAME column in the lowercase, proving that our problematic query was rewritten.
It is however important to note that the text match rewrite can distinguish contexts where the difference between uppercase and lowercase is significant and where it is not.

For example, the following statements are equivalent:

SELECT X, 'aBc' FROM Y;
Select x, 'aBc' From y;

But following statements are not:

SELECT X, 'aBc' FROM Y;
SELECT X colx, 'aBc' coly FROM Y Y_ALIAS;

If you wish to remove this rewrite at a later stage-

exec sys.dbms_advanced_rewrite.drop_rewrite_equivalence( 'test_equivalence' );

select * from dept;

DEPTNO DNAME LOC
———- ————– ————-
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

In this post I have only picked up one sample usage, for a more detailed discussion please visit Oracle documentation on Advanced Query Rewrite.

  • © 2004-2015 Special Work & Technology Limited