Category: Allgemein

  • Cubes in Oracle

    The issue about roll ups in Oracle is that roll up only calculate sub totals in one direction. So if you have a country, city combination, subtotals are calculated per city in a country, but not in a country per city.

    In case of a hierarchy, this is ok. One is only interested in having the subtotals in a certain natural order. First totals per city, then totals per country and finally totals per region.

    It is different if not such natural order exists. Think of a combination of department and location. A department may be spread over several locations and a location may have several departments. One could be interested to have to subtotals per department (aggregating over locations) and subtotals per location (aggregating over departments).

    For that situation, we have the concept of a cube.

    select department_id ,job_id, count(employee_id) emp_count 
    FROM
    employees
    group by cube (department_id ,job_id) ;

    So instead of “rollup”, the keyword “cube” is used.

    Like the rollup, we may add a grouping clause to indicate how the subtotals are calculated.

    select  department_id ,  job_id , count(*) ,
     GROUPING ( department_id ) g1,
     GROUPING ( job_id ) g2
     from employees
     group by  cube( department_id ,  job_id );

    or

    select  department_id ,  job_id , count(*) ,
    GROUPING_id (department_id,job_id) group_id
    from employees
    group by  cube( department_id ,  job_id );

    or

    select  department_id ,  job_id , count(*) ,
    GROUPING_id (department_id,job_id) group_id
    from employees
    group by
    GROUPING SETS  ((department_id,job_id ) , () );

    Note that the latter SQL does not contain a cube clause. Instead, the GROUPING SETS is used. This allows us to explicitly mention all combinations for which a sub total is required. Here, the grand total is required (therefore ()), with the subtotals on low level (department_id, job_id).

  • Oracle: rollup totals

    Oracle has a nice feature that allows to show a grand total. I assume you want to show a line with a grand total when a grouping by SQL is executed. Something that shows the number of employees per department and the total number of employees.

    That can be done by a simple change in the traditional group by SQL:

    select department_id , to_char(sum(salary),'999999d00') avg_sal, count(*) as Nmbr_Employees
     FROM
     employees
     group by ROLLUP (department_id );

    The last line then provides a grand total:

    One may be puzzled by the usage of “null”: does it indicate a null as no department is found or does it refer to a “null” as it is a grand total where not all departments are known.

    This can be solved by adding one additional column that indicates the level. This one column is invoked by “grouping(column) alias” as in:

    select  decode ( GROUPING (department_id), 1,'Grand total' ,
                                                0,nvl(to_char(department_id ),                      'no dept') ) dept_id  , 
     sum(salary) sum_sal 
     FROM
     employees
     group by rollup( department_id  )

    It is possible to extend the number of subtotals. So if you have two or more items in the group by clause (say region, country and city ), one may want to calculate the subtotals for region, country and city. This can be done with a small extension of previous SQL:

    This also allows us to create totals per level. See:

    select region, country,city, sum(amount)   
    from info_sales 
    group by  rollup (region, country,city); 

    This is the way to create hierarchical data. Grand totals are given, along with totals per region, per country and per city.

  • Real time loading in Oracle

    The idea behind real time loading a data warehouse is to propagate data directly after an event has happened in an underlying source database. Let us think of an invoice database. In most circumstances, the invoice database is loaded with records that represents invoices that are sent. During the night, a set of records in collected and they are sent as a file to a data warehouse.

    An alternative is to propagate a message from the source database directly after a new record is inserted. This message is received by the data warehouse. It can then be subsequently inserted into the data warehouse.

    In Oracle, we have a trigger mechanism to implement this idea.

    The trigger is fired, once the source table is changed. This trigger looks like:

    create or replace trigger INVOER.T$EMPLOYEESUITVOER
        after insert or update or delete on INVOER.EMPLOYEES
        for each row
        declare
            V_FLAG  VARCHAR(1);
            V_EMPLOYEE_ID   NUMBER(6);
        begin
            if inserting then
                V_EMPLOYEE_ID := :new.EMPLOYEE_ID;
                V_FLAG := 'I';
            end if;
         if updating then
            V_EMPLOYEE_ID := :new.EMPLOYEE_ID;
            V_FLAG := 'U';
        end if;
        if deleting then
            V_EMPLOYEE_ID := :old.EMPLOYEE_ID;
            V_FLAG := 'D';
        end if;
    
        insert into UITVOER.J$EMPLOYEES
        (
            JRN_SUBSCRIBER,
            JRN_CONSUMED,
            JRN_FLAG,
            JRN_DATE,
            EMPLOYEE_ID
        )
        select  USER,
            '0',
            V_FLAG,
            sysdate,
            V_EMPLOYEE_ID
        from    dual
        ;
    end; 

    The idea behind this trigger is that each insert, delete or update generates a new record in a remote table in the staging area of a data warehouse. Here, a table (UITVOER.J$EMPLOYEES) is continuously updated with each update representing a change in the source database.

    In this case, the table in the staging area only contains the primary key of the record that is changed. With only a minor modification, one could include all fields from the source table. A similar result can be achieved with a view where the UITVOER.J$EMPLOYEES is joined with the original table.

    See below:

    DROP VIEW UITVOER.JV$DEMPLOYEES;
    CREATE VIEW UITVOER.JV$DEMPLOYEES
    AS select     decode(TARG.ROWID, null, 'D', 'I')   AS  JRN_FLAG,
        JRN.JRN_SUBSCRIBER       AS  JRN_SUBSCRIBER,
        JRN.JRN_DATE         AS  JRN_DATE,
        JRN.EMPLOYEE_ID      AS  EMPLOYEE_ID
        ,TARG.FIRST_NAME         AS  FIRST_NAME,
        TARG.LAST_NAME       AS  LAST_NAME,
        TARG.EMAIL       AS  EMAIL,
        TARG.PHONE_NUMBER        AS  PHONE_NUMBER,
        TARG.HIRE_DATE       AS  HIRE_DATE,
        TARG.JOB_ID      AS  JOB_ID,
        TARG.SALARY      AS  SALARY,
        TARG.COMMISSION_PCT      AS  COMMISSION_PCT,
        TARG.MANAGER_ID      AS  MANAGER_ID,
        TARG.DEPARTMENT_ID       AS  DEPARTMENT_ID
    from    (
            select  L.JRN_SUBSCRIBER     AS  JRN_SUBSCRIBER,
                L.EMPLOYEE_ID    AS  EMPLOYEE_ID,
                L.JRN_CONSUMED as JRN_CONSUMED,
                L.JRN_DATE   AS  JRN_DATE
            from    UITVOER.J$EMPLOYEES    L
        )    JRN
    left join INVOER.EMPLOYEES    TARG    
    ON JRN.EMPLOYEE_ID  = TARG.EMPLOYEE_ID
    and JRN.JRN_CONSUMED = 0;

    Finally, this can be used to update the data warehouse.

  • Reading XML data with ODI

    ODI has a feature that allows to read XML data. I really enjoyed working with this feature. It allowed to directly insert values from an XML file into different fields in an Oracle table.

    The idea is very simple. One has to set up a technical and logical schema that is based on XML. With the properties of the physical scheme, the XML filename is given:

    Here, one may see that the file “maaltijd.xml” is used that is stored in directory “C:\Users\tmaanen\CloudStation\ODImap”.

    Subsequently, a model is created whereby the XML dataset is reverse engineered:

    One table contains data that are of interest. That table is used in a mapping as an input. As output, we use an Oracle table:

    Running this mapping propagates the data from an XML file (“Maaltijd.xml”) to an Oracle table. See below for a screen shot of the Oracle table:

  • ODI and SCD

    Oracle has a very nice ETL tool (or in Oracle parlance ELT tool). Its purpose is clear: make a easily maintainable set of workflows that show clearly the lineage from source to target.

    To use ODI, we must download a zip file from Oracle. It can be found if we look for “download ODI”. We get a file (fmw_12.2.1.4.0_odi_Disk1_1of1.zip) that contains an executable whereby ODI can be installed. This is well explained in different youtube movies and on the Oracle website.

    We must then install the master repository, followed by a work repository. This is also straight forward and well explained in multiple sources.

    We then proceed by setting up the technical environment necessary for a SCD2 loading. We start with an input table that has four fields with one field being a key that will be used as the business key. The table is called DEPARTMENTS and looks like:

    The data will be written into a target table that contains the four fields from above with 4 additional technical fields: the surrogate key, a date_from and a date_to to indicate the validity period and a field that indicates whether a record is current or not. It looks like:

    The surrogate key now acts as a key, whereas the original business key is deprived of its role as key. this can be understood as we will collect multiple versions of a certain business key with different periods of validity.

    We will use a sequence to generate values for the key.

    We must store these items in ODI. Under the heading models, the input table and the target table can be stored:

    whereas the sequence is stored under projects:

    We may then describe the properties of the target table:

    and defining the role of each field:

    We can then create a mapping:

    In a final step, we must define the knowledge modules:

    and the Integration Knowledge Module with the Check Knowledge Module:

    Running this mapping provides the desired result.

  • Oracle – provide a rank

    Oracl has a nice feature to add a rank to a row. Let us assume you have a table with 4 values: some rows have an A, others have a B, others have a C and some are D. Oracle is able to provide a rank to this series by providing a 1 to A, 2 to B, 3 to C and 4 to D.

    This could be used (for example) is we have prices that we would like to order: the lowest price a 1, second a 2 etc.

    The code is as follows:

     CREATE TABLE rank_demo ( col VARCHAR(10) NOT NULL); 
    INSERT ALL 
    INTO rank_demo(col) VALUES('A')
    INTO rank_demo(col) VALUES('A')
    INTO rank_demo(col) VALUES('B')
    INTO rank_demo(col) VALUES('C')
    INTO rank_demo(col) VALUES('C')
    INTO rank_demo(col) VALUES('C')
    INTO rank_demo(col) VALUES('D')
    SELECT 1 FROM dual; 
    
    SELECT  col,  dense_RANK() OVER (ORDER BY col) my_rank
    FROM  rank_demo; 

    Which provides:

  • Keeping a journal in Oracle

    The idea is actually quite simple. Whenever a record in a table (here: employee) is updated with a new value in a field (here: salary), a trigger gets fired. This trigger stored the old and new value of salary in a seperate table.

    I like this trigger. It is simple. It is straightforward.

    create or replace TRIGGER employee_journal
      AFTER INSERT OR UPDATE OF salary ON employee
      FOR EACH ROW
    BEGIN
      INSERT INTO audit_entry 
        (entry_date, entry_user, entry_text, old_value, new_value)
      VALUES
        (SYSDATE, USER, 'Salary Update ' || :NEW.ssn, 
         :OLD.salary,
         :NEW.salary);
    END;

    An alternative is a trigger that calls a stored procedure:

    create or replace TRIGGER employee_journal2
      AFTER INSERT OR UPDATE OF salary ON employee
      FOR EACH ROW
      call sp_employee_journal(:OLD.salary,:NEW.salary,:NEW.SSN)

    with the stored procedure:

    create or replace procedure  sp_employee_journal (oud IN employee.salary%type, nieuw IN employee.salary%type, ssn IN employee.ssn%type) as
    begin
      INSERT INTO audit_entry 
        (entry_date, entry_user, entry_text, old_value, new_value)
      VALUES
        (SYSDATE, USER, 'Salary Update ' || ssn,oud,nieuw);
    end;
  • Oracle – trigger example

    This note provides an example on a trigger. I like this example as it shows how additional business logic can be implemented.

    It is an example of a statement trigger: whenever a statement is issued, the trigger fires once, no matter how many records are affected.

    CREATE OR REPLACE TRIGGER security_time_check
         BEFORE DELETE OR UPDATE ON emp
    DECLARE
      dy_of_week   CHAR(3);
      hh_of_day    NUMBER(2);
    BEGIN
      dy_of_week := TO_CHAR(SYSDATE,'DY');
      hh_of_day := TO_CHAR(SYSDATE,'HH24');
      IF dy_of_week IN ('WO')
         OR hh_of_day NOT BETWEEN 8 AND 17 THEN
        RAISE_APPLICATION_ERROR(-20600, 'Transaction rejected for security reasons');
      END IF;
    END;
    /
  • Oracle: writing to a file

    Oracle has a package that allows you to write to a file. Oracle uses the concept of a directory (here “External”) that acts as a logical description of a directory. One of the properties of such directory is the physical location.

    That file can be opened, written to and closed. Subsequent programme provides an example.

    create or replace PROCEDURE writeEmployee as
      TextRecord   VARCHAR2(2000);
      TextFile     utl_file.FILE_TYPE;
      CURSOR EmployeeList IS
         SELECT EName, Sal, Comm
         FROM emp e
         ORDER BY EName;
      TYPE EmployeeRecordType IS RECORD
         (EmpName   emp.EName%TYPE,
          EmpSalary emp.Sal%TYPE,
          Commission  emp.Comm%TYPE);
      EmployeeRecord   EmployeeRecordType;
    BEGIN 
      OPEN EmployeeList;
      TextFile := utl_file.fopen ('EXTERNAL', 'Employees.csv', 'w', 32767);
      LOOP
        FETCH EmployeeList INTO EmployeeRecord;
        EXIT WHEN EmployeeList%NOTFOUND;
        TextRecord := EmployeeRecord.EmpName || ',' ||
                      EmployeeRecord.EmpSalary  || ',' ||
                      EmployeeRecord.Commission;
        utl_file.put_line (TextFile, TextRecord);
      END LOOP;
      CLOSE EmployeeList;
      utl_file.fclose (TextFile);
    EXCEPTION
      WHEN OTHERS THEN
        dbms_output.put_line (sqlcode);
        dbms_output.put_line (sqlerrm);
    END; 
    /
  • Weak cursor in Oracle

    This programme shows you we may retrieve the results from a query. It works with a cursor that contains another cursor. The example below is a cursor that retrieves data from employee table, along with data from a cursor that is linked to the employee table. Doing so, we may add data to the employee data. Here some data on dependants are added. Likewise, we may add data on projects that employees worked on etc.

    As two cursors are used, we must start two loops: one loop that retrieves data on employee and a second loop that retrieves data on the dependants.

    We do not know upfront how the data are returned. Therefore a so-called weak cursor is used. This cursor definition does not return the type data that are returned.

    The code to undertake is:

    create or replace PROCEDURE FamilyWeakCursor AS 
      TYPE DepType IS REF CURSOR;
      DepCursor DepType;
      EmpLName    employee.LName%TYPE;
      EmpFName    employee.FName%TYPE;
      EmpRELATIONSHIP    dependent.RELATIONSHIP%TYPE;
      EmpDEPENDENT_NAME    dependent.DEPENDENT_NAME%TYPE;
      CURSOR EmpWork IS
        SELECT LName, FName, CURSOR(SELECT RELATIONSHIP, DEPENDENT_NAME
                                     FROM dependent d
                                      WHERE d.essn = e.ssn) AS DepCursor
    
        FROM employee e
        ORDER BY LName;   
    
    BEGIN
      OPEN EmpWork;
        LOOP
          FETCH EmpWork INTO EmpLName, EmpFName, DepCursor;
          EXIT WHEN EmpWork%NOTFOUND;
          dbms_output.put_line ('Processing here for ' || EmpLname||' ,' || EmpFname );      
          LOOP    
            FETCH DepCursor INTO EmpRELATIONSHIP, EmpDEPENDENT_NAME;      
            EXIT WHEN DepCursor%NOTFOUND;     
            dbms_output.put_line ('Processing here for ' || EmpLname||' ,' || EmpFname || ' and for dependant ' || EmpDEPENDENT_NAME||' (' ||EmpRELATIONSHIP || ')');        
          END LOOP;     
        END LOOP;
      CLOSE EmpWork;
    END;
    /