Category: nice to know

  • Oracle Aggregate and analytic functions

    We all know aggregate functions in Oracle. Let me provide a simple example to recap what the aggregate function is. Let us firse this SQL on a 107 record table:

    select department_id, listagg( first_name,'-') within group (order by hire_date) from employees group by department_id;

    The result is a 12 record outcome, one record for each department:

    One could be interested to combine this aggregate with the original data. One then calls for a so-called analytical function. The corresponding SQL is:

    select department_id, first_name, listagg( first_name,'-') within group (order by hire_date)  over (partition  by department_id) from employees;

    The result is a 107 record outcome whereby aggregates are mixed with the original records:

    A similar code can be used to interlace grouping results (as a sum) with the original records. The code is:

    select  department_id, salary, sum( salary)   over (partition  by department_id) from employees;

    and the outcome:

  • Inserting a BLOB

    Inserting a BLOB in Oracle is slightly different from inserting from inserting a value in an Oracle database. We first have to create a location with n empty BLOB. After that the BLOB can be inserted. In a PL/SQL programme:

    
    create or replace PROCEDURE UPLOAD_FILE_TO_DATABASE(p_dir_name varchar2,p_file_name varchar2,p_file_desc varchar2 default null)
    AS
        L_BLOB  BLOB;
        L_BFILE  BFILE := BFILENAME(p_dir_name, p_file_name);
    BEGIN
        -- Insert a reacord with empty blog
        INSERT INTO MY_FILE_TABLE(nummer,FILE_NAME, FILE_LOB,DESCRIPTION)
            VALUES (file_no_seq.nextval,p_file_name, empty_blob(),p_file_desc)
            RETURNING FILE_LOB INTO L_BLOB;-- Open the bfile locator 
    DBMS_LOB.OPEN(L_BFILE, DBMS_LOB.LOB_READONLY);
    -- Open the blob locator to add the file 
    DBMS_LOB.OPEN(L_BLOB, DBMS_LOB.LOB_READWRITE);
    -- Add the file to blob locator
    DBMS_LOB.LOADFROMFILE(DEST_LOB => L_BLOB,
                          SRC_LOB  => L_BFILE,
                          AMOUNT   => DBMS_LOB.GETLENGTH(L_BFILE));
    -- Close the lob locators
    DBMS_LOB.CLOSE(L_BLOB);
    DBMS_LOB.CLOSE(L_BFILE);
    COMMIT;
    END UPLOAD_FILE_TO_DATABASE;

    which call be invoked by (example) exec UPLOAD_FILE_TO_DATABASE(‘TEMP’,’2019-11-15 12.46.30.mov’,’Nora’);

    Likewise, downloading a BLOB is done via:

    create or replace procedure download_file_from_database( p_file_number number)
    is
        l_file           utl_file.file_type;    
        l_buffer_data    raw(32767);            
        l_byte_amount    binary_integer := 32767;  
        l_position       integer        := 1;   
        l_blob           blob;                 
        l_blob_length    integer;              
        l_file_name      varchar2(250);       
    begin
      -- fetch the blob content from table into variable
      select file_lob,
             file_name
      into l_blob,
           l_file_name
      from hr.my_file_table
      where nummer  = p_file_number;
    -- compute the length of blob content
      l_blob_length   := dbms_lob.getlength(l_blob);
      l_position      := 1;
    -- open the destination file.
      l_file := utl_file.fopen('EXTERNORA',l_file_name,'wb', l_byte_amount); 
    -- read chunks of the blob and write them to the file
    -- until complete.
    while l_position < l_blob_length
    loop
    dbms_lob.read(l_blob, l_byte_amount, l_position, l_buffer_data);
    utl_file.put_raw(l_file, l_buffer_data, true);
    l_position := l_position + l_byte_amount;
    end loop;
    -- close the file.
    utl_file.fclose(l_file);
     exception
    when others then
    -- if anything goes wrong, then close the file.
    if utl_file.is_open(l_file) then
    utl_file.fclose(l_file);
    end if;
    raise;
    end download_file_from_database;

    Al this download is invoked via: exec DOWNLOAD_FILE_FROM_DATABASE(5);

    An alternative way is to store data directly into the database via:

    insert into my_file_table(FILE_NAME, FILE_LOB, DESCRIPTION, NUMMER) values ('prut', utl_raw.cast_to_raw('some magic here'), 'onzin',6);
    
    followed by
    
    exec DOWNLOAD_FILE_FROM_DATABASE(6);

    The text “some magic here” is then shown as being inserted into file “prut” that is stored in the database.

  • Oracle numerical data

    Numbers can be stored in Oracle according to different formats. On one hand, we have the American way, whereby numbers are stored with a dot (.) as decimal indicator. On the other hand, we have a comma (,) as decimal indicator. Let me provide my own Oracle instance.

    I have the following language settings:

    select * from nls_session_parameters;

    which provides:

    NLS_LANGUAGE    ENGLISH
    NLS_TERRITORY AMERICA
    NLS_NUMERIC_CHARACTERS .,

    This means that numbers are interpreted with a dot (.) as decimal indicator. I created a small table with numbers that shows this dot:

    It is possible to change the settings for a session. To that end, we fire next command:

    ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

    To check if numbers are now interpreted as having as decimal indicator being a comma, we try:

    insert into nummer(getal) values('1,45');

    This looks successful. To check if ‘1,45’ is really inserted, we display the data:

    It is also possible to change the settings that determine the decimal point. These settings are derived from the computer one is working. On a windows machine, one may create a setting in the environmental variables:

    A variable NLS_LANG either exists or must be created. On my machine, it is AMERICAN_AMERICA.WE8MSWIN1252.

    Let us change this to DUTCH_THE NETHERLANDS.WE8MSWIN1252

    It is also possible to set this variable in the registry:

    This is done. Then the machine is restarted. After a restart, we check if the comma is used as decimal separator. This is the indeed the case:

  • Copying data with data pump

    Oracle has a brilliant feature to export / import data at great speed. The trick is to use the data pump facility. Let us first introduce the export via data pump.

    We may export data via data pump as:

    CREATE TABLE stu_details_ext
    ORGANIZATION EXTERNAL
    ( TYPE ORACLE_DATAPUMP
    DEFAULT DIRECTORY EXTERNORA
    LOCATION ('stu_details_ext_table.dmp')
    )
    AS SELECT * FROM nationaliteit;

    Note that two items are created: a new table with the original details, along with a file that is stored in an external directory.

    Subsequently, the file can be read via:

    CREATE TABLE stu_details_ext_table2
    ("COLUMN1" VARCHAR2(26 BYTE), 
        "COLUMN2" VARCHAR2(128 BYTE), 
        "COLUMN3" NUMBER(38,0), 
        "COLUMN4" NUMBER(38,0), 
        "COLUMN5" VARCHAR2(26 BYTE))
    ORGANIZATION EXTERNAL
    (
    TYPE ORACLE_DATAPUMP
    DEFAULT DIRECTORY EXTERNORA LOCATION ('STU_DETAILS_EXT_TABLE.DMP')
    );

    Now, the data are read from the dump file with a specification that is derived from the original table.

  • Take latest values

    The situation is as follows. We have a table with records that are added over time. The request is to produce a resultset that only contains values that are added latest.

    Let me first show the table:

    CREATE TABLE "RELATION_VALUES" 
    ( "RELATION_ID" NUMBER,
    "STARTDATE" DATE,
    "VALUE" NUMBER
    ) ;
    Insert into RELATION_VALUES (RELATION_ID,STARTDATE,VALUE) values ('1',to_date('11-FEB-2019','DD-MON-YYYY'),'80');
    Insert into RELATION_VALUES (RELATION_ID,STARTDATE,VALUE) values ('2',to_date('12-FEB-2019','DD-MON-YYYY'),'60');
    Insert into RELATION_VALUES (RELATION_ID,STARTDATE,VALUE) values ('2',to_date('14-FEB-2019','DD-MON-YYYY'),'70');
    Insert into RELATION_VALUES (RELATION_ID,STARTDATE,VALUE) values ('1',to_date('14-FEB-2019','DD-MON-YYYY'),'50');
    Insert into RELATION_VALUES (RELATION_ID,STARTDATE,VALUE) values ('2',to_date('15-FEB-2019','DD-MON-YYYY'),'80');

    For relation_id =1 we see that over time the values 80, 50 are added.

    Similarly, for relation_id=2, we see that over time the values 60, 70, 80 are added.

    We would like to see a report that only contains the latest values. That implies we would like to see 50 and 80 only for relation_id 1 and 2 respectively.

    The query to use is:

    select 
    relation_id
    , max(value) KEEP(DENSE_RANK last ORDER BY "STARTDATE" ASC) as value
    from relation_values
    group by relation_id;

    The result is:

  • The ORACLE_HOME

    Oracle needs to have a set of context variables that allow Oracle to know where the programmes are located. Upon installation, you have to check if these variabled are set. If not, you have to set them yourself. In linux, such variables can ne set in the .bash_profile file that is stored as a file in the home directory of the oracle user. This file looks like:

    export ORACLE_HOSTNAME=localhost.domain
    export ORACLE_UNQNAME=ORCL
    export ORACLE_BASE=/orasoft
    export ORACLE_HOME=/orasoft
    export ORACLE_SID=orcl
    PATH=$PATH:$HOME/bin
    export PATH=$ORACLE_HOME/bin:$PATH

    The hostname is a name of the server that can also be stored in the hosts file. This then allows the system to refer to a certain IP number that is connected to the server.

    The oracle_sid is the name that is also used when one uses the tnsping command or when someone wants to set up a connection to oracle.

  • SQL in steps

    Let us assume we have a request to show results from a query that is too massive to run on-line. Let us also assume that we may distinguish in this query a series on countries / persons that must be run.

    In pseudo code, we have the situation that we may have to run: select * from complicated that could be translated into something like: for employees select * from lesscomplicated(employee).

    This can be solved in a PLSQL programme that contains a LOOP. Two possible solutions are given below:

    create or replace PROCEDURE FORLOOP AS
    CURSOR c1 IS SELECT * FROM HR.EMPLOYEES;
    i NUMBER:= 0;
    v_totalName varchar2(80);
    BEGIN
    FOR e_rec IN c1 LOOP
    i:= i+1;
    select DEPARTMENTS.department_name into v_totalName from HR.DEPARTMENTS where e_rec.department_id = DEPARTMENTS.department_id;
    dbms_output.put_line(i||chr(9)||e_rec.EMPLOYEE_ID||chr(9)||e_rec.LAST_NAME||chr(9)|| v_totalName);
    END LOOP;
    END;

    The idea is that we have a series of employees. For each of these employees, we have a simple query for one employee. This simple query for one employee runs fast. The loop guarantees that all employees are considered and all results are returned. A

    An alternative programme is:

    create or replace PROCEDURE FORLOOP AS
    CURSOR c1 IS SELECT * FROM HR.EMPLOYEES;
    e_rec c1%ROWTYPE;
    i NUMBER:= 0;
    v_totalName varchar2(80);
    BEGIN
    OPEN c1;
    i:=0;
    LOOP
    FETCH c1 into e_rec;
    EXIT WHEN c1%NOTFOUND;
    i:= i+1;
    select DEPARTMENTS.department_name into v_totalName from HR.DEPARTMENTS where e_rec.department_id = DEPARTMENTS.department_id;
    dbms_output.put_line(i||chr(9)||e_rec.EMPLOYEE_ID||chr(9)||e_rec.LAST_NAME||chr(9)|| v_totalName);
    END LOOP;
    END;
  • Writing content from Oracle

    This note provides a PL/SQL programme that writes the the content of a table to a file. It also uses a steering table (emp_ids) that contains a series of ids that can be used in a susequent query from which the content can be generated.

    Let me first provide the code:

    create or replace PROCEDURE print_emp_name_dpmt AS
    CURSOR id_cur
    IS SELECT distinct department_id FROM HR.emp_ids;
    emp_rec id_cur%ROWTYPE;
    CURSOR id_dpt
    IS SELECT employee_id, first_name FROM employees WHERE department_id = emp_rec.department_id;
    dpt_rec id_dpt%ROWTYPE;
    BEGIN
    OPEN id_cur;
    LOOP
    FETCH id_cur INTO emp_rec;
    EXIT WHEN id_cur%NOTFOUND;
    OPEN id_dpt;
    LOOP
    FETCH id_dpt INTO dpt_rec;
    EXIT WHEN id_dpt%NOTFOUND;
    dbms_output.put_line('The employee ' || dpt_rec.first_name ||';'||emp_rec.department_id||';'||dpt_rec.employee_id);
    END LOOP;
    CLOSE id_dpt;
    END LOOP;
    END;

    I created two cursors. One cursor contains the query outcomes from the steering table. A second cursor contains the outcomes from a query that must be written to a file.

    The two cursors are interwoven in two loops. Each loop fetches a record from a query. In the centre, the results are written.

    If one executes this PL/SQL procedure in SQL plus with a spool on-command, one captures the results.

  • Data miner in Oracle

    I have played a bit with Oracle data miner. This feature is available in the enterprise edition of Oracle version 11 or above. It can be accessed from SQL developer. Before using the feature, one must first set up a user. This can be done with:

    CREATE USER dmuser IDENTIFIED BY dmpassword
    DEFAULT TABLESPACE users
    TEMPORARY TABLESPACE temp
    QUOTA UNLIMITED ON users;
    Commit;
    GRANT CREATE JOB TO dmuser;
    GRANT CREATE MINING MODEL TO dmuser;
    GRANT CREATE PROCEDURE TO dmuser;
    GRANT CREATE SEQUENCE TO dmuser;
    GRANT CREATE SESSION TO dmuser;
    GRANT CREATE SYNONYM TO dmuser;
    GRANT CREATE TABLE TO dmuser;
    GRANT CREATE TYPE TO dmuser;
    GRANT CREATE VIEW TO dmuser;

    Once this user is created, one must set up a connection with the dmuser. This connection is used in the data miner widget. It looks like:

    Note that we have opened the data miner widget. And that we have used the connection with the dmuser. Moreover, upon the first usage, we have to set a repository.

    Each analysis is done within a project and a workflow. Within that workflow, different steps can be defined. The most logical step that is used as a start is a “Data Source”. Within that data source, we may define a table that exists on Oracle.

    After that, we may define one or more steps that use such data source. In the example above, we explore the data and we undertake a regression.

    It is interesting to see that most settings have a default value that allows to get the procedure running quickly. With the regression, I played with two different settings.

    The first setting was expliciting indicating the input variables:

    Whereas as the second setting was related to the number of observations. This can be steared with the Build – Properties. As a standard, only a subset is included in the population. One may like to include all observations to improve the quality of the estimations.

    Running was pretty quick. I compared the outcomes to the regression estimates from another programme to have a check.

    All in all, I was quite pleased with this feature. I could imagine that this tool set offers enough for an a information department. Moreover, it is really easy to use. Despite its simpleness, it offers regression, cluster analysis and some text analysis.

  • Adding information

    Today, I struggled a bit with a simple situation. I had a table with a primary key and an additional field that was partially filled. I also had a secondary table with a key and data were to be loaded in the first table.

    In a scheme, the situation looked like:

    loading additional data

    In this example we have a table A with a primary key having values 1,2,3,4,5 with an additional field that is partially field. With key=3,4,5, we have no value. This value is to be loaded from another table that has key 3,4,5 and a field with values.

    In code, we have:

    CREATE TABLE "VULDOEL" 
    ( "I" NUMBER,
    "NAAM" CHAR(10)
    ) ;
    REM INSERTING into VULDOEL
    SET DEFINE OFF;
    Insert into VULDOEL (I,NAAM) values ('1','tom ');
    Insert into VULDOEL (I,NAAM) values ('2','ine ');
    Insert into VULDOEL (I,NAAM) values ('3',null);
    Insert into VULDOEL (I,NAAM) values ('4',null);
    Insert into VULDOEL (I,NAAM) values ('5',null);
    CREATE TABLE "BIJDRAGE" 
    ( "I" NUMBER,
    "NAAM" CHAR(10)
    )
    REM INSERTING into BIJDRAGE
    SET DEFINE OFF;
    Insert into BIJDRAGE (I,NAAM) values ('3','Paula ');
    Insert into BIJDRAGE (I,NAAM) values ('4','Stella ');
    Insert into BIJDRAGE (I,NAAM) values ('5','Bart ');

    The solution to load the missing information is:

    update vuldoel A 
    set A.naam = (select B.naam from bijdrage B where B.I = A.I)
    where exists (select B.I from bijdrage B where A.I=B.I);
    commit;