Saturday, January 23, 2016

Oracle 12c enhanced syntax for row-limiting (A.K.A Top-N queries)

Introduction

Prior to Oracle 12c we had to use the ROWNUM pseudo column in order to implement Top-N reporting. Following are few simple examples of Top-N queries:
  • Query the top 3 employees with the highest salaries
  • Query the first 2 employees who have joined the company

Using the ROWNUM pseudo column had worked well, however it had major disadvantages:
  • It's not a straight-forward syntax, especially if you need to implement query paging such as query the second block of the top 3 employees with the highest salaries.
  • It allows us specifying the Top-N rows but it doesn't allows specifying the Top-N percent (for example, query the top 25% percent of employees with the highest salaries.

In Oracle 12c, SQL SELECT syntax has been enhanced in order to address the 2 disadvantages with the ROWNUM pseudo column listed above. You can specify the number of rows or percentage of rows to return with the FETCH NEXT keywords. You can use the OFFSET keyword to specify that the returned rows begin with a row after the first row of the full result set. In the case of a negative OFFSET, the OFFSET value is treated as 0.

Demonstration

For the demonstration I will create a table of employees and populate it with 10 records:
SQL> CREATE TABLE EMP
  2  (
  3     id          NUMBER,
  4     name        VARCHAR2 (20),
  5     salary      NUMBER,
  6     hire_date   DATE,
  7     CONSTRAINT id_pk PRIMARY KEY (id)
  8  );
Table created.

SQL> insert into EMP value values (1, 'DAVID', 8500, '07-APR-15');
1 row created.

SQL> insert into EMP value values (2, 'JOHN', 10000, '17-MAR-15');
1 row created.

SQL> insert into EMP value values (3, 'JANE', 13500, '23-DEC-15');
1 row created.

SQL> insert into EMP value values (4, 'DAN', 15000, '02-JAN-15');
1 row created.

SQL> insert into EMP value values (5, 'RACHEL', 19000, '20-FEB-15');
1 row created.

SQL> insert into EMP value values (6, 'BRAD', 20000, '25-JUN-15');
1 row created.

SQL> insert into EMP value values (7, 'TIM', 15000, '16-MAR-15');
1 row created.

SQL> insert into EMP value values (8, 'KELLY', 9000, '28-APR-15');
1 row created.

SQL> insert into EMP value values (9, 'NICK', 7500, '04-FEB-15');
1 row created.

SQL> insert into EMP value values (10, 'ERIK', 6000, '09-JUL-15');
1 row created.

SQL> commit;
Commit complete.

SQL> select * from EMP;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
         1 DAVID                      8500 07-APR-15
         2 JOHN                      10000 17-MAR-15
         3 JANE                      13500 23-DEC-15
         4 DAN                       15000 02-JAN-15
         5 RACHEL                    19000 20-FEB-15
         6 BRAD                      20000 25-JUN-15
         7 TIM                       15000 16-MAR-15
         8 KELLY                      9000 28-APR-15
         9 NICK                       7500 04-FEB-15
        10 ERIK                       6000 09-JUL-15
10 rows selected.

In my first example I will query the first 2 employees who have joined the company:
SQL>   select *
  2    from EMP
  3    ORDER BY hire_date
  4    FETCH FIRST 2 ROWS ONLY;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
         4 DAN                       15000 02-JAN-15
         9 NICK                       7500 04-FEB-15
Now, let's demonstrate a query paging via the OFFSET clause. In this example, I will query the second block of the first 2 employees who have joined the company:
SQL>   select *
  2    from EMP
  3    order by hire_date
  4    offset 2 rows fetch next 2 ROWS ONLY;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
         5 RACHEL                    19000 20-FEB-15
         7 TIM                       15000 16-MAR-15
Now, I will query the top 3 employees with the with the highest salaries:
SQL>   select *
  2    from EMP
  3    order by salary DESC
  4    fetch first 3 rows only;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
         6 BRAD                      20000 25-JUN-15
         5 RACHEL                    19000 20-FEB-15
         4 DAN                       15000 02-JAN-15
In my sample table there are 2 employees with the salary of 15000 : DAN and TIM, but because I used the "ONLY" clause it limited the output to be exactly 3 rows. By replacing the "ONLY" clause with the "WITH TIES" clause, it will diplay all the top-3 employees even if there is more than one employee with the 3rd highest salary , as follows:
SQL>   select *
  2    from EMP
  3    order by salary DESC
  4    fetch first 3 rows with ties;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
         6 BRAD                      20000 25-JUN-15
         5 RACHEL                    19000 20-FEB-15
         4 DAN                       15000 02-JAN-15
         7 TIM                       15000 16-MAR-15

In my last example I will demonstrate how to query the Top-N percent using the PERCENT clause. The following query retrieves the top 40% of employees with the lowest salary:
SQL>   select *
  2    from EMP
  3    order by salary
  4    fetch first 40 percent rows only;
        ID NAME                     SALARY HIRE_DATE
---------- -------------------- ---------- ---------
        10 ERIK                       6000 09-JUL-15
         9 NICK                       7500 04-FEB-15
         1 DAVID                      8500 07-APR-15
         8 KELLY                      9000 28-APR-15


Additional Notes

  • If you specify a negative OFFSET number, OFFSET is treated as 0. If you specify NULL or a number greater than or equal to the number of rows that are returned by the query, 0 rows are returned.​
  • The FIRST or NEXT keywords can be used interchangeably. They are provided for semantic clarity.
  • The ROW keyword and the ROWS keyword can be used interchangeably. They are provided for semantic clarity.

Summary

The new enhanced syntax for row-limiting is one of my favorite new features of Oracle 12c. It provides an extremely straight-forward syntax for implementing a Top-N and query paging instead of using less convenient syntax via the ROWNUM pseudo column as we used to do prior to Oracle 12c.

    Wednesday, January 20, 2016

    Help me spread the word about my sessions at COLLABORATE 16 IOUG event!

    Hi everyone,

    I'm very happy to update you that I got accepted to speak at the Independent Oracle Users Group (IOUG) COLLABORATE event in Las Vegas from April 10-14 at the Mandalay Bay Resort & Casino.

    I will be presenting 3 sessions:

    I hope to see you there!


    Tuesday, January 5, 2016

    How to view the history of your Pluggable Databases?

    Introduction

    Let's say you have a 12c container database with multiple pluggable databases. Some of the PDBs were created during the initial container database installation, some were cloned later and some were unplugged/plugged over the time.
    A question that can be raised is how to track the history of the PDBs?

    Solution

    Using CDB_PDB_HISTORY dictionary view, you can easily query the history of the PDBs and for each PDB you can see when it was created/cloned/plugged/unplugged and from which other PDB it was cloned from.

    Demonstration

    Following is a demonstration of the CDB_PDB_HISTORY from one of our Oracle 12c environments:
    SQL> select pdb_name, operation, op_timestamp, cloned_from_pdb_name from cdb_pdb_history order by 3;
    
    PDB_NAME   OPERATION        OP_TIMESTAMP         CLONED_FROM_PDB_NAME
    ---------- ---------------- -------------------- -------------------------
    PDBTEST    CREATE           12-MAR-2015 14:58:52 PDB$SEED
    PINIDB     CLONE            15-MAR-2015 15:00:07 PDBTEST
    PDBTEST    UNPLUG           05-JAN-2016 15:01:39
    PDBTEST    PLUG             05-JAN-2016 15:09:59 PDBTEST
    
    

    Following is an explanation for the this example:

    • The first PDB named PDBTEST was created in 12-MAR-2015 14:58:52 from the PDB$SEED (a system-supplied template PDB).
    • The second PDB named PINIDB was cloned  in 15-MAR-2015 15:00:07 from PDBTEST.
    • On 05-JAN-2016 15:01:39 PDBTEST has been unplugged.
    • On 05-JAN-2016 15:09:59 PDBTEST has been plugged into the container database.

    Summary

    The CDB_PDB_HISTORY view can be useful for investigating the history of your PDBs. 
    I hope you can find it useful in your Oracle 12c environments.

    Tuesday, December 29, 2015

    Oracle 12c Privilege Analysis

    Introduction

    In this post I'd like to demonstrate another new Oracle 12c security feature - Privilege Analysis. Using this feature, the DBA can easily understand which privileges are actually being used by users. Once the analysis has been completed, the DBA can revoke all of the unnecessary privileges/roles. This feature is only available for Enterprise Edition with Oracle Database Vault (extra cost option).

    How does it work?

    Oracle introduced a new package, DBMS_PRIVILEGE_CAPTURE which allows you to create a new privilege analysis policy, enable/disable it, generate the results of the analysis and drop the policy once the analysis is over and the policy is not needed anymore. In order to use the DBMS_PRIVILEGE_CAPTURE package you need to be grnted the CAPTURE_ADMIN role.

    Demonstration

    In order to create a new privilege analysis policy, use the following syntax:
    DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE(
       name              VARCHAR2, 
       description       VARCHAR2 DEFAULT NULL, 
       type              NUMBER DEFAULT DBMS_PRIVILEGE_CAPTURE.G_DATABASE, 
       roles             ROLE_NAME_LIST DEFAULT ROLE_NAME_LIST(), 
       condition         VARCHAR2 DEFAULT NULL);
    Let's start by creating a user named "pini" and grant him the DBA role. Afterwards, we'll create and enable a simple policy named "capture_pini_privs" that simply captures all the privileges used by user pini:
    SQL> create user pini identified by pini default tablespace users;
    User created.
    
    SQL> grant dba to pini;
    Grant succeeded.
    
    SQL> BEGIN
      2    DBMS_PRIVILEGE_CAPTURE.create_capture(
      3      name        => 'capture_pini_privs',
      4      type        => DBMS_PRIVILEGE_CAPTURE.g_context,
      5      condition   => 'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''PINI'''
      6    );
      7  END;
      8  /
    PL/SQL procedure successfully completed.
    
    SQL> EXECUTE DBMS_PRIVILEGE_CAPTURE.enable_capture('capture_pini_privs');
    PL/SQL procedure successfully completed.
    
    Explanation of the above code:

    - In line 3 I set the name of the policy to be "capture_pini_privs"
    - In line 4 I set the type to be DBMS_PRIVILEGE_CAPTURE.g_context to captrue privileges of the sessions defined in line 5
    - In line 5 I used SYS_CONTEXT to specify capture privileges for user "PINI" only

    After we have created the new policy we can verify it via DBA_PRIV_CAPTURES dictionary view that lists all the policies as follows:
    SQL> SELECT TYPE, enabled, context FROM DBA_PRIV_CAPTURES;
    
    TYPE             ENABLED    CONTEXT
    ---------------- ---------- --------------------------------------------------
    CONTEXT          Y          SYS_CONTEXT('USERENV', 'SESSION_USER') = 'PINI'
    

    Note that there are several other types that you can use (in line 4) like capturing privileges of the entire database users except of use SYS (using DBMS_PRIVILEGE_CAPTURE.G_DATABASE), or capturing the privileges of specific sessions with specific roles (DBMS_PRIVILEGE_CAPTURE.G_ROLE_AND_CONTEXT) which requires also to specify the "roles" parameter. You can read more about these options in the official documentation for the DBMS_PRIVILEGE_CAPTURE package.

    Now, after we have created and enabled to policy, the analysis period has been started.
    Next, let's connect with user pini and execute a few commands to test this feature:
    SQL> connect pini/pini
    Connected.
    
    SQL> create table EMP (id number, name varchar2(20), constraint id_pk PRIMARY KEY (id));
    Table created.
    
    SQL> insert into EMP values (1, 'DAVID');
    1 row created.
    
    SQL> commit;
    Commit complete.
    
    SQL> CREATE OR REPLACE FUNCTION return_num_of_emps
      2     RETURN NUMBER IS
      3     num_of_emps NUMBER;
      4     BEGIN
      5        select count(*)
      6        into num_of_emps
      7        from EMP;
      8        RETURN(num_of_emps);
      9      END;
     10  /
    Function created.
    
    SQL> select return_num_of_emps from dual;
    RETURN_NUM_OF_EMPS
    ------------------
                     1
    SQL> select instance_name from v$instance;
    INSTANCE_NAME
    ----------------
    o1264np
    
    SQL> select log_mode from v$database;
    LOG_MODE
    ------------
    NOARCHIVELOG
    Now, I will disable the capture policy and generate the report as follows:
    SQL> execute DBMS_PRIVILEGE_CAPTURE.DISABLE_CAPTURE('capture_pini_privs');
    PL/SQL procedure successfully completed.
    
    SQL> execute DBMS_PRIVILEGE_CAPTURE.generate_result('capture_pini_privs');
    PL/SQL procedure successfully completed.
    
    The output of the report will be printed to various dictionary views like DBA_USED_SYSPRIVS and DBA_USED_OBJPRIVS as you can see in the following demonstration:
    SQL> SELECT SYS_PRIV
      2    FROM DBA_USED_SYSPRIVS
      3   WHERE username = 'PINI';
    
    SYS_PRIV
    ---------------------------------------
    CREATE SESSION
    CREATE TABLE
    CREATE ANY INDEX
    CREATE PROCEDURE
    UNLIMITED TABLESPACE
    
    SQL> SELECT obj_priv, object_owner, object_name
      2    FROM DBA_USED_OBJPRIVS
      3   WHERE username = 'PINI';
    
    OBJ_PRIV                                 OBJECT_OWNER         OBJECT_NAME
    ---------------------------------------- -------------------- ----------------------------------------
    SELECT                                   SYS                  V_$INSTANCE
    SELECT                                   SYS                  V_$DATABASE
    

    Once the analysis has been completed, you can drop the policy. This step is optional and it's goal is to clean to policy-related information from the data-dictionary views. In order to do that use the following syntax:
    SQL> execute DBMS_PRIVILEGE_CAPTURE.DROP_CAPTURE ('capture_pini_privs');
    PL/SQL procedure successfully completed.
    


    Summary

    Granting minimum privileges for users is a security best practice, however, many DBAs are struggling with identifying which exact privileges are actually needed and which privileges are unnecessary - and therefore, should be revoked. This feature comes to solve this challenge. I would expect this useful security feature to be available for all Oracle Editions but unfortunately, it's only available for Enterprise Edition with Oracle Database Vault (extra cost option). 

    Monday, December 14, 2015

    Oracle Multiprocess and Multithreaded Architecture

    Introduction

    The Oracle process architecture of Windows operating system is a different process architecture comparing to Linux/Unix operating systems. On Windows, each Oracle instance has one single process that is multithreded, i.e. each background process is a thread within the single "father" process, therefore the "processes" tab in the the task manager will display only one "oracle.exe" process per each instance, as you can see in the following screenshot (taken from one of our Oracle environments):




























    On Linux/Unix on the other hand, each background process is a different OS process so by looking for all the processes you should expect to get a long list of Oracle processes, as you can see the following screenshot (taken from one of our Oracle on Linux environments):






















































    Oracle 12c Multiprocess and Multithreaded Architecture

    By default, the pre-12c Oracle process architecture remains the same in Oracle 12c. However, in Oracle 12c you can enable the multithreaded architecture on Unix/Linux that will cause Oracle processes on Linux/Unix to run as threads - similar to the process architecture on Windows. In order to do so, simply set the THREADED_EXECUTION initialization parameter to TRUE (default value is FALSE). This is a static parameter (SCOPE=SPFILE), therefore requires restarting the instance in order for the changes to take effect.

    Demonstration

    First, I will connect to one of our 12c Oracle Linux environments and set the THREADED_EXECUTION to be TRUE:
    SQL> alter system set THREADED_EXECUTION=true scope=spfile;
    System altered.
    
    SQL> shu immediate;
    Database closed.
    Database dismounted.
    ORACLE instance shut down.
    
    SQL> startup
    Total System Global Area 1073741824 bytes
    Fixed Size                  2932632 bytes
    Variable Size             692060264 bytes
    Database Buffers          373293056 bytes
    Redo Buffers                5455872 bytes
    Database mounted.
    Database opened.
    

    Now I will check how many Oracle processes I have on the Linux environment:













    As you can see, now there are much less processes than before. Most of the background processes now run as threads instead of processes but some of them might still run as operating system processes (like the PMON and the DB Writer processes).

    Important things to keep in mind

    • OS authentication is not allowed with the multithreaded architecture. If you will try to connect via an OS authentication (for example, by connecting with "/ AS SYSDBA") you will encounter "ORA-01017: invalid username/password; logon denied", therefore you must use a password file for connecting with a SYSDBA/SYSOPER user.
    • When the THREADED_EXECUTION parameter is set to TRUE, you must set the DEDICATED_THROUGH_BROKER_LISTENER parameter to ON in your listener.​ora file. When that parameter is set, the listener knows that it should not spawn an OS process when a connect request is received, instead it passes the request to the database so that a database thread is spawned and answers the connection.​ 
    • In RAC environments all nodes must have the same value for the THREADED_EXECUTION parameter.

    Summary

    In this post I've reviewed the process architecture in Linux/Unix vs. Windows and demonstrated the new 12c Multithreaded option. This feature can be useful in order to reduce the number of OS processes in scenarios where you have many Oracle instances on the same machine which may cause a higher overhead as a result of a very high number of OS processes.

    Useful Links