SlideShare a Scribd company logo
Copyright © 2017, Oracle and/or its affiliates. All rights reserved. |
Your PL/SQL Office Hours session will begin
soon…
Polymorphic Table Functions!
with
Chris Saxon, @ChrisRSaxon & @SQLDaily
https://www.youtube.com/c/TheMagicofSQL
https://blogs.oracle.com/sql
Steven Feuerstein, @sfonplsql
http://www.youtube.com/c/PracticallyPerfectPLSQL
http://stevenfeuersteinonplsql.blogspot.com/
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
Polymorphic
Table Functions
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
Added in Oracle Database 18c, Polymorphic Table Functions
(PTFs) allow you do dynamically manipulate a result set at
runtime.
This means you can add or remove columns from a table,
based on input parameters
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
Why would
I want to do
this?!
Ryan McGuire / Gratisography
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
C,S,V =>
Dynamic
Customer Total Orders
Best customer 1,422
2nd best customer 1,000
All other customers 6,502
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
PTF Use Cases
CSV to Column conversion
Inspect CSV files and automatically split
the fields into columns
Dynamic Pivot
Generate pivoted column names based
on a row source
Top-N+
Like a standard Top-N query, but with an
extra row, summarizing all remaining data
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
To build a PTF, you need two things
A package
The package is the engine of the PTF. This must include a describe function. This tells
the database which columns are in the output
To assign values for each row to the new columns, you use a fetch_rows procedure
The function itself
You can create the PTF itself within the package
Or as a standalone function
Defining PTFs
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
create or replace package add_cols_pkg as
function describe (
tab in out dbms_tf.table_t,
cols dbms_tf.columns_t
) return dbms_tf.describe_t;
procedure fetch_rows ;
end add_cols_pkg;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
Assign values
(optional)
Define new s
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
create or replace function add_columns (
tab table,
cols columns
) return
table pipelined
table polymorphic
using add_cols_pkg;
/
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
create or replace function add_columns (
tab table,
cols columns
) return
table pipelined
table polymorphic
using add_cols_pkg;
/
PTFs introduce two new "data types":
table
The input table for the PTF
Every PTF must have one of these
columns pseudo operator
A list of identifiers. These could be
existing columns in the table, or new
columns you want to add
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
create or replace function add_columns (
tab table,
cols columns
) return
table pipelined
table polymorphic
using add_cols_pkg;
/
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
In the polymorphic clause you
define it as using row or table
semantics.
With row semantics, the input is a
single row.
With table semantics, the input is a set
of rows. This allows you to sort the
input
The using clause states which package
contains the implementation of the PTF
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
describe function
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
You must have one of one of these in your package
This tells the database which columns will be in the result set
The following describe body adds columns to the output
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
begin
for i in 1 .. cols.count loop
new_cols(i) := dbms_tf.column_metadata_t (
name => cols(i),
type => dbms_tf.type_number
);
end loop;
return dbms_tf.describe_t ( new_columns => new_cols );
end;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
This builds up an array of definitions for the new columns
dbms_tf.column_metadata_t defines their properties
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
begin
for i in 1 .. cols.count loop
new_cols(i) := dbms_tf.column_metadata_t (
name => cols(i),
type => dbms_tf.type_number
);
end loop;
return dbms_tf.describe_t ( new_columns => new_cols );
end;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
To add the new columns to the results, you must return them
using dbms_tf.describe_t
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
dual, columns ( c1 )
);
DUMMY C1
X <null>
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
dual, columns ( c1, c2 )
);
DUMMY C1 C2
X <null> <null>
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
fetch_rows procedure
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
To assign values to each row for the new columns you need a
fetch_rows procedure
The following fetch_rows body sets the value of new
columns to
row# * column#
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
begin
env := dbms_tf.get_env();
for clmn in 1 .. env.ref_put_col.count loop
for rw in 1 .. env.row_count loop
col ( rw ) := rw * clmn;
end loop;
dbms_tf.put_col ( clmn, col );
end loop;
end fetch_rows;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
dbms_tf.get_env captures the
current execution state
This includes details of all the
rows and columns processed in
this iteration of fetch_rows
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
begin
env := dbms_tf.get_env();
for clmn in 1 .. env.ref_put_col.count loop
for rw in 1 .. env.row_count loop
col ( rw ) := rw * clmn;
end loop;
dbms_tf.put_col ( clmn, col );
end loop;
end fetch_rows;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
col is an array of row values
for a column
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
begin
env := dbms_tf.get_env();
for clmn in 1 .. env.ref_put_col.count loop
for rw in 1 .. env.row_count loop
col ( rw ) := rw * clmn;
end loop;
dbms_tf.put_col ( clmn, col );
end loop;
end fetch_rows;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
To return the row values to the
client, you must call
dbms_tf.put_col
This assigns the array of row
values to the put column at
position CLMN
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
tab,
columns ( c1, c2 )
);
X C1 C2
1 1 2
2 2 4
3 3 6
4 4 8
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
tab is a four-row table with the
column x
The PTF assigns incrementing
values to the columns added
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
tab,
columns ( c1, c2 )
);
X C1 C2
1 1 2
2 2 4
3 3 6
4 4 8
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
tab order by x desc,
columns ( c1, c2 )
);
X C1 C2
4 1 2
3 2 4
2 3 6
1 4 8
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
This PTF uses table semantics
So you can sort the input with
an order by clause after the
table name
This has a descending sort, so as
X decreases, C1 increases
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
select * from add_columns (
tab partition by y order by x desc,
columns ( c1, c2 )
);
X Y C1 C2
4 0 1 2
2 0 2 4
3 1 1 2
1 1 2 4
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
This PTF uses table semantics
So you can also split the input
into groups with an partition by
clause after the table name
The database calls the
fetch_rows procedure at least
once for each distinct value in
the partition by
Y = mod (X, 2); so odd and even
values of X have separate
counters
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
X Y C1 C2
1021 1 1021 2042
1022 0 1022 2044
1023 1 1023 2046
1024 0 1024 2048
1025 1 1 2
1026 0 2 4
1027 1 3 6
1028 0 4 8
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
PTFs process rows in batches
Empirical testing shows this as
units of 1,024 rows (whether
this is a hard limit is TBC)
After fetching this many rows,
the PTF calls fetch_rows again
So this resets the counter
If you write PTFs which have
running counters or
aggregations, you'll need to
save the execution state
You can do this with
dbms_tf.xstore procedures
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
for clmn in 1 .. env.ref_put_col.count loop
dbms_tf.xstore_get('col' || clmn, last_row);
for rw in 1 .. env.row_count loop
col ( rw ) := ( rw + last_row ) * clmn;
end loop;
dbms_tf.put_col ( clmn, col );
dbms_tf.xstore_set (
'col' || clmn, last_row + env.row_count
);
end loop;
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
The xstore holds key-
value pairs
If you get a non-
existent key, the input
value is unchanged
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
How do
I debug it?
Gratisography
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
dbms_tf.trace (
env => dbms_tf.get_env()
);
dbms_tf.trace (
msg => 'Your text here'
);
blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
The dbms_tf.trace procedure
has several overloads which
allow you to view the current
execution state
In my experience, the most
useful are:
• env; this displays the whole
execution state
• msg; which allows you to
add your own text
Like dbms_output, tracing
displays the results on screen,
not in a database table or view
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
Now it's over to you!
Where canYou can find many PTF examples on https://livesql.oracle.com
Copyright © 2019, Oracle and/or its affiliates. All rights reserved. |
asktom.oracle.com
#AskTOMOfficeHours
Ryan McGuire / Gratisography

