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.

Saturday, 25 February 2017

Analytic Functions in Oracle - III

In this post, we will cover RANK, DENSE_RANK and Top N Queries. Oracle 12c is used for all queries.

RANK as the name suggests ranks any measure in a query using sequential numbers starting from 1. If in the ranking process, a tie is encountered, then, the same rank is repeated for all values that tie and the next rank in sequence is used after skipping as many rank values as was repeated in the tie . Let us see that by means of an example. For starters, let us use the same hr.employees table used in the previous posts. We are interested only in the results of the below query:

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

The results returned are shown below:  








The query returns ten records. Let us now run the first query using RANK shown below:

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

The results returned are shown below:  












The results are as written above: a tie is seen at 17000, so there is a repeat of ranks for 17000 and at the next value of 12008, rank value 3 is skipped for one repeat of 17000 and a rank of 4 is returned. Same is true for the salary value 9000 where rank of 6 is skipped.

DENSE_RANK is similar to RANK except that in case a of tie, the rank values are not skipped. Let us replace RANK with DENSE_RANK in above query to see this contrast.

select employee_id, last_name, department_id, salary, dense_rank() over (order by salary desc) "SALARY DENSE RANK" from  hr.employees where employee_id <= 109;

The results returned are shown below: 











Results show that DENSE_RANK does not skip any values at all and ranks are repeated at ties. 

Let us add the partition keyword and see the results. The query using partition is show below:

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

The results returned are shown below:














The results show that the RANK function is applied department wise. The same can be tried using DENSE_RANK as shown below:

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

The results returned are shown below:












The results are clearly in line with our understanding of DENSE_RANK as is seen in the ranking of Lorentz.

Next, we will pass values to RANK and DENSE_RANK function as shown below. The results returned are the same as the results shown above.

select rank(24000) within group (order by salary desc) "RANK OF 24000" from hr.employees where employee_id <= 109;






select dense_rank(24000) within group (order by salary desc) "DENSE RANK OF 24000" from hr.employees where employee_id <= 109;





select rank(17000) within group (order by salary desc) "RANK OF 17000" from hr.employees where employee_id <= 109;






select dense_rank(17000) within group (order by salary desc) "DENSE RANK OF 17000" from hr.employees where employee_id <= 109;






select rank(9000) within group (order by salary desc) "RANK OF 9000" from hr.employees where employee_id <= 109; 



select dense_rank(9000) within group (order by salary desc) "DENSE RANK OF 9000" from hr.employees where employee_id <= 109;






If the value passed to RANK or DENSE_RANK function does not exist in the table, then it will return a result such that it fits into the ranking of the existing values in the table. Let us see the below two queries, one for RANK and another for DENSE_RANK:

select rank(16000) within group (order by salary desc) "RANK OF 16000" from hr.employees where employee_id <= 109;







select dense_rank(16000) within group (order by salary desc) "DENSE RANK OF 16000" from hr.employees where employee_id <= 109;



16000 does not exist in the table. So, it is neatly ranked as though it is in the table. The important think to note is that, no errors or nulls are returned.

Last part of this post is the Top N Queries. Such type of queries answer questions like what are top 5 salaries for employees with employee_id less than 109. The query for that question is shown below:

select employee_id, last_name, department_id, salary from hr.employees where employee_id <= 109 order by salary desc fetch first 5 rows only;

The results returned are shown below:









In the same manner, we can use percentage to indicate the number of records returned as shown below:

select employee_id, last_name, department_id, salary from hr.employees where employee_id <= 109 order by salary desc fetch first 50 percent rows only;

The results returned are the same as shown below:









We can ignore the top 2 salary values and then query for the next 5 salaries using OFFSET  as shown below:

select employee_id, last_name, department_id, salary from hr.employees where employee_id <= 109 order by salary desc offset 2 rows fetch first 5 rows only; 

The results returned are the same as shown below: