Tuesday, 22 May 2018

UNPIVOT in SQL



SELECT 'welcome' col1,
       'to'      col2,
       'oracle'  col3,
       'class'   col4
FROM   dual;



SELECT * FROM (
            SELECT
                'welcome' col1,
                'to'      col2,
                'oracle'  col3,
                'class'   col4
            FROM
                dual)
UNPIVOT(column_val for column_name IN (col1,col2,col3,col4));



SELECT
    *
FROM
    (
        SELECT
            ename,
            To_char(empno) empno,
            job
        FROM
            emp
    )
UNPIVOT ( column_val for column_name  IN ( ename,empno,job ));

Monday, 21 May 2018

Approx_rank, Approx_sum, Approx_count ( Oracle 18C New Functions)


1. "GROUP BY" clause is mandatory to use approx_* functions.
2. Approx_count & Approx_sum functions has to be used with "HAVING" clause containing approx_rank function.
3. Both approx_* functions and non approx_* aggregate functions are not allowed in same select statement.
4. "ORDER BY" clause within approx_rank function should use only approx_* functions only (+ with "DESC" keyword only).
5. "HAVING" clause should contain "<= number" or "< number" conditions only. Follow this format only ('APPROX_RANK(PARTITION BY ... ORDER BY ... DESC) <(=) n')

SELECT   empno,
         approx_rank ( order by approx_sum(sal) DESC )
FROM     scott.emp
GROUP BY empno
HAVING   approx_rank ( ORDER BY approx_sum(sal) DESC ) <=10
ORDER BY 2;




SELECT   deptno,
         Approx_sum(sal),
         approx_rank ( order by approx_sum(sal) DESC )
FROM     scott.emp
GROUP BY deptno
HAVING   approx_rank ( ORDER BY approx_sum(sal) DESC ) <=10;




SELECT   deptno,
         Approx_count(empno),
         approx_rank ( order by approx_count(empno) DESC )
FROM     scott.emp
GROUP BY deptno
HAVING   approx_rank ( ORDER BY approx_count(empno) DESC ) <=10;


Friday, 18 May 2018

Oracle Approximate Count Distinct Function

Oracle Approximate Count Distinct Function


CREATE TABLE tab_num_list
  (
     col1 NUMBER
  );

INSERT INTO tab_num_list
SELECT LEVEL
FROM   dual
CONNECT BY LEVEL <= 100000;

SELECT Count(*),
       Count(DISTINCT col1),
       Approx_count_distinct(col1)
FROM   tab_num_list; 

Wednesday, 16 May 2018

Loading Data into Oracle database

There are many situation, where the data from external sources(like text, csv, JSON, XML etc.,) needs to be loaded into database.This can be achieved by many ways. Though there are many ways, each option is suited for particular scenarios only. This is mainly due to the difference in the source data and target data structures.
For eg, we might need different mechanism to read text file vs XML files. The mechanism needs to be decided depending on the nature/type of source data.

Given below the possible ways to load data into oracle database.
  1. Database Client Tools (like SQL developer, TOAD etc., support loading data from files into tables)
  2.  Program/Script ( Using any "Programming language" (Like Java etc.,)  or "Scripting Language" (Like shell script, python etc.,))
  3. SQL Loader (Oracle provided utility )
  4. External Table ( Oracle provided option to read data from external files as if they present in table)
  5. PLSQL Program ( Oracle supplied UTL_FILE package to do file handling operations like read, write, copy and remove operations on operating system files)
  6. ETL Tools ( Lot of ETL tools are available to map, extract and load the data from external files into oracle database)

Of all the options given above, option 3,4 & 5 are oracle provided mechanism to load data into oracle database.

Here is a course on Udemy to teach about oracle supplied options to load the data from external source into oracle database.

This course covers in detail about SQL Loader, UTL_FILE & External table concepts with example.

https://www.udemy.com/oracle-file-handling-utl_file-sql-loader-external-table/



Monday, 14 May 2018

PIVOT in SQL






SELECT
    *
FROM
    (
        SELECT job,deptno,sal
        FROM emp
    )
        PIVOT ( sum ( sal )
            FOR deptno
            IN ( 10,20,30 )
        );
    
SELECT
    *
FROM
    (
        SELECT deptno,sal
        FROM emp
    )
        PIVOT ( sum ( sal )
            FOR deptno
            IN ( 10,20,30 )
        );
SELECT
    *
FROM
    (
        SELECT job,sal
        FROM  emp
    )
        PIVOT ( sum ( sal )
            FOR job
            IN ( 'CLERK','SALESMAN','PRESIDENT','MANAGER','ANALYST' )
        );
SELECT
    *
FROM
    (
        SELECT  job,deptno,sal
        FROM   emp
    )
        PIVOT ( sum ( sal )
            FOR job
            IN ( 'CLERK','SALESMAN','PRESIDENT','MANAGER','ANALYST' )
        );

Sunday, 13 May 2018

Oracle 12C With Clause Enhancements



Functions can be defined in the "WITH" clause and can be used in select statement from 12.1 onwards.
       

WITH
    FUNCTION fn_cube (p_no NUMBER) RETURN NUMBER
        AS
    BEGIN
        RETURN power(p_no,3);
    END;

SELECT
    100 AS num,
    fn_cube(10)
FROM
    dual;
/

       
 
Another Example of "WITH" clause function
       

WITH
    FUNCTION avg_sal (p_deptno NUMBER) RETURN NUMBER AS
        v_avg_sal   NUMBER;
    BEGIN
        SELECT
            AVG(sal)
        INTO v_avg_sal
        FROM
            emp
        WHERE
            deptno = p_deptno;

        RETURN v_avg_sal;
    END avg_sal;