More Related Content

What's hot

How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
oysteing
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
pitchaiah yechuri
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360
Carlos Sierra
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL Compiler
Steven Feuerstein
 
Error Management Features of PL/SQL
Error Management Features of PL/SQLError Management Features of PL/SQL
Error Management Features of PL/SQL
Steven Feuerstein
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
rehaniltifat
 
Cursors in MySQL
Cursors in MySQL Cursors in MySQL
Cursors in MySQL
Tharindu Weerasinghe
 
SQL Plan Directives explained
SQL Plan Directives explainedSQL Plan Directives explained
SQL Plan Directives explained
Mauro Pagano
 
Oracle使用者安全設定
Oracle使用者安全設定Oracle使用者安全設定
Oracle使用者安全設定
Chien Chung Shen
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
Andrej Pashchenko
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
EDB
 
Managing objects with data dictionary views
Managing objects with data dictionary viewsManaging objects with data dictionary views
Managing objects with data dictionary views
Syed Zaid Irshad
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
rehaniltifat
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
Tanel Poder
 
SQLd360
SQLd360SQLd360
SQLd360
Mauro Pagano
 
Oracle Advanced SQL
Oracle Advanced SQLOracle Advanced SQL
Oracle Advanced SQL
Marcin Blaszczyk
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
rehaniltifat
 
