Monday, 20 March 2017

Analytic Functions in Oracle - VI

In this post, we will focus on pivoting operation in Oracle. Pivot operation in Oracle was introduced in 11g version

AS in earlier posts, we will use Pivoting operation in Oracle lets one to aggregate rows followed by rotating the rows into columns.  To get an idea, let us understand run below query:

select department_id, count(*) from hr.employees where department_id <= 40 group by department_id;

The results returned are shown below: 










We can rotate the values in department_id column to be column headers using PIVOT keyword. Let us run below query for starters that will be used in the PIVOT query.

select department_id from hr.employees  where department_id <= 40;

The results returned are shown below: 
















Now, let us use the PIVOT query as shown below:

select * from (select department_id from hr.employees where department_id <= 40) pivot (count(*) for department_id in (10,20,30,40));

The results returned are shown below: 






The results show that an aggregate, count, of the departments is calculated on the fly and then the values in the department column is rotated to be column headers.  The expression following PIVOT keyword can be understood in the following way:

(count(*) for department_id in (10,20,30,40))

COUNT(*) is the aggregated entity, and will appear as a row. department_id following the FOR keyword is the column header. Expression (10,20,30,40) following the IN clause filters the column appearing after FOR keyword, department_id in this case.

The filtering of the columns in the final result can be done in the values in the parenthesis after IN keyword as shown in below query:

 select * from (select department_id from hr.employees) pivot (count(*) for department_id in (10,20,30,40));

The results returned are shown below: 







The results are the same as before.

Let us now add one more column called salary instead of count aggregate. The original query for reference is shown below:

select department_id, sum(salary) from hr.employees where department_id <= 40 group by department_id order by department_id;

The results returned are shown below:








 
The query with PIVOT keyword is shown below:

select * from (select department_id, salary from hr.employees) pivot (sum(salary)  for department_id in (10,20,30,40));

The results returned are shown below: 






The results are as expected.

Next, we take a look at aliasing of the resulting column headers. As before, let us check the reference query first.

select department_id, sum(salary) "Sum of Salary" from hr.employees where department_id <= 40 group by department_id order by department_id;

The results returned are shown below:










We see the salary column is aliased as expected.

The first query we see with PIVOT keyword is shown below:

select * from (select department_id, salary from hr.employees) pivot (sum(salary) "Sum of Salary" for department_id in (10,20,30,40));

The results returned are shown below: 





We see column header is a concatenation of the aggregate alias and the elements in IN clause. The next query has aliases for the elements in the IN clause as shown below:

select * from (select department_id, salary from hr.employees) pivot (sum(salary) "Sum of Salary" for department_id in (10 "A" ,20 "B",30 "C",40 "D") );

The results returned are shown below: 






Now, we see that the column header is a concatenation of the aggregate alias and the aliases in IN clause. Before we invoke the next query, let us run the reference that shows two aggregates:

select department_id, count(*), sum(salary) "Sum of Salary" from hr.employees where department_id <= 40 group by department_id order by department_id;

The results returned are shown below:









Now, we will replicate the above result but with the pivot operation with these two aggregates and also having aliases.

select * from (select department_id,salary from hr.employees ) pivot (count(*) as cnt,sum(salary) as sal for department_id in (10,20,30,40));

The results returned are shown below:





 The results are in line with our expectation that the aggregate alternate each other starting with COUNT aggregate.

The way to filter the results based on input in IN clause is shown in the next few examples. To get an idea, let us understand run below query:

select department_id, sum(salary) "Sum of Salary" from hr.employees where department_id <= 40 group by department_id order by department_id;

The results returned are shown below:










Let us run below query that filters department_id as shown below:

select * from (select department_id, salary from hr.employees) pivot (sum(salary) "Sum of Salary" for department_id in (select department_id from hr.employees where department_id <= 40));

We get below error:

ORA-00936: missing expression
00936. 00000 -  "missing expression"
*Cause:   
*Action:
Error at Line: 42 Column: 121


But, adding XML keyword after PIVOT keyword solves the issue as shown below:

select * from (select department_id, salary from hr.employees) pivot  xml (sum(salary) "Sum of Salary" for department_id in (select department_id from hr.employees where department_id <= 40));

The results returned are shown below: 








We get a result with xml tags that shows the filtered result. Opening the result saved as a .xml file, we see the below result filtered by department_id:



















Lastly, we see the UNPIVOT operation. It is the reverse of the PIVOT operation as shown in below query:

select value_type department_id,value cnt
from
(
    (
      select * from (select department_id from hr.employees)
pivot (count(*) for department_id in (10 "10",20 "20",30  "30",40  "40"))
    )
    unpivot
    (
        value
        for value_type in
            ("10","20","30","40")
    )
);

  
The results returned are shown below: 









The results are the same as returned by the first query in this blog.This concludes the post on pivoting in Oracle.

Monday, 13 March 2017

Analytic Functions in Oracle - V

The fifth post in this series of Analytic Functions in Oracle takes a look at Regular Expressions as is dealt by Oracle. Regular Expressions are a powerful feature in all languages and Oracle adding it to its collection of features should not come as a surprise

A Regular Expression is a special text used as a search pattern. In other words, a Regular Expression describes a pattern that can be used for searching text in strings. They are specified as a combination of Metacharacters and Literals. These are described below:

1) Metacharacters: These are operators like *,?,[], etc, that are used to create the algorithm to be used in the search process

2) Literals: These are the actual characters or content that are searched for

Oracle has the following functions to support Regular Expressions: REGEXP_LIKE, REGEXP_REPLACE, REGEXP_INSTR, REGEXP_SUBSTR, and REGEXP_COUNT. We will see examples of these in a series of queries

We will use 12c sample schema for demonstrating the usage of these functions. In the first query, we will use REGEXP_LIKE as seen in the example below:

Use of '.':

select first_name, last_name from hr.employees where regexp_like (last_name, 'A....n');

The results returned are shown below: 






The '.' metacharacter matches any character. So, since there are 4 of those, the query matches any word that starts with A and ends with n and has 4 characters in between.

Use of '+':

select first_name, last_name from hr.employees where regexp_like (last_name, '(rr)+');

The results returned are shown below: 








'+' matches one or more of the preceding subexpression. 

Use of '?':

select first_name, last_name from hr.employees where regexp_like (last_name, '(at?a)');

The results returned are shown below: 







'?' matches zero or one of the preceding subexpression. De Haan is selected because there is no t in between in aa. Pataballa is selected because there is one occurrence of t between aa.

Use of '*':

select first_name, last_name from hr.employees where regexp_like (last_name, 'al*a');


The results returned are shown below: 
 





'*' matches zero or more of the preceding subexpression.

Use of '^':

select last_name from hr.employees  where regexp_like (last_name, '^K(*)');

The results returned are shown below:











This query returns all employees starting with letter, K.

select first_name, last_name from hr.employees where regexp_like (last_name, '^Ma');

The results returned are shown below:











This query returns all employees starting with letters, Ma.

Use of '{}':

select first_name, last_name from hr.employees where regexp_like (last_name, 'l{2}');

The results returned are shown below:


















This query returns last_name containing l character two times.

select first_name, last_name from hr.employees where regexp_like (last_name, 'a{2,}');

The results returned are shown below:





This query returns all employees having last_names having a two times or more.

select first_name, last_name from hr.employees where regexp_like (last_name, 'h{1,2}');

The results returned are shown below:



















The last query returns all employees having last_names having at least one h but not more than two h.

Use of '[]':

select first_name, last_name from hr.employees where regexp_like (last_name, '[zx]');

The results returned are shown below:










The last query returns first_name, last_name from all employees having last_name containing x, or z.

Use of '/s':

select first_name, last_name from hr.employees where regexp_like (last_name, '(\s)');

The results returned are shown below: 






The last query returns first_name, last_name from all employees having last_name containing a space.

Use of '\1':

select last_name from hr.employees where regexp_like (last_name, '([aeiou])\1', 'i');

The results returned are shown below: 













The last query returns last_name containing two consecutive characters mentioned in []. i means the matching is case insensitive.

Use of '$':

select last_name from hr.employees where regexp_like (last_name, 'z$', 'i');

The results returned are shown below: 








The last query returns last_name ending with z.

Use of '^$':

select last_name from hr.employees where regexp_like (last_name, '^K[a-z]+r$');

The results returned are shown below:






The last query returns last_name starting with K and ending in r.

Use of '[:blank:]':

select last_name from hr.employees where regexp_like (last_name, '[[:blank:]]');

 The results returned are shown below:





The last query returns last_name from all employees having last_name containing a blank.

Use of '[:digit:]':

select last_name,salary from hr.employees where regexp_like (salary, '[[:digit:]]{5}');

The results returned are shown below: 




















The last query returns last_name, salary of all employees having currency in 5 digits.

Use of '[[=n=]]':

select regexp_substr('Danke schön', '[[=o=]]') from dual;

The results returned are shown below: 







The last query uses REGEX_SUBSTR to extract any o in the input string.

select regexp_substr('El Niño', '[[=n=]]',1,1), regexp_substr('El Niño', '[[=n=]]',1,2) from dual;

The results returned are shown below: 