SELECT
    deptno,
    dname,
    loc,
    round(avg_sal(deptno) ) avg_sal -- Calling the function
FROM
    dept;
/

       
 
No DMLs are allowed in function while using in select statements. However DMLs can be used with autonomous_transaction functions.
       

CREATE TABLE temp_1 (
    col1   NUMBER
);

WITH
    FUNCTION avg_sal (p_deptno NUMBER) RETURN NUMBER AS
        PRAGMA autonomous_transaction;
        v_avg_sal   NUMBER;
    BEGIN
        SELECT
            AVG(sal)
        INTO v_avg_sal
        FROM
            emp
        WHERE
            deptno = p_deptno;

        INSERT INTO temp_1 VALUES ( 1 );

        COMMIT;
        RETURN v_avg_sal;
    END avg_sal;

SELECT
    deptno,
    dname,
    loc,
    round(avg_sal(deptno) ) avg_sal -- Calling the function
FROM
    dept;
/

       
 
Example of using procedure and function in WITH clause, however procedures cannot be called directly in select statements. Procedure can be accessed via the calling functions as show below.
       

WITH
    PROCEDURE pr_cube (p_no IN OUT NUMBER)
        AS
    BEGIN
        p_no := power(p_no,3);
    END;

    FUNCTION fn_cube (p_no NUMBER) RETURN NUMBER AS
        lv_num   NUMBER := p_no;
    BEGIN
        pr_cube(lv_num);
        RETURN lv_num;
    END;

SELECT
    100 AS num,
    fn_cube(10)
FROM
    dual;
/

       
 
       

WITH
    PROCEDURE pr_cube (p_no IN OUT NUMBER) AS
        PRAGMA autonomous_transaction;
    BEGIN
        p_no := power(p_no,3);
        INSERT INTO temp_1 VALUES ( 1 );

        COMMIT;
    END;

    FUNCTION fn_cube (p_no NUMBER) RETURN NUMBER AS
        lv_num   NUMBER := p_no;
    BEGIN
        pr_cube(lv_num);
        RETURN lv_num;
    END;

SELECT
    100 AS num,
    fn_cube(10)
FROM
    dual;
/

       
 

Monday, 7 May 2018

Oracle 18C JSON_EQUAL function



select case
when json_equal('{}','{   }') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"A":null}','{"A":""}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"EMPNAME":"SCOTT"}','{"EMPNAME":"SCOTT"}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"EMPNAME":"SCOTT"}','{"EMPNAME":"Scott"}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"EMPID":"1000","EMPNAME":"KING"}','{"EMPID":"1000","EMPNAME":"KING"}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"EMPID":"1000","EMPNAME":"KING"}','{"EMPNAME":"KING","EMPID":"1000"}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"NUMLIST":[1,2,3,4,5,6]}','{"NUMLIST":[1,2,3,4,5,6]}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;

select case
when json_equal('{"NUMLIST":[1,2,3,4,5,6]}','{"NUMLIST":[6,5,4,3,2,1]}') then 'SAME JSON' else 'DIFFERENT JSON' end JSON_COMP_RESULT
from dual;



CREATE TABLE json_sample_data_table (
    s_no                 NUMBER NOT NULL,
    json_1               VARCHAR2(100),
    json_2               VARCHAR2(100),
    CONSTRAINT json_chk_1 CHECK ( json_1 IS JSON ),
    CONSTRAINT json_chk_2 CHECK ( json_2 IS JSON )
);

insert into json_sample_data_table values(1,'{}','{  }');
insert into json_sample_data_table values(2,'{"A":null}','{"A":""}');
insert into json_sample_data_table values(3,'{"A":""}','{"A":""}');
insert into json_sample_data_table values(4,'{"EMPNAME":"SCOTT"}','{"EMPNAME":"SCOTT"}');
insert into json_sample_data_table values(5,'{"EMPID":"1000","EMPNAME":"KING"}','{"EMPID":"1000","EMPNAME":"KING"}');
insert into json_sample_data_table values(6,'{"EMPID":"1000","EMPNAME":"KING"}','{"EMPNAME":"KING","EMPID":"1000"}');
insert into json_sample_data_table values(7,'{"NUMLIST":[1,2,3,4,5,6]}','{"NUMLIST":[1,2,3,4,5,6]}');
insert into json_sample_data_table values(8,'{"NUMLIST":[1,2,3,4,5,6]}','{"NUMLIST":[6,5,4,3,2,1]}');

commit;


select * from json_sample_data_table
where json_1 = json_2;

select * from json_sample_data_table
where json_equal(json_1,json_2);

select * from json_sample_data_table
where not json_equal(json_1,json_2);

select s_no, json_1,json_2,
case
when json_equal(json_1,json_2)
   then 'SAME JSON'
   else 'DIFFERENT JSON'
end JSON_COMP_RESULT
from json_sample_data_table;

About Me

I am Siva Jeevan.LK [LEARN | CODE | TRAIN | SHARE] Passionate to answer oracle SQL & PLSQL related questions. In my day to day job, I work with technologies including Oracle, Java, Python, MongoDB, talend and UNIX. I am passionate about "DATA", “SQL” , coding & training. In my spare time, I teach database technologies , ETL etc. I am very glad that you are reading my Profile, and I value your time as well as mine. Looking forward to see you in my videos at Siva Academy Passionate to answer oracle SQL & PLSQL related questions. You can contact me via My youtube channel (Siva Academy) or drop an email at siva.k.academy@gmail.com Happy to Learn & Help :-)

Total Pageviews