39
Advanced Functions in PL/SQL

Advanced functions in PL SQL

Embed Size (px)

Citation preview

Advanced Functions in PL/SQL

TitlesAnalytic Functions

LISTAGG Function

TRANSLATE Function

REGEXP_LIKE Condition

REGEXP_COUNT Function

COALESCE Function

EXTRACT Function

ADD_MONTHS Function

INITCAP Function

INSTR Function

GREATEST Function

2/39

Analytic Functions• It is true that whatever an analytic function does can be done by native SQL, with join

and sub-queries. But the same routine done by analytic function is always faster, or at least as fast.

• Syntaxanalytic_function([ arguments ]) OVER (analytic_clause)

analytic_clause:

[ query_partition_clause ] [ order_by_clause [ windowing_clause ] ]

• An aggregate function aggregates data from several rows into a single result row.

3/39

How are analytic functions different from group or aggregate functions?

Query-1 returns departments and their employee count. Most importantly it groups the records into departments in accordance with the GROUP BY clause. As such any non-"group by" column is not allowed in the select clause.

Query-2 Though analytic functions give aggregate result they do not group the result set. They return the group value multiple times with each record. As such any other non-"group by" column or expression can be present in the select clause.

4/39

How are analytic functions different from group or aggregate functions?

Analytic functions are computed after all joins, WHERE clause, GROUP BY and HAVING are computed on the query. The main ORDER BY clause of the query operates after the analytic functions. So analytic functions can only appear in the select list and in the main ORDER BY clause of the query.In absence of any PARTITION or <window_clause> inside the OVER( ) portion, the function acts on entire record set returned by the where clause.

5/39

Analytic Functions(order-by-clause)• The order_by_clause is used to order rows, or siblings, within a partition. So if an

analytic function is sensitive to the order of the siblings in a partition you should include an order_by_clause.

• ORDER BY <sql_expr> [ASC or DESC] NULLS [FIRST or LAST]

• The functions SUM, COUNT, AVG, MIN, MAX are the common analytic functions the result of which does not depend on the order of the records.

• Functions like LEAD, LAG, RANK, DENSE_RANK, ROW_NUMBER, FIRST, FIRST VALUE, LAST, LAST VALUE depends on order of records.

6/39

ROW_NUMBER, RANK and DENSE_RANK

All the above three functions assign integer values to the rows depending on their order.

ROW_NUMBER( ) gives a running serial number to a partition of records. It is very useful in reporting, especially in places where different partitions have their own serial numbers.

7/39

ROW_NUMBER, RANK and DENSE_RANK

RANK and DENSE_RANK both provide rank to the records based on some column value or expression. In case of a tie of 2 records at position N, RANK declares 2 positions N and skips position N+1 and gives position N+2 to the next record. While DENSE_RANK declares 2 positions N but does not skip position N+1.

8/39

LEAD and LAG

LEAD has the ability to compute an expression on the next rows (rows which are going to come after the current row) and return the value to the current row.

• Syntax

LEAD (<sql_expr>, <offset>, <default>) OVER (<analytic_clause>)

<sql_expr> is the expression to compute from the leading row.<offset> is the index of the leading row relative to the current row.<offset> is a positive integer with default 1.<default> is the value to return if the <offset> points to a row outside the partition range.

The syntax of LAG is similar except that the offset for LAG goes into the previous rows.

9/39

LEAD and LAG

10/39

FIRST VALUE and LAST VALUE function

• SyntaxFIRST_VALUE(<sql_expr>) OVER (<analytic_clause>)

The FIRST_VALUE analytic function picks the first record from the partition after doing the ORDER BY.

The <sql_expr> is computed on the columns of this first record and results are returned.

The LAST_VALUE function is used in similar context except that it acts on the last record of the partition.

How many days after the first hire of each department were the next employees hired?

11/39

FIRST and LAST function

The FIRST function (or more properly KEEP FIRST function) is used in a very special situation. Suppose we rank a group of record and found several records in the first rank. Now we want to apply an aggregate function on the records of the first rank. KEEP FIRST enables that.

• syntaxFunction( ) KEEP (DENSE_RANK FIRST ORDER BY <expr>) OVER (<partitioning_clause>)

Please note that FIRST and LAST are the only functions that deviate from the general syntax of analytic functions. They do not have the ORDER BY inside the OVER clause. Neither do they support any <window> clause. The ranking done in FIRST and LAST is always DENSE_RANK.

The LAST function is used in similar context to perform computations on last ranked records.

How each employee's salary compare with the average salary of the first year hires of their department?

12/39

FIRST and LAST function

13/39

Analytic Functions(window-clause)• This group of rows is known as a window, which is why analytic functions are

sometimes referred to as window[ing] functions.

• We have seen previously the query_partition_clause controls the window, or group of rows, the analytic operates on. The windowing_clause gives some analytic functions a further degree of control over this window within the current partition. The windowing_clause is an extension of the order_by_clause and as such, it can only be used if an order_by_clause is present.

14/39

Analytic Functions(window-clause)<window_clause>• [ROW or RANGE] BETWEEN <start_expr> AND <end_expr>

<start_expr> can be any one of the following • UNBOUNDED PRECEDING• CURRENT ROW• <sql_expr> PRECEDING or FOLLOWING.

<end_expr> can be any one of the following • UNBOUNDED FOLLOWING• CURRENT ROW• <sql_expr> PRECEDING or FOLLOWING.

15/39

Analytic Functions(window-clause)• For ROW type windows the definition is in terms of row numbers before or after the

current row. So for ROW type windows <sql_expr> must evaluate to a positive integer.

• For RANGE type windows the definition is in terms of values before or after the current ORDER.

• The ROW or RANGE window cannot appear together in one OVER clause.

• The window clause is defined in terms of the current row. But may or may not include the current row.

• The start point of the window and the end point of the window can finish before the current row or after the current row.

• Only start point cannot come after the end point of the window.

16/39

ROW Type Windows

17/39

RANGE Windows

18/39

LISTAGG Function• Description

The Oracle/PLSQL LISTAGG function concatenates values of the

measure_column for each GROUP based on the order_by_clause.

• SYNTAX

LISTAGG (measure_column [, 'delimiter']) WITHIN GROUP (order_by_clause)

[OVER (query_partition_clause)]

• measure_column

The column whose values you wish to concatenate together in the result set.

Null values in the measure_column are ignored.

• Delimiter

Optional. It is the delimiter to use when separating the measure_column values

when outputting the results.

19/39

LISTAGG Function• order_by_clause

It determines the order that the concatenated values (ie: measure_column) are

returned.

• Example

SELECT LISTAGG(product_name, ', ') WITHIN GROUP (ORDER BY product_name)

"Product_Listing" FROM products;

Product_id Product_name

1001 Bananas

1002 Apples

1003 Pears

1004 Oranges

Product_Listing

Apples, Bananas, Oranges, Pears

20/39

TRANSLATE Function• Description

The Oracle/PLSQL TRANSLATE function replaces a sequence of characters in a string with another set of characters. However, it replaces a single character at a time.

For example, it will replace the 1st character in the string_to_replace with the 1st character in the replacement_string. Then it will replace the 2nd character in the string_to_replace with the 2nd character in the replacement_string, and so on.

• SyntaxTRANSLATE( string1, string_to_replace, replacement_string )

• string1

The string to replace a sequence of characters with another set of characters.

21/39

TRANSLATE Function• string_to_replace

The string that will be searched for in string1.

• replacement_string

All characters in the string_to_replace will be replaced with the corresponding

character in the replacement_string.

• Example

TRANSLATE('1tech23', '123', '456') Result: '4tech56'

TRANSLATE('222tech', '2ec', '3it') Result: '333tith'

22/39

REGEXP_LIKE Condition• Description

The Oracle REGEXP_LIKE condition allows you to perform regular expression

matching in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE

statement.

• SYNTAX

REGEXP_LIKE ( expression, pattern [, match_parameter ] )

• Expression

A character expression such as a column or field. It can be a

VARCHAR2, CHAR, NVARCHAR2, NCHAR, CLOB or NCLOB data type.

23/39

REGEXP_LIKE Condition• Pattern

The regular expression matching information.

^ Matches the beginning of a string.

$ Matches the end of a string.

* Matches zero or more occurrences.

| Used like an "OR" to specify more than one alternative.

+ Matches one of more occurrences.

? Matches zero or one occurrence.

. Matches any character except NULL.

[ ] Used to specify a matching list where you are trying to match any one of the characters in the list.

[^ ]

Used to specify a nonmatching list where you are trying to match any character except for the ones in the list.

24/39

REGEXP_LIKE Condition• match_parameter

Optional. It allows you to modify the matching behavior for the REGEXP_LIKE condition.

• Example

SELECT last_name FROM contacts WHERE REGEXP_LIKE (last_name, 'Anders(o|e|a)n');

SELECT last_name FROM contacts WHERE REGEXP_LIKE (last_name, '^A(*)');

SELECT last_name FROM contacts WHERE REGEXP_LIKE (last_name, '(*)n$');

‘c’ Perform case-sensitive matching.

‘i’ Perform case-insensitive matching.

‘n’ Allows the period character (.) to match the newline character.

‘m’ expression is assumed to have multiple lines, where ^ is the start of a line and $ is the end of a line, regardless of the position of those characters in expression.

‘x’ Whitespace characters are ignored.

25/39

REGEXP_COUNT Function• Description

The Oracle/PLSQL REGEXP_COUNT function counts the number of times that a pattern occurs in a string.

• SyntaxREGEXP_COUNT( string, pattern [, start_position [, match_parameter ] ] )

• string The string to search. string can be CHAR, VARCHAR2, NCHAR,

NVARCHAR2, CLOB, or NCLOB.

• pattern The regular expression matching information.

• start_position Optional. It is the position in string where the search will start. If omitted, it defaults to 1 which is the first position in the string.

• match_parameter Optional. It allows you to modify the matching behavior for the

REGEXP_COUNT function.

26/39

REGEXP_COUNT Function• Example

SELECT REGEXP_COUNT ('TechOnTheNet is a great resource!', 't') FROM dual;

Result: 2.

SELECT REGEXP_COUNT ('TechOnTheNet is a great resource!', 't', 1, 'i') FROM dual;

Result: 4

SELECT REGEXP_COUNT ('The example shows how to use the REGEXP_COUNT function.', 'the', 4, 'i') FROM dual;

Result: 1

SELECT REGEXP_COUNT ('Anderson', 'a|e|i|o|u') FROM dual;

Result: 2

SELECT REGEXP_COUNT ('Anderson', 'a|e|i|o|u', 1, 'i') FROM dual;

Result: 3

27/39

COALESCE Function• Description

The Oracle/PLSQL COALESCE function returns the first non-null expression in the list. If all expressions evaluate to null, then the COALESCE function will return null.

• SyntaxCOALESCE( expr1, expr2, ... expr_n )

• expr1, expr2, ... expr_n The expressions to test for non-null values.

28/39

COALESCE Function• ExampleSELECT COALESCE( address1, address2, address3 ) result FROM suppliers;

The above COALESCE function is equivalent to the following IF-THEN-ELSE statement:

IF address1 is not null THEN

result := address1;

ELSIF address2 is not null THEN

result := address2;

ELSIF address3 is not null THEN

result := address3;

ELSE

result := null;

END IF;

29/39

EXTRACT Function• Description

The Oracle/PLSQL EXTRACT function extracts a value from a date or interval value.

• Syntax

EXTRACT ( { YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | {

TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION |

TIMEZONE_ABBR } FROM { date_value | interval_value } )

• Example

EXTRACT(YEAR FROM DATE '2003-08-22') Result: 2003

EXTRACT(MONTH FROM DATE '2003-08-22') Result: 8

EXTRACT(DAY FROM DATE '2003-08-22') Result: 22

30/39

ADD_MONTHS Function• Description

The Oracle/PLSQL ADD_MONTHS function returns a date with a specified number of months added.

• SyntaxADD_MONTHS( date1, number_months )

• Date1The starting date (before the n months have been added).

• number_monthsThe number of months to add to date1.

31/39

ADD_MONTHS Function• Example

ADD_MONTHS('01-Aug-03', 3)

Result: '01-Nov-03‘

ADD_MONTHS('01-Aug-03', -3)

Result: '01-May-03'

ADD_MONTHS('21-Aug-03', -3)

Result: '21-May-03'

ADD_MONTHS('31-Jan-03', 1)

Result: '28-Feb-03'

32/39

INITCAP Function• Description

The Oracle/PLSQL INITCAP function sets the first character in each word to uppercase and the rest to lowercase.

• SyntaxINITCAP( string1 )

• string1

The string argument whose first character in each word will be converted to uppercase

and all remaining characters converted to lowercase.

• Example

INITCAP('tech on the net');

Result: 'Tech On The Net‘

INITCAP('GEORGE BURNS');

Result: 'George Burns'

33/39

INSTR Function• Description

The Oracle/PLSQL INSTR function returns the location of a substring in a string.

• SyntaxINSTR( string, substring [, start_position [, nth_appearance ] ] )

• StringThe string to search. string can be CHAR, VARCHAR2, NCHAR,

NVARCHAR2, CLOB, or NCLOB.

• SubstringThe substring to search for in string. substring can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.

34/39

INSTR Function• start_position

Optional. The position in string where the search will start. If omitted, it defaults to 1. The first position in the string is 1. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

• nth_appearanceOptional. The nth appearance of substring. If omitted, it defaults to 1.

Note: If substring is not found in string, then the INSTR function will return 0.

35/39

INSTR Function• Example

INSTR('Tech on the net', 'e') Result: 2 (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 1) Result: 2 (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 2) Result: 11 (the second occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 3) Result: 14 (the third occurrence of 'e')

INSTR('Tech on the net', 'e', -3, 2) Result: 2

36/39

GREATEST Function• Description

The Oracle/PLSQL GREATEST function returns the greatest value in a list of expressions.

• SyntaxGREATEST( expr1 [, expr2, ... expr_n] )

• expr1 The first expression to be evaluated whether it is the greatest.

• expr2, ... expr_n Optional. Additional expressions that are to be evaluated.

Note:If the datatypes of the expressions are different, all expressions will be converted to whatever datatype expr1 is.

If the comparison is based on a character comparison, one character is considered greater than another if it has a higher character set value.

37/39

GREATEST Function• Example

GREATEST(2, 5, 12, 3) Result: 12

GREATEST('2', '5', '12', '3') Result: '5'

GREATEST('apples', 'oranges', 'bananas') Result: 'oranges'

GREATEST('apples', 'applis', 'applas') Result: 'applis'

38/39

Name of Functionsselect distinct

   object_name

from

   all_arguments

where

   package_name = 'STANDARD';

 

39/39