The last query uses REGEX_SUBSTR to extract any n in the input string. In the first expression, the search starts at first position and locates the first instance of  n and the second expression locates the second instance of n.

Use of '\w':

select regexp_substr('A@6', '\w',1,2) from dual;

The results returned are shown below: 







The last query returns the first word character starting from the first position and is a second instance.

Use of '\W':

select regexp_substr('test@test', '\W') from dual;

The results returned are shown below:







This query returns first non-word character in the input expression. 

Use of REGEXP_REPLACE:

select last_name, phone_number, regexp_replace(phone_number, '([/.])', ' ') as modified_phone_number from  hr.employees where regexp_like (last_name, '^K(*)') ;

The results returned are shown below: 









REGEXP_REPLACE function replaces '.' character in phone_number with a space character.

Use of REGEXP_INSTR:

select regexp_instr('Copyright ©  2005, 2012 Oracle.All Rights Reserved.', '[^[:alpha:]]') from dual;

The results returned are shown below: 






REGEXP_INSTR returns the position of the search criteria, a non alphanumeric character, in the input string.

Use of REGEXP_COUNT:

select last_name, regexp_count(last_name, '[A-z]'), phone_number,  regexp_count(phone_number, '[0-9]{3}')  from hr.employees where regexp_like (last_name, '^K(*)');

The results returned are shown below: 








REGEXP_COUNT gives the count based on inputs. In the first expression, REGEXP_COUNT returns the number of alpha characters in the last name and in the second expression, REGEXP_COUNT returns the number of three continuous numbers.

This concludes the post on Regular Expressions in Oracle.

Thursday, 2 March 2017

Analytic Functions in Oracle - IV

Three functions LAG, LEAD and LISTAGG are covered in this post. Again, Oracle 12c is used for all queries and we will use the results of the below query to understand these three functions:

select * from hr.employees where employee_id <= 109 order by salary desc;

The results returned are shown below:  


 





All the three functions are dependent on the order of the rows. If the order of the rows are changed, then, the values returned by these functions also will change as we will see in the queries shortly. LAG and LEAD functions return values from previous of following rows. The offset determines the row that is selected from which the value will be fetched. If no offset is specified, then, value from the immediate previous or immediate following row depending on whether LAG or LEAD function is used, respectively. If no value is available because previous row or next row is non-existent, then NULL, is returned. To avoid NULL values being returned, we can specify default value so that a meaningful result is returned.

As an example, let us run below query:

select employee_id, last_name, hire_date, department_id, salary, lag(salary) over (order by salary desc) "PREVIOUS SALARY" from hr.employees where employee_id <= 109;

The results returned are shown below: 










The second row and further rows correctly carry the salary from the previous row. Two things are to be noted. The first row has NULL for previous salary as there there is no previous row from which salary can be fetched. NULL value is returned as we have not set a default value to LAG function.  Below query corrects both the issues where 0 is returned instead of NULL:

select employee_id, last_name, hire_date, department_id, salary, lag(salary,1,0) over (order by salary desc) "PREVIOUS SALARY" from hr.employees where employee_id <= 109;

The results returned are shown below:  










If, however, instead of 1 as offset, we use 0 with no default for NULL value as shown below, the PREVIOUS SALARY column shows the current salary. This is only to be expected.

select employee_id, last_name, hire_date, department_id, salary, lag(salary,0) over (order by salary desc) "PREVIOUS SALARY" from hr.employees where employee_id <= 109;

The results returned are shown below: 











The next query shows a offset value of 2 using LEAD function but with a different sorting on order.

select employee_id, last_name, hire_date, department_id, salary, lead(salary,2,0) over (order by salary) "FOLLOWING SALARY" from hr.employees where employee_id <= 109;

The results returned are shown below: 











Finally, we introduce the PARTITION keyword in the clause following OVER as shown below:

select employee_id, last_name, hire_date, department_id, salary, lag(salary) over (partition by department_id order by salary desc) "PREVIOUS SALARY" from hr.employees where employee_id <= 109;

The results returned are shown below: 











The results are neatly partitioned by department_id. 

Lastly, we take a look at the LISTAGG function. This function aggregates values in a column into a list based on a grouping, say, department_id. We can specify the delimiter for the separation of the values in the list. In the example shown below, half the salary is the bonus and two delimiters have been used: ":" for last_name and "-" for bonus.

select department_id, listagg(last_name, ':') within group (order by last_name desc) as "LIST OF EMPLOYEES",listagg(salary/2, '-') within group (order by last_name desc) as "LIST OF BONUS"
from hr.employees where employee_id <= 109 group by department_id;


The results returned are shown below: 







This concludes this post on the functions LAG, LEAD and LISTAGG.