SlideShare a Scribd company logo
1 of 39
Advanced Functions in PL/SQL
Titles
Analytic 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.
• Syntax
analytic_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
• Syntax
FIRST_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.
• syntax
Function( ) 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.
• Syntax
TRANSLATE( 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.
• Syntax
REGEXP_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.
• Syntax
COALESCE( expr1, expr2, ... expr_n )
• expr1, expr2, ... expr_n
The expressions to test for non-null values.
28/39
COALESCE Function
• Example
SELECT 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.
• Syntax
ADD_MONTHS( date1, number_months )
• Date1
The starting date (before the n months have been added).
• number_months
The 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.
• Syntax
INITCAP( 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.
• Syntax
INSTR( string, substring [, start_position [, nth_appearance ] ] )
• String
The string to search. string can be CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB.
• Substring
The 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_appearance
Optional. 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.
• Syntax
GREATEST( 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 Functions
select distinct
object_name
from
all_arguments
where
package_name = 'STANDARD';
39/39

More Related Content

What's hot

Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Thuan Nguyen
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
Database normalization
Database normalizationDatabase normalization
Database normalizationJignesh Jain
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 
Oracle Compensation Management
Oracle Compensation ManagementOracle Compensation Management
Oracle Compensation ManagementHussain Abbas
 
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book Feras Ahmad
 
Almost everything-you-wanted-to-know-about-pto
Almost everything-you-wanted-to-know-about-ptoAlmost everything-you-wanted-to-know-about-pto
Almost everything-you-wanted-to-know-about-ptoMayadevi Gopi
 
7. Relational Database Design in DBMS
7. Relational Database Design in DBMS7. Relational Database Design in DBMS
7. Relational Database Design in DBMSkoolkampus
 
How to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdfHow to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdfFeras Ahmad
 
Fast formula in Fusion Cloud HCM
Fast formula in Fusion Cloud HCMFast formula in Fusion Cloud HCM
Fast formula in Fusion Cloud HCMFeras Ahmad
 
Les16[1]Declaring Variables
Les16[1]Declaring VariablesLes16[1]Declaring Variables
Les16[1]Declaring Variablessiavosh kaviani
 
Validation type 'special' in value sets
Validation type 'special' in value setsValidation type 'special' in value sets
Validation type 'special' in value setsFeras Ahmad
 
Defining key flexfields
Defining key flexfieldsDefining key flexfields
Defining key flexfieldsrunjithrocking
 

What's hot (20)

Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
 
SQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftjSQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftj
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Database normalization
Database normalizationDatabase normalization
Database normalization
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
Fiori eğitimi - kod
Fiori eğitimi - kodFiori eğitimi - kod
Fiori eğitimi - kod
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Oracle Compensation Management
Oracle Compensation ManagementOracle Compensation Management
Oracle Compensation Management
 
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
Infolets and OTBI Deep link Actionable Reports - Configuration Work Book
 
Almost everything-you-wanted-to-know-about-pto
Almost everything-you-wanted-to-know-about-ptoAlmost everything-you-wanted-to-know-about-pto
Almost everything-you-wanted-to-know-about-pto
 
Normalization
NormalizationNormalization
Normalization
 
7. Relational Database Design in DBMS
7. Relational Database Design in DBMS7. Relational Database Design in DBMS
7. Relational Database Design in DBMS
 
LR Parsing
LR ParsingLR Parsing
LR Parsing
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
How to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdfHow to Debug the Fast Formula.pdf
How to Debug the Fast Formula.pdf
 
Fast formula in Fusion Cloud HCM
Fast formula in Fusion Cloud HCMFast formula in Fusion Cloud HCM
Fast formula in Fusion Cloud HCM
 
Normalization
NormalizationNormalization
Normalization
 
Les16[1]Declaring Variables
Les16[1]Declaring VariablesLes16[1]Declaring Variables
Les16[1]Declaring Variables
 
Validation type 'special' in value sets
Validation type 'special' in value setsValidation type 'special' in value sets
Validation type 'special' in value sets
 
Defining key flexfields
Defining key flexfieldsDefining key flexfields
Defining key flexfields
 

Similar to Advanced functions in PL SQL

Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracleLogan Palanisamy
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdfKalyankumarVenkat1
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
 
Using Excel Functions
Using Excel FunctionsUsing Excel Functions
Using Excel FunctionsGautam Gupta
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
 
5.Analytical Function.pdf
5.Analytical Function.pdf5.Analytical Function.pdf
5.Analytical Function.pdfssuser8b6c85
 
it skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptxit skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptxMdAquibRazi1
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaperoracle documents
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Alexey Furmanov
 
SQL-Developer-Lecture-21.pdf
SQL-Developer-Lecture-21.pdfSQL-Developer-Lecture-21.pdf
SQL-Developer-Lecture-21.pdfshiv159508
 
Oracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive PlansOracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive PlansFranck Pachot
 
Enabling Applications with Informix' new OLAP functionality
 Enabling Applications with Informix' new OLAP functionality Enabling Applications with Informix' new OLAP functionality
Enabling Applications with Informix' new OLAP functionalityAjay Gupte
 

Similar to Advanced functions in PL SQL (20)

Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdf
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
Using Excel Functions
Using Excel FunctionsUsing Excel Functions
Using Excel Functions
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 
5.Analytical Function.pdf
5.Analytical Function.pdf5.Analytical Function.pdf
5.Analytical Function.pdf
 
it skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptxit skill excel sheet for ppt.pptx
it skill excel sheet for ppt.pptx
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
SQL-Developer-Lecture-21.pdf
SQL-Developer-Lecture-21.pdfSQL-Developer-Lecture-21.pdf
SQL-Developer-Lecture-21.pdf
 
Oracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive PlansOracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive Plans
 
Enabling Applications with Informix' new OLAP functionality
 Enabling Applications with Informix' new OLAP functionality Enabling Applications with Informix' new OLAP functionality
Enabling Applications with Informix' new OLAP functionality
 

Recently uploaded

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Advanced functions in PL SQL

  • 2. Titles Analytic 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
  • 3. 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. • Syntax analytic_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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 11. FIRST VALUE and LAST VALUE function • Syntax FIRST_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
  • 12. 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. • syntax Function( ) 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
  • 13. FIRST and LAST function 13/39
  • 14. 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
  • 15. 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
  • 16. 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
  • 19. 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
  • 20. 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
  • 21. 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. • Syntax TRANSLATE( string1, string_to_replace, replacement_string ) • string1 The string to replace a sequence of characters with another set of characters. 21/39
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. REGEXP_COUNT Function • Description The Oracle/PLSQL REGEXP_COUNT function counts the number of times that a pattern occurs in a string. • Syntax REGEXP_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
  • 27. 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
  • 28. 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. • Syntax COALESCE( expr1, expr2, ... expr_n ) • expr1, expr2, ... expr_n The expressions to test for non-null values. 28/39
  • 29. COALESCE Function • Example SELECT 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
  • 30. 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
  • 31. ADD_MONTHS Function • Description The Oracle/PLSQL ADD_MONTHS function returns a date with a specified number of months added. • Syntax ADD_MONTHS( date1, number_months ) • Date1 The starting date (before the n months have been added). • number_months The number of months to add to date1. 31/39
  • 32. 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
  • 33. INITCAP Function • Description The Oracle/PLSQL INITCAP function sets the first character in each word to uppercase and the rest to lowercase. • Syntax INITCAP( 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
  • 34. INSTR Function • Description The Oracle/PLSQL INSTR function returns the location of a substring in a string. • Syntax INSTR( string, substring [, start_position [, nth_appearance ] ] ) • String The string to search. string can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. • Substring The substring to search for in string. substring can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. 34/39
  • 35. 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_appearance Optional. 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
  • 36. 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
  • 37. GREATEST Function • Description The Oracle/PLSQL GREATEST function returns the greatest value in a list of expressions. • Syntax GREATEST( 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
  • 38. 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
  • 39. Name of Functions select distinct object_name from all_arguments where package_name = 'STANDARD'; 39/39