Harnessing the Power of Optimizer Hints
Harnessing the Power of Optimizer HintsHarnessing the Power of Optimizer Hints
Harnessing the Power of Optimizer Hints
Maria Colgan
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
rehaniltifat
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
Chien Chung Shen
 

What's hot (20)

How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL Compiler
 
Error Management Features of PL/SQL
Error Management Features of PL/SQLError Management Features of PL/SQL
Error Management Features of PL/SQL
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
 
Cursors in MySQL
Cursors in MySQL Cursors in MySQL
Cursors in MySQL
 
SQL Plan Directives explained
SQL Plan Directives explainedSQL Plan Directives explained
SQL Plan Directives explained
 
Oracle使用者安全設定
Oracle使用者安全設定Oracle使用者安全設定
Oracle使用者安全設定
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
 
[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
 
Managing objects with data dictionary views
Managing objects with data dictionary viewsManaging objects with data dictionary views
Managing objects with data dictionary views
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
SQLd360
SQLd360SQLd360
SQLd360
 
Oracle Advanced SQL
Oracle Advanced SQLOracle Advanced SQL
Oracle Advanced SQL
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
Harnessing the Power of Optimizer Hints
Harnessing the Power of Optimizer HintsHarnessing the Power of Optimizer Hints
Harnessing the Power of Optimizer Hints
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 

Similar to Polymorphic Table Functions in SQL

18(ish) Things You'll Love About Oracle Database 18c
18(ish) Things You'll Love About Oracle Database 18c18(ish) Things You'll Love About Oracle Database 18c
18(ish) Things You'll Love About Oracle Database 18c
Chris Saxon
 
M|18 Ingesting Data with the New Bulk Data Adapters
M|18 Ingesting Data with the New Bulk Data AdaptersM|18 Ingesting Data with the New Bulk Data Adapters
M|18 Ingesting Data with the New Bulk Data Adapters
MariaDB plc
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
Les09.ppt
Les09.pptLes09.ppt
Fortran & Link with Library & Brief Explanation of MKL BLAS
Fortran & Link with Library & Brief Explanation of MKL BLASFortran & Link with Library & Brief Explanation of MKL BLAS
Fortran & Link with Library & Brief Explanation of MKL BLAS
Jongsu "Liam" Kim
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
Beg sql
Beg sqlBeg sql
Beg sql
KPNR Jan
 
Beg sql
Beg sqlBeg sql
Apache Cassandra 2.0
Apache Cassandra 2.0Apache Cassandra 2.0
Apache Cassandra 2.0
Joe Stein
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and Oracle
Kellyn Pot'Vin-Gorman
 
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesChoose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
CHOOSE
 

Similar to Polymorphic Table Functions in SQL (20)

18(ish) Things You'll Love About Oracle Database 18c
18(ish) Things You'll Love About Oracle Database 18c18(ish) Things You'll Love About Oracle Database 18c
18(ish) Things You'll Love About Oracle Database 18c
 
M|18 Ingesting Data with the New Bulk Data Adapters
M|18 Ingesting Data with the New Bulk Data AdaptersM|18 Ingesting Data with the New Bulk Data Adapters
M|18 Ingesting Data with the New Bulk Data Adapters
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
 
Les09.ppt
Les09.pptLes09.ppt
Les09.ppt
 
Fortran & Link with Library & Brief Explanation of MKL BLAS
Fortran & Link with Library & Brief Explanation of MKL BLASFortran & Link with Library & Brief Explanation of MKL BLAS
Fortran & Link with Library & Brief Explanation of MKL BLAS
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Apache Cassandra 2.0
Apache Cassandra 2.0Apache Cassandra 2.0
Apache Cassandra 2.0
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and Oracle
 
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of TonguesChoose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
Choose'10: Ralf Laemmel - Dealing Confortably with the Confusion of Tongues
 

More from Chris Saxon

Game of Fraud Detection with SQL and Machine Learning
Game of Fraud Detection with SQL and Machine LearningGame of Fraud Detection with SQL and Machine Learning
Game of Fraud Detection with SQL and Machine Learning
Chris Saxon
 
Agile Database Development with JSON
Agile Database Development with JSONAgile Database Development with JSON
Agile Database Development with JSON
Chris Saxon
 
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL ChangesUsing Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Chris Saxon
 
Why Isn't My Query Using an Index? An Introduction to SQL Performance
Why Isn't My Query Using an Index? An Introduction to SQL PerformanceWhy Isn't My Query Using an Index? An Introduction to SQL Performance
Why Isn't My Query Using an Index? An Introduction to SQL Performance
Chris Saxon
 
12 Things Developers Will Love About Oracle Database 12c Release 2
12 Things Developers Will Love About Oracle Database 12c Release 212 Things Developers Will Love About Oracle Database 12c Release 2
12 Things Developers Will Love About Oracle Database 12c Release 2
Chris Saxon
 
How to Hack Your App Using SQL Injection
How to Hack Your App Using SQL InjectionHow to Hack Your App Using SQL Injection
How to Hack Your App Using SQL Injection
Chris Saxon
 
How to Find Patterns in Your Data with SQL
How to Find Patterns in Your Data with SQLHow to Find Patterns in Your Data with SQL
How to Find Patterns in Your Data with SQL
Chris Saxon
 

More from Chris Saxon (7)

Game of Fraud Detection with SQL and Machine Learning
Game of Fraud Detection with SQL and Machine LearningGame of Fraud Detection with SQL and Machine Learning
Game of Fraud Detection with SQL and Machine Learning
 
Agile Database Development with JSON
Agile Database Development with JSONAgile Database Development with JSON
Agile Database Development with JSON
 
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL ChangesUsing Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
 
Why Isn't My Query Using an Index? An Introduction to SQL Performance
Why Isn't My Query Using an Index? An Introduction to SQL PerformanceWhy Isn't My Query Using an Index? An Introduction to SQL Performance
Why Isn't My Query Using an Index? An Introduction to SQL Performance
 
12 Things Developers Will Love About Oracle Database 12c Release 2
12 Things Developers Will Love About Oracle Database 12c Release 212 Things Developers Will Love About Oracle Database 12c Release 2
12 Things Developers Will Love About Oracle Database 12c Release 2
 
How to Hack Your App Using SQL Injection
How to Hack Your App Using SQL InjectionHow to Hack Your App Using SQL Injection
How to Hack Your App Using SQL Injection
 
How to Find Patterns in Your Data with SQL
How to Find Patterns in Your Data with SQLHow to Find Patterns in Your Data with SQL
How to Find Patterns in Your Data with SQL
 

Recently uploaded

Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
Sease
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
Fwdays
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
ScyllaDB
 
AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)
HarpalGohil4
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
Ortus Solutions, Corp
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
Fwdays
 

Recently uploaded (20)

Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
 
AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)AWS Certified Solutions Architect Associate (SAA-C03)
AWS Certified Solutions Architect Associate (SAA-C03)
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
 

Polymorphic Table Functions in SQL

  • 1. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Your PL/SQL Office Hours session will begin soon… Polymorphic Table Functions! with Chris Saxon, @ChrisRSaxon & @SQLDaily https://www.youtube.com/c/TheMagicofSQL https://blogs.oracle.com/sql Steven Feuerstein, @sfonplsql http://www.youtube.com/c/PracticallyPerfectPLSQL http://stevenfeuersteinonplsql.blogspot.com/
  • 2. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | Polymorphic Table Functions blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon Added in Oracle Database 18c, Polymorphic Table Functions (PTFs) allow you do dynamically manipulate a result set at runtime. This means you can add or remove columns from a table, based on input parameters
  • 3. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | Why would I want to do this?! Ryan McGuire / Gratisography
  • 4. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | C,S,V => Dynamic Customer Total Orders Best customer 1,422 2nd best customer 1,000 All other customers 6,502 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon PTF Use Cases CSV to Column conversion Inspect CSV files and automatically split the fields into columns Dynamic Pivot Generate pivoted column names based on a row source Top-N+ Like a standard Top-N query, but with an extra row, summarizing all remaining data
  • 5. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon To build a PTF, you need two things A package The package is the engine of the PTF. This must include a describe function. This tells the database which columns are in the output To assign values for each row to the new columns, you use a fetch_rows procedure The function itself You can create the PTF itself within the package Or as a standalone function Defining PTFs
  • 6. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | create or replace package add_cols_pkg as function describe ( tab in out dbms_tf.table_t, cols dbms_tf.columns_t ) return dbms_tf.describe_t; procedure fetch_rows ; end add_cols_pkg; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon Assign values (optional) Define new s
  • 7. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon create or replace function add_columns ( tab table, cols columns ) return table pipelined table polymorphic using add_cols_pkg; /
  • 8. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon create or replace function add_columns ( tab table, cols columns ) return table pipelined table polymorphic using add_cols_pkg; / PTFs introduce two new "data types": table The input table for the PTF Every PTF must have one of these columns pseudo operator A list of identifiers. These could be existing columns in the table, or new columns you want to add
  • 9. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | create or replace function add_columns ( tab table, cols columns ) return table pipelined table polymorphic using add_cols_pkg; / blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon In the polymorphic clause you define it as using row or table semantics. With row semantics, the input is a single row. With table semantics, the input is a set of rows. This allows you to sort the input The using clause states which package contains the implementation of the PTF
  • 10. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | describe function blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon You must have one of one of these in your package This tells the database which columns will be in the result set The following describe body adds columns to the output
  • 11. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | begin for i in 1 .. cols.count loop new_cols(i) := dbms_tf.column_metadata_t ( name => cols(i), type => dbms_tf.type_number ); end loop; return dbms_tf.describe_t ( new_columns => new_cols ); end; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon This builds up an array of definitions for the new columns dbms_tf.column_metadata_t defines their properties
  • 12. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | begin for i in 1 .. cols.count loop new_cols(i) := dbms_tf.column_metadata_t ( name => cols(i), type => dbms_tf.type_number ); end loop; return dbms_tf.describe_t ( new_columns => new_cols ); end; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon To add the new columns to the results, you must return them using dbms_tf.describe_t
  • 13. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( dual, columns ( c1 ) ); DUMMY C1 X <null> blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
  • 14. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( dual, columns ( c1, c2 ) ); DUMMY C1 C2 X <null> <null> blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
  • 15. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | fetch_rows procedure blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon To assign values to each row for the new columns you need a fetch_rows procedure The following fetch_rows body sets the value of new columns to row# * column#
  • 16. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | begin env := dbms_tf.get_env(); for clmn in 1 .. env.ref_put_col.count loop for rw in 1 .. env.row_count loop col ( rw ) := rw * clmn; end loop; dbms_tf.put_col ( clmn, col ); end loop; end fetch_rows; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon dbms_tf.get_env captures the current execution state This includes details of all the rows and columns processed in this iteration of fetch_rows
  • 17. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | begin env := dbms_tf.get_env(); for clmn in 1 .. env.ref_put_col.count loop for rw in 1 .. env.row_count loop col ( rw ) := rw * clmn; end loop; dbms_tf.put_col ( clmn, col ); end loop; end fetch_rows; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon col is an array of row values for a column
  • 18. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | begin env := dbms_tf.get_env(); for clmn in 1 .. env.ref_put_col.count loop for rw in 1 .. env.row_count loop col ( rw ) := rw * clmn; end loop; dbms_tf.put_col ( clmn, col ); end loop; end fetch_rows; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon To return the row values to the client, you must call dbms_tf.put_col This assigns the array of row values to the put column at position CLMN
  • 19. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( tab, columns ( c1, c2 ) ); X C1 C2 1 1 2 2 2 4 3 3 6 4 4 8 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon tab is a four-row table with the column x The PTF assigns incrementing values to the columns added
  • 20. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( tab, columns ( c1, c2 ) ); X C1 C2 1 1 2 2 2 4 3 3 6 4 4 8 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon
  • 21. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( tab order by x desc, columns ( c1, c2 ) ); X C1 C2 4 1 2 3 2 4 2 3 6 1 4 8 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon This PTF uses table semantics So you can sort the input with an order by clause after the table name This has a descending sort, so as X decreases, C1 increases
  • 22. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | select * from add_columns ( tab partition by y order by x desc, columns ( c1, c2 ) ); X Y C1 C2 4 0 1 2 2 0 2 4 3 1 1 2 1 1 2 4 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon This PTF uses table semantics So you can also split the input into groups with an partition by clause after the table name The database calls the fetch_rows procedure at least once for each distinct value in the partition by Y = mod (X, 2); so odd and even values of X have separate counters
  • 23. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | X Y C1 C2 1021 1 1021 2042 1022 0 1022 2044 1023 1 1023 2046 1024 0 1024 2048 1025 1 1 2 1026 0 2 4 1027 1 3 6 1028 0 4 8 blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon PTFs process rows in batches Empirical testing shows this as units of 1,024 rows (whether this is a hard limit is TBC) After fetching this many rows, the PTF calls fetch_rows again So this resets the counter If you write PTFs which have running counters or aggregations, you'll need to save the execution state You can do this with dbms_tf.xstore procedures
  • 24. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | for clmn in 1 .. env.ref_put_col.count loop dbms_tf.xstore_get('col' || clmn, last_row); for rw in 1 .. env.row_count loop col ( rw ) := ( rw + last_row ) * clmn; end loop; dbms_tf.put_col ( clmn, col ); dbms_tf.xstore_set ( 'col' || clmn, last_row + env.row_count ); end loop; blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon The xstore holds key- value pairs If you get a non- existent key, the input value is unchanged
  • 25. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | How do I debug it? Gratisography
  • 26. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | dbms_tf.trace ( env => dbms_tf.get_env() ); dbms_tf.trace ( msg => 'Your text here' ); blogs.oracle.com/sql www.youtube.com/c/TheMagicOfSQL @ChrisRSaxon The dbms_tf.trace procedure has several overloads which allow you to view the current execution state In my experience, the most useful are: • env; this displays the whole execution state • msg; which allows you to add your own text Like dbms_output, tracing displays the results on screen, not in a database table or view
  • 27. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | Now it's over to you! Where canYou can find many PTF examples on https://livesql.oracle.com
  • 28. Copyright © 2019, Oracle and/or its affiliates. All rights reserved. | asktom.oracle.com #AskTOMOfficeHours Ryan McGuire / Gratisography