欢迎使用WebCHM(原WebSeizer测试版)

软件简介

： WebCHM
： 全站下载打包仪
： 2.14版
： 朱晓峰
：zhu_xfcn@163.com
： 正式推出IE右键菜单功能。。

WebCHM（原WebSeizer测试版）是多线程离线浏览软件，专业的下载大型网站的工具，大小1000KB左右，支持断点续传，支持在线升级，具有对下载信息进行分类管理的功能，操作方便，体贴用户。它可以方便地下载书库网站中的某一篇你感兴趣的文章，甚至可以将整个网站拉到硬盘慢慢看。在下载了喜欢的文章后，还可以用WebCHM直接打包为CHM格式的电子书籍，既方便浏览，又节省空间。由于宽带上网的普及，将整个大型网站下载下来不再是梦想，而WebCHM这一强力工具应运而生，经过测试，可以下载容量达到10GB以上，文件数量达到100万个以上的网站。WebCHM对小型网站的支持也很有力，是目前唯一能下载java链接的离线浏览器软件，而且支持需要登陆的网站，以前很难下载的论坛、BBS等，现在除了一些结构特别复杂的，大部分也可用WebCHM下载。 具体功能如下：

1、可以下载整个网站所有的网页、文件，也可以灵活地指定下载范围和下载的层次，如只下载同一个目录的文件，或者下载特定的几个目录内的文件。

2、是目前唯一能下载java链接的离线浏览器软件。

3、可以提取下载网站的一部分打包成CHM格式的电子书籍,用于在PDA等移动工具上阅读。也是唯一不使用其他辅助程序就可独立完成CHM打包的离线浏览软件。

4、可以建立CHM任务，非常适用于文件数量很多的任务，所谓CHM任务,就是在网页下载后的所有文件不保存到硬盘，而是直接压缩到到CHM文件制成电子书，可以节省大量空间。

5、在下载大型网站的技术上有独到之处，可以下载容量达到数个GB，文件数量达到10万个以上网站。

6、支持需要登陆的网站，如：论坛、BBS等.

7、支持HTTP代理服务器,支持出错重试。

8、支持‘修补’功能，能修复一次下载不成功的网页/文件。

9、支持‘更新’功能，在任务下载数月后执行更新功能，就可以自动识别下载过的网页/文件在网上是否更新过，减少重复下载。

10、支持‘自动更新’功能，能在下载的同时判断图片/文件是否在硬盘上已经存在，并且判断是否最新文件，减少重复下载。

11、支持多线程下载。

12、可根据URL地址设置过滤，只下载所需网页/文件。

13、支持任务和目录的拖拽操作，更方便用户分类管理任务。

14、支持‘重新开始’功能，能重新启动下载任务。

15、可以为CHM文件生成书签、目录、标题搜索等辅助阅读功能。

16、附带工具CHM浏览器具有简单的CHM文档编辑功能,可以用来制作电子书。能拖放目录、文件到CHM浏览器打开的CHM文档中,可以自动生成CHM文档的目录（Table of Content）,也可将一个XML文件转化为目录TOC,还可以改变CHM文档的首页、标题等属性。


安装说明

： WebCHM
： 全站下载打包仪
： 2.14版
： 朱晓峰
：zhu_xfcn@163.com
： 正式推出IE右键菜单功能。

离线浏览软件WebCHM的有两种发布形式，一种是一个自解压缩文件，运行此文件后就会在释放所有文件到WebCHM文件夹。解压完成后，就会运行软件，并在桌面上生成一个快捷方式。除此之外，软件对系统改动很小，所以删除软件时，不需要运行控制面板的“添加/删除程序”，只需要运行软件自带的工具菜单中的删除功能就可以了。
另外一种发布形式是installsheild安装包，删除软件时可以运行控制面板的“添加/删除程序”。


快速入门

实例1-下载一本书
以《爬爬书库》里收录的文章《龙枪编年史》为例，它的下载地址是http://www.3320.net/blib/c/read/3/1210/index.html，共有三大卷，一百多章，如果要一篇一篇地下载，显然要花不少的时间。而用WebSeizer只要点击几下鼠标就可以解决这个问题。先在WebSeizer主界面的"首页地址"栏中输入上述的网址，然后点击第一个工具按钮--"任务"按钮来新建一个任务，或者在任务菜单选取“新建”菜单项。点击后，会出现设置选项的对话框，如图所示：

在下载范围中选择"只下载当前目录"，也就是只下载目录http://www.3320.net/blib/c/read/3/1210/ 下的文件。下载层数选择缺省的"-1"。下载层数为"-1"，指的是下载从首页开始点击无数次鼠标能浏览到的网页，由于限定了下载范围是"当前目录"，所以就只下载这个目录下的所有文件。如果下载层数为"1"，指的是下载从首页开始点击一次鼠标能浏览到的网页，下载层数为"3"，指的是下载从首页开始点击三次鼠标能浏览到的网页。点击"OK"确认过后，再指定一下保存的地址就开始下载了，简单吧。下载完第一个页面，会跳出一个目录选择对话框，让你选择除了当前目录，还要下载哪些目录的内容，这是为那些文章的索引与内容不在同一个目录下准备的，这里不用选择直接点击"OK"跳过就可以了。几分钟之后，文章就都下载完了，出现一个对话框，显示"任务结束，共下载162个文件，2714632字节"，点击"OK"后就可以慢慢观看了。下载后的文件保存在一开始指定的目录下，而且按原来网站的目录结构保存，所以文章就保存在目录
/指定的目录/www.3320.net/blib/c/read/3/1210/下面。
另外一种下载方案是下载层数选择1，下载范围选择"当前域名"。软件就会下载网站内从http://www.3320.net/blib/c/read/3/1210/index.html开始点击一次鼠标能浏览到的网页。这种方案下载会下载一些多余的内容，但是适合于网站结构比较复杂，而你又不想设置目录选择对话框的情况。

实例2-下载整个网站
 如果您的野心比较大，要下载整个《书库》，制作整个网站的镜像，软件WebSeizer完全可以满足您的要求，只要在设置里将下载范围改为"当前域名"就可以了，下载层数还是选择缺省的"-1"。经过测试WebSeizer完全可以满足下载大型网站的要求，下载容量可达数个GB，文件数十万个也没有问题。一次下载不完可以保存任务，下一次上网的时候载入任务并且运行它，直到下完为止。

实例3-下载新闻网站
 比如说，要下载新闻网站http://news.sohu.com/,此时的下载范围不能用"当前域名"，而要改为"当前网站"。因为有一部分的新闻在http://it.sohu.com/、http://yule.sohu.com/等域名中。选用"当前网站"就可以下载类似于http://***.sohu.com/的所有域名下的文件。


制作CHM格式的电子书籍

WebSeizer中制作CHM格式的电子书籍有好几种方式，可以灵活选择：
一、将任务中的文件压缩到一个CHM文件，适用于文件数量较小的任务。
如：要将《猛虎王朝》这本书制成电子书。先选取任务，点击右键，弹出右键菜单，将任务载入内存，再选取“压缩成CHM文件到”子菜单，就可以将任务中的文件打包压缩到指定的路径。一开始，子菜单中没有路径名称，需要在“发送路径设置”中添加发送路径。添加后就会增加相应的路径子菜单项。
注意：为了方便PDA（掌上电脑）用户阅读CHM电子书，当下载范围是“当前目录”，就只发送当前目录的网页文件，而不发送其它目录的图片等其它文件，以简化CHM文件结构，以防止复杂的目录结构PDA软件阅读不了。

二、建立CHM任务，适用于文件数量很多的任务。
所谓CHM任务，就是网站下载后的文件不保存到硬盘，而是直接压缩到到CHM文件中。建立CHM任务的好处有很多，如;
1、节省空间。
2、便于将CHM文件删除、复制、剪贴，当任务中文件数量很多时，效果特别明显，因为此时删除、复制文件将花费巨量的时间。
当文件数量>10000个时，会自动分卷压缩，分卷后的CHM文件名为 任务名.chm、任务名1.chm、任务名2.chm、......
具体的情况将在下一章“建立CHM任务”中介绍。

三、将任务中的一个目录打包压缩为CHM格式的电子书籍。
方法是：任务载入后在“工具”菜单中“任务结构”，选取“目录结构”，选择需要打包的目录，点击右键，在弹出菜单中选择“将此目录打包为CHM文件”。

四、CHM文件浏览器
WebSeizer内置了一个简单的CHM文件浏览器，可以查看CHM文件内部的目录、文件，并且可以解压小型的CHM文件。能拖放目录、文件到CHM浏览器打开的CHM文件中,可以自动生成CHM文档的目录（Table of Content）,还可以改变CHM文档的首页、标题等属性,实现了简单的WebCHM文档编辑功能。在工具菜单中点击"CHM文件浏览器"就可以使用这个工具。


建立CHM任务

CHM任务非常适用于文件数量很多的任务。所谓CHM任务,就是网页下载后的文件不保存到硬盘，而是直接压缩到到CHM文件制成电子书。当任务中文件数量很多时，删除、复制文件将花费巨量的时间,而建立CHM任务后,文件占用的空间大大减小了,而且当文件数量>10000个时，会自动分卷压缩，分卷后的CHM文件名为 任务名.chm、任务名1.chm、任务名2.chm、......,网站的目录建立在CHM文件的内部,系统在复制,删除CHM文件时不用在处理文件目录上花时间,速度会加快10倍以上,甚至更多。建立CHM任务的好处还有很多，有;

1、节省磁盘空间。CHM压缩文件本身就使用LZX算法对文件进行压缩，而且再算上由于小文件产生的磁盘空隙，目录占用的空间等原因，节省的空间更多。

2、便于文件的删除、复制、剪贴等操作。

3、CHM任务可以使用软件自带的CHM工具生成标题搜索功能,可以更快地找到文件。

4、CHM文件有书签功能,可以保存喜爱的文章的位置。

一、如何建立CHM任务

在新建任务时,在对话框的"建立CHM任务"选择项中选上勾就可以了。CHM任务的图标与一般的任务图标不一样,一般任务的图标是电脑形状,而CHM任务的图标是CHM文件的图标,如下图所示:

二、用CHM工具对CHM任务进行处理

在CHM任务下载完成后,仅仅是将下载的文件保存在CHM文件里,虽然可以当作电子书来阅读,但是还不具备目录,标题搜索等辅助阅读功能,使用起来还不方便,这就需要使用CHM工具进行处理。在下载过程中遇到死机等异常情况,会导致CHM文件损坏,也需要CHM工具来修补,修补过程中可能要丢失一些文件,可以使用CHM工具的复核功能来检查哪些文件丢失了,并将那些文件置为"未下载"状态以便于重新下载。CHM文件还有一个特性,在CHM压缩文件中删除一个文件,被删的文件所占用的磁盘空间不会被释放,在下载过程中会删除一些临时文件,所以必要时可以使用CHM工具的压缩功能来减小CHM文件大小。

当载入一个CHM任务后,点击此任务名,会在工具栏的"停止"与"更新"按钮的中间出现"CHM工具"按钮。

点击"CHM工具"按钮后,会出现一个对话框,其中有很多选项,选择要进行的处理后确定就可以了。一般建议下载完成后最好要选择"生成目录"和"生成标题搜索功能"。为了节省生成的时间,目前只为一个目录的Index.htm,Index.asp等文件生成目录和标题搜索功能,一般书库网站的一本书的文章都存放在一个目录下,所以这样可以照顾到每一本书,花的时间也最少。而且“CHM工具”只为网页的标题生成搜索，花费的时间极少，而不是像常规的生成全文搜索（Full Text Search）那样，为了生成搜索花的时间比下载的时间还要多，占用的空间也相当于原有文件的总大小。


智能过滤功能

    WebCHM2.11版更加智能化，改进了多首页系统和过滤功能。 可以更加灵活地确定下载范围，可以只下载所需的特定的内容，缩小了下载的范围，节省了下载的时间。
    载入了任务后，在局部设置面板中可以设置过滤功能。WebCHM的智能过滤功能包括4种过滤方式，其中两种下载过滤，两种更新过滤。其中正向下载过滤是指网页文件名中必须包含特定的关键字，它的有效范围是任务的所有网页文件；而反向下载过滤是指文件名中不能包含特定的关键字，它的有效范围是任务的所有的文件，包括网页、图片、JS文件等。更新过滤是指在执行更新下载任务时采用的过滤设置。


版本变化

各个版本的变化

/WebSeizer 1.06.1780 生成托盘图标。
/WebSeizer 1.07 增加了将下载后的网页打包为CHM格式的电子书籍的功能。
/WebSeizer 1.07.2108 增加了支持HTTP代理服务器的功能。
/WebSeizer 1.08 实现了UTF-8解码。
/WebSeizer 1.09.3508 可以在网站下载后不保存，而是直接压缩到到CHM文件制成电子书,当文件数目太多时(>10000)，可以分成数个CHM文件分卷压缩。
/WebSeizer 1.09.4473 增加CHM文件修补、压缩、生成目录（Table of Content）等功能。
/WebSeizer 1.10-1.12 完善了CHM任务的下载、解析等，能自动修改网页中不适合在CHM文件中显示的元素，使之能正常显示。对数据结构作了优化，提高了解析速度。
/WebSeizer 1.13 可以为CHM文件生成标题搜索功能。
/WebSeizer 1.14 改进了CHM文件修补功能。
/WebSeizer 2.00-2.02 对数据结构作了重大的改进,建立了动态目录结构,处理动态网页的速度有了很大的提高。
/WebSeizer 2.03-2.05 完善了制作在PDA上阅读的CHM电子书功能。
/WebCHM 2.06-2.07 软件改名为WebCHM。实现了出错重试功能。
/WebCHM 2.08 实现了escape解码。
/WebCHM 2.09 增强了附带工具CHM浏览器的功能,能拖放目录、文件到CHM浏览器打开的CHM文件中,能将XML文件转化为CHM文档的目录TOC,还可以改变CHM文档的首页、标题等属性,实现了简单的CHM文档编辑功能,可以用来制作电子书。
/WebCHM 2.10-2.11 为了软件更加智能化，更好地确定下载范围，改进了多首页系统和过滤功能。
/WebCHM 2.13 改进了登陆功能，可以自动Post登陆数据。。
/WebCHM 2.14 正式推出IE右键菜单，并将发布形式从自解压包改为installsheild安装包。


常见问题

问:
你好，我是天津的，我正在用你开发的webseizer软件，很不错，很是佩服你。现在有几个问题想向你请教，我用这个软件下载小型的网站感觉很不错，下载完以后基本上都可以连接上，可当我下载像新华网这样的大网站的时候，我用了三天才基本上下载完，不过下载的时候很多都出错了，到了第二层就全都链接不上了，不知道是怎么回事，我在设置下载属性的时候，选择的是下载网站所有内容，当前域名，层数是-1，只下载本站内容，可下载完以后还是连不上，很奇怪，请你指教，谢谢！！！！
答:
  感谢帮助测试本软件。您所说新华网的问题原因是这样的：
由于下载范围选择了“当前域名”只能下载http://www.xinhuanet.com/域名下的文件，而第二层链接有许多是http://news.xinhuanet.com域名下的文件。所以要想下载这样的大型网站，下载范围应当选择“当前网站”，这样就能将所有类似于http://？？？.xinhuanet.com的域名下的文件都下载下来。希望继续支持本软件。

问:
我用这个下载http://ro.cga.com.cn\map\bigmap8.htm
结果只能下载1页，不知道这个网站用了什么方式，我对这个不太了解，你能帮我看看为什么只能下载1页，不能下载其他东西下来好吗？
答:
只要注意以下几个问题就可以顺利下载。
1、最主要的问题是设置中，下载范围要选择“当前域名”，而不能选择“本目录”，因为下一层连接如“http://ro.cga.com.cn/fild/mjolnir_02.htm”不在同一个目录下。
2、此网页的正确写法是：http://ro.cga.com.cn/map/bigmap8.htm

问:
webseizer确实是个好软件，建议喜欢看小说的朋友都用一用，它的强大功能不用我说了比webzip或OfflineExplorer好用多了。但最近在使用时遇到一个问题，比如我下载某个网站但没下完，后来我把WebSiezer所在的文件夹包括websiezer程序本身和相关的程序移动到另外一个文件夹里，这是再打开websiezer发现原来没完成的任务消失了，重新载入那个没完成的任务后发现已下载的信息全部丢失，包括下载文件数和下载大小等等，没办法我只好从头在来。
答:
yemao,您好！
谢谢你对本软件的关心。文件夹移动后会导致软件找不到原来的路径，解决的办法是在文件菜单中导入原来的任务文件（以.web为后缀的文件）。


Oracle Analytic Functions
Version 11.1

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
AVG

Returns a running average 		AVG(DISTINCT | ALL <expression>) OVER (analytic clause)
CREATE TABLE vote_count (
submit_date  DATE NOT NULL,
num_votes    NUMBER NOT NULL);

INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-4, 100);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-3, 150);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-2, 75);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-3, 25);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-1, 50);
COMMIT;

SELECT * FROM vote_count;

SELECT submit_date, num_votes, TRUNC(AVG(num_votes)
OVER(ORDER BY submit_date ROWS UNBOUNDED PRECEDING)) AVG_VOTE_PER_DAY
FROM vote_count
ORDER BY submit_date;

SELECT submit_date, num_votes, TRUNC(AVG(num_votes)
OVER(PARTITION BY submit_date ORDER BY submit_date ROWS UNBOUNDED PRECEDING)) AVG_VOTE_PER_DAY
FROM vote_count
ORDER BY submit_date;
CORR

Returns the coefficient of correlation of a set of number pairs 		CORR(<expression1>, <expression2>) OVER (<analytic clause>)
conn sh/sh

SELECT t.calendar_month_number,
CORR (SUM(s.amount_sold), SUM(s.quantity_sold))
OVER (ORDER BY t.calendar_month_number) AS CUM_CORR
FROM sales s, times t
WHERE s.time_id = t.time_id AND calendar_year = 1998
GROUP BY t.calendar_month_number;
COUNT

Returns a running count of all records or by partition 		COUNT(<*, [DISTINCT | ALL] <expression>>) OVER (<analytic clause>)
SELECT submit_date, num_votes, TRUNC(COUNT(num_votes)
OVER(ORDER BY submit_date ROWS UNBOUNDED PRECEDING)) AS DAY_COUNT
FROM vote_count
ORDER BY submit_date;

SELECT submit_date, COUNT(*)
OVER(PARTITION BY submit_date ORDER BY submit_date
ROWS UNBOUNDED PRECEDING) NUM_RECS
FROM vote_count;

Return a frequency distribution 		CREATE TABLE myprods (
prod1 NUMBER(3),
prod2 NUMBER(3),
prod3 NUMBER(3));

INSERT INTO myprods VALUES (34,23,45);
INSERT INTO myprods VALUES (34,22,34);
INSERT INTO myprods VALUES (54,44,45);
INSERT INTO myprods VALUES (23,22,45);
INSERT INTO myprods VALUES (45,22,34);

SELECT prod1, COUNT(prod1) OVER (PARTITION BY prod1) freq1,
       prod2, COUNT(prod2) OVER (PARTITION BY prod2) freq2,
       prod3, COUNT(prod3) OVER (PARTITION BY prod3) freq3
FROM myprods;
COVAR_POP

Returns the population covariance of a set of number pairs 		COVAR_POP(<expression1>, <expression2>) OVER (<analytic clause>)
conn oe/oe

SELECT job_id,
COVAR_POP(SYSDATE-hire_date, salary) AS covar_pop,
COVAR_SAMP(SYSDATE-hire_date, salary) AS covar_samp
FROM employees
WHERE department_id in (50, 80)
GROUP BY job_id;
COVAR_SAMP
Returns the sample covariance of a set of number pairs | COVAR_SAMP(<expression1>, <expression2>) OVER (<analytic clause>)
See COVAR_POP Demo above
CUME_DIST

Returns the cumulative distribution of a value in a group of values 		CUME_DIST(<value>) OVER (<partition_clause> <order by clause>)
conn oe/oe

SELECT job_id, last_name, salary, CUME_DIST()
OVER (PARTITION BY job_id ORDER BY salary) AS cume_dist
FROM employees
WHERE job_id LIKE 'PU%';
DENSE_RANK

Ranks items in a group leaving no gaps in ranking sequence when there are ties 		DENSE_RANK() OVER (<query_partition_clause> <order_by_clause>)
conn oe/oe

SELECT d.department_name, e.last_name, e.salary, DENSE_RANK()
OVER (PARTITION BY e.department_id ORDER BY e.salary) AS DENSE_RANK
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND d.department_id IN (30, 60);
FIRST

Returns the row ranked first using DENSE_RANK 		SELECT <aggregate_function(column_name)> KEEP
(DENSE_RANK FIRST ORDER BY <column_name> [<ASC|DESC> NULLS <FIRST|LAST>)
OVER (PARTITION BY <column_name>)
FROM <table_name>
GROUP BY <column_name>;
conn oe/oe

SELECT last_name, department_id, salary,
MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct)
OVER (PARTITION BY department_id) "Worst",
MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct)
OVER (PARTITION BY department_id) "Best"
FROM employees
WHERE department_id IN (30, 60)
ORDER BY department_id, salary;
FIRST_VALUE

Returns the first value in an ordered set of values. If the first value in the set is null, then the function returns NULL unless you specify IGNORE NULLS 		FIRST_VALUE(<expression> [IGNORE NULLS])
OVER (<analytic clause>)

conn oe/oe

SELECT last_name, salary, hire_date, FIRST_VALUE(hire_date)
OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date);

IGNORE NULLS

The following is a minor modification of a demo published in the November/December 2006 issue of Oracle Magazine by Tom Kyte 		(<column_name> IGNORE NULLS)

CREATE TABLE t1 (
row_num NUMBER(3),
col1 VARCHAR2(15),
col2 VARCHAR2(15));

INSERT INTO t1 VALUES (6, NULL, NULL);
INSERT INTO t1 VALUES (1, 'Category 1', 'Mango');
INSERT INTO t1 VALUES (2, NULL, NULL);
INSERT INTO t1 VALUES (3, NULL, NULL);
INSERT INTO t1 VALUES (4, NULL, 'Banana');
INSERT INTO t1 VALUES (5, NULL, NULL);
INSERT INTO t1 VALUES (6, NULL, NULL);
INSERT INTO t1 VALUES (7, 'Category 2', 'Vanilla');
INSERT INTO t1 VALUES (8, NULL, NULL);
INSERT INTO t1 VALUES (9, 'Category 3', 'Strawberry');
COMMIT;

SELECT * FROM t1;

SELECT row_num,
LAST_VALUE(col1 IGNORE NULLS) OVER (ORDER BY row_num) col1,
LAST_VALUE(col2 IGNORE NULLS) OVER (ORDER BY row_num) col2
FROM t1
ORDER BY row_num;

LAG
LAG provides access to more than one row of a table at the same time without a self-join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position. LAG(<value expression>, <offset>, <default>)
OVER ([<query partition clause>] <order_by_clause>)
conn oe/oe

SELECT last_name, hire_date, salary,
LAG(salary, 1, 0) OVER (ORDER BY hire_date) AS PREV_SAL
FROM employees
WHERE job_id = 'PU_CLERK';
LAST
Returns the row ranked last using DENSE_RANK <aggregate function> KEEP (DENSE_RANK LAST ORDER BY
(<expression> <ASC | DESC> NULLS <FIRST | LAST>)
See FIRST Demo above
LAST_VALUE
Returns the last value in an ordered set of values. If the last value in the set is null, then the function returns NULL unless you specify IGNORE NULLS. This setting is useful for data densification. If you specify IGNORE NULLS, then LAST_VALUE returns the first non-null value in the set, or NULL if all values are null. | LAST_VALUE (<expression> IGNORE NULLS) OVER (<analytic clause>)
conn oe/oe

SELECT last_name, salary, hire_date, FIRST_VALUE(hire_date)
OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
FROM (SELECT * FROM employees WHERE department_id = 90
ORDER BY hire_date);
LEAD

LEAD provides access to a row at a given physical offset beyond that position 		LEAD(<expression, offset, default>)
[(<query_partition_clause>)]
OVER (<order_by_clause>)
SELECT submit_date, num_votes,
LEAD(num_votes, 1, 0) OVER (ORDER BY submit_date) AS NEXT_VAL
FROM vote_count;
MAX

Returns the maximum value by partition 		MAX (<DISTINCT | ALL> expression) OVER (<analytic clause>)
conn oe/oe

SELECT manager_id, last_name, salary
FROM (
  SELECT manager_id, last_name, salary,
  MAX(salary) OVER (PARTITION BY manager_id) AS rmax_sal
  FROM employees)
WHERE salary = rmax_sal;
MIN

Returns the minimum value by partition 		MIN (<DISTINCT | ALL> expression) OVER (<analytic clause>)
conn oe/oe

SELECT manager_id, last_name, salary
FROM (
  SELECT manager_id, last_name, salary,
  MAX(salary) OVER (PARTITION BY manager_id) AS rmax_sal
  FROM employees)
WHERE salary = rmax_sal;
NTILE
Divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr. The expr value must resolve to a positive constant for each partition. | NTILE (<expression>) OVER ([query_partition_clause] <order by clause>)
conn oe/oe

SELECT last_name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees
WHERE department_id = 100;
OVER PARTITION BY

This demo returns employees that
are making above average salary in their respective department 		NTILE (<expression>) OVER ([query_partition_clause] <order by clause>)
conn hr/hr

col ename format a30
col department_name format a20

SELECT * FROM (
  SELECT e.ffirst_name || ' ' || e.last_name ENAME, d.department_name,
  e.salary, TRUNC(e.salary - avg(e.salary) OVER (PARTITION BY
  e.department_id)) sal_dif
FROM employees e, departments d
WHERE e.department_id=d.department_id)
WHERE sal_dif > 0
ORDER BY 2,4 DESC;
PERCENT_RANK
For a row r, PERCENT_RANK calculates the rank of r minus 1, divided by 1 less than the number of rows being evaluated (the entire query result set or a partition). | PERCENT_RANK(<value>) OVER (<partition_clause> <order_by_clause>)
conn oe/oe

SELECT department_id, last_name, salary, PERCENT_RANK()
OVER (PARTITION BY department_id ORDER BY salary DESC) AS pr
FROM employees
ORDER BY pr, salary;
PERCENTILE_CONT
Inverse distribution function that assumes a continuous distribution model. It takes a percentile value and a sort specification, and returns an interpolated value that would fall into that percentile value with respect to the sort specification. Nulls are ignored in the calculation. | PERCENTILE_CONT(<value>) WITHIN GROUP (ORDER BY <expression> [ASC | DESC]) OVER (<partition_clause>)
conn oe/oe

SELECT last_name, salary, department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary DESC)
OVER (PARTITION BY department_id) PCT_CONT, PERCENT_RANK()
OVER (PARTITION BY department_id ORDER BY salary DESC) PCT_RANK
FROM employees
WHERE department_id IN (30, 60);
PERCENTILE_DISC
An inverse distribution function that assumes a discrete distribution model. It takes a percentile value and a sort specification and returns an element from the set. Nulls are ignored in the calculation. | PERCENTILE_DISC(<expression>) WITHIN GROUP (ORDER BY <order_by_clause>)
conn oe/oe

col cume_dist format 9.999

SELECT last_name, salary, department_id,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC)
OVER (PARTITION BY department_id) PCT_DISC,
CUME_DIST() OVER (PARTITION BY department_id
ORDER BY salary DESC) CUME_DIST
FROM employees
WHERE department_id IN (30, 60);
RANK

Calculates the rank of a value in a group of values 		RANK(<value>) OVER (<partition_clause> ORDER BY <order_by_clause>)
conn oe/oe

SELECT department_id, last_name, salary, commission_pct,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC, commission_pct) "Rank"
FROM employees
WHERE department_id = 80;

/* The following query finds the 5 top-selling products for each product subcategory where that product contributes more than 20% of the sales within its product category. */
conn sh/sh

col categ format a15
col prod_subcategory format a20

SELECT SUBSTR(prod_category,1,8) AS CATEG, prod_subcategory, prod_id, sales
FROM (
  SELECT p.prod_category, p.prod_subcategory, p.prod_id,
  SUM(amount_sold) as SALES, SUM(SUM(amount_sold))
  OVER (PARTITION BY p.prod_category) AS CAT_SALES,
  SUM(SUM(amount_sold))
  OVER (PARTITION BY p.prod_subcategory) AS SUBCAT_SALES,
  RANK() OVER (PARTITION BY p.prod_subcategory
  ORDER BY SUM(amount_sold) ) AS RANK_IN_LINE
  FROM sales s, customers c, countries co, products p
  WHERE s.cust_id = c.cust_id
  AND c.country_id = co.country_id
  AND s.prod_id = p.prod_id
  AND s.time_id = TO_DATE('11-OCT-2000')
  GROUP BY p.prod_category, p.prod_subcategory, p.prod_id
  ORDER BY prod_category, prod_subcategory)
WHERE SUBCAT_SALES > 0.2 * CAT_SALES
AND RANK_IN_LINE<=5;
RATIO_TO_REPORT
Computes the ratio of a value to the sum of a set of values. If expr evaluates to null, then the ratio-to-report value also evaluates to null. | RATIO_TO_REPORT(<value>) OVER (<partition_clause>)
conn oe/oe

SELECT last_name, salary, RATIO_TO_REPORT(salary) OVER () AS RR
FROM employees
WHERE job_id = 'PU_CLERK';
REGR_ (Linear Regression) Functions
Generic Syntax | FUNCTION_NAME (<expression1>,<expression2>) OVER (<analytic_clause>)

REGR_AVGX 		-- see REGR_AVGX Demo

conn oe/oe

SELECT job_id, employee_id ID, salary,
REGR_SLOPE(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) slope,
REGR_INTERCEPT(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) intcpt,
REGR_R2(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) rsqr,
REGR_COUNT(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) count,
REGR_AVGX(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) avgx,
REGR_AVGY(SYSDATE-hire_date, salary)
OVER (PARTITION BY job_id) avgy
FROM employees
WHERE department_id in (50, 80)
ORDER BY job_id, employee_id;

REGR_AVGY 		-- see REGR_AVGX Demo

conn oe/oe

SELECT job_id,
REGR_AVGY(SYSDATE - hire_date, salary) avgy,
REGR_AVGX(SYSDATE - hire_date, salary) avgx
FROM employees
WHERE department_id in (30, 50)
GROUP BY job_id;

REGR_COUNT 		-- see REGR_AVGX Demo

conn oe/oe

SELECT job_id,
REGR_COUNT(SYSDATE-hire_date, salary) count
FROM employees
WHERE department_id in (30, 50)
GROUP BY job_id;

REGR_INTERCEPT 		-- see REGR_AVGX Demo

conn oe/oe

SELECT job_id,
REGR_SLOPE(SYSDATE - hire_date, salary) slope,
REGR_INTERCEPT(SYSDATE - hire_date, salary) intercept
FROM employees
WHERE department_id in (50,80)
GROUP BY job_id
ORDER BY job_id;

REGR_R2 		-- see REGR_AVGX Demo

conn oe/oe

SELECT job_id, REGR_R2(SYSDATE-hire_date, salary) Regr_R2
FROM employees
WHERE department_id IN (50, 80)
GROUP by job_id;
REGR_SLOPE See REGR_AVGX Demo
See REGR_INTERCEPT Demo

REGR_SXX 		conn oe/oe

SELECT job_id,
REGR_SXY(SYSDATE - hire_date, salary) regr_sxy,
REGR_SXX(SYSDATE - hire_date, salary) regr_sxx,
REGR_SYY(SYSDATE - hire_date, salary) regr_syy
FROM employees
WHERE department_id in (50, 80)
GROUP BY job_id
ORDER BY job_id;
REGR_SXY | See REGR_SXX Demo
REGR_SYY | See REGR_SXX Demo
ROW_NUMBER

Assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order by clause, beginning with 1. 		ROW_NUMBER(<value>) OVER (<partition_clause> ORDER BY <order_by_clause>)
CREATE TABLE test (
id      NUMBER(1),
degrees NUMBER(3));

INSERT INTO test VALUES (0,235);
INSERT INTO test VALUES (0,276);
INSERT INTO test VALUES (1,211);
INSERT INTO test VALUES (1,250);
INSERT INTO test VALUES (1,255);
INSERT INTO test VALUES (2,55);
INSERT INTO test VALUES (2,277);
INSERT INTO test VALUES (2,69);
INSERT INTO test VALUES (3,25);
INSERT INTO test VALUES (3,166);
INSERT INTO test VALUES (3,262);
INSERT INTO test VALUES (4,47);
INSERT INTO test VALUES (4,238);
INSERT INTO test VALUES (4,40);
COMMIT;

SELECT * FROM test;

-- choose the starting cell
SELECT id, degrees s
FROM (
  SELECT id, degrees, (360 - degrees) d360,
  ROW_NUMBER() OVER(PARTITION BY id
  ORDER BY CASE
    WHEN (degrees < 360 - degrees) THEN degrees
    ELSE 360 - degrees
    END) rn
  FROM test) t
WHERE rn = 1;

-- order the rest clockwise
SELECT *
FROM (
  SELECT t.id, t.degrees,
  ROW_NUMBER() OVER(PARTITION BY t.id
  ORDER BY CASE
    WHEN (t.degrees < starting_cell.degrees) THEN t.degrees + 360
    ELSE t.degrees
    END) rn
  FROM test t
JOIN (
  SELECT id, degrees, (360 - degrees) d360,
  ROW_NUMBER() OVER(PARTITION BY id
  ORDER BY CASE
    WHEN (degrees < 360 - degrees) THEN degrees
    ELSE 360 - degrees
    END) rn
  FROM test) starting_cell
  ON t.id = starting_cell.id
  WHERE starting_cell.rn=1)t
ORDER BY id, rn;
STDDEV

Returns the sample standard deviation of an expression 		STDDEV([DISTINCT | ALL] <expression>) OVER (<analytic_clause>)
conn oe/oe

col stddev format 99999.999

SELECT last_name, salary,
STDDEV(salary) OVER (ORDER BY hire_date) "StdDev"
FROM employees
WHERE department_id = 30;
STDDEV_POP
Computes the population standard deviation and returns the square root of the population variance | STDDEV_POP(<expression>) OVER (<analytic_clause>)
conn oe/oe

SELECT department_id, last_name, salary,
STDDEV_POP(salary) OVER (PARTITION BY department_id) AS pop_std
FROM employees;
STDDEV_SAMP

Computes the cumulative sample standard deviation and returns the square root of the sample variance. 		STDDEV_SAMP(<expression>) OVER (<analytic_clause>)
conn oe/oe

SELECT department_id, last_name, hire_date, salary,
STDDEV_SAMP(salary) OVER (PARTITION BY department_id
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sdev
FROM employees;
SUM

Computes the cumulative sample running sum

Corrected thanks to a note from Mette Stephansen in Denmark.
CREATE TABLE vote_count (
submit_date  DATE NOT NULL,
num_votes    NUMBER NOT NULL);

INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-4, 100);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-3, 150);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-2, 75);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-3, 25);
INSERT INTO vote_count VALUES (TRUNC(SYSDATE)-1, 50);
COMMIT;

SELECT * FROM vote_count;

SELECT submit_date, num_votes, SUM(num_votes)
OVER(ORDER BY submit_date ROWS UNBOUNDED PRECEDING) TOT_VOTE
FROM vote_count
ORDER BY submit_date;
VAR_POP

Returns the population variance of a set of numbers 		VAR_POP(<value>) OVER (<analytic_clause>)
conn sh/sh

SELECT t.calendar_month_desc, VAR_POP(SUM(s.amount_sold))
OVER (ORDER BY t.calendar_month_desc) "Var_Pop",
VAR_SAMP(SUM(s.amount_sold))
OVER (ORDER BY t.calendar_month_desc) "Var_Samp"
FROM sales s, times t
WHERE s.time_id = t.time_id AND t.calendar_year = 2001
GROUP BY t.calendar_month_desc;
VAR_SAMP
Returns the sample variance of a set of numbers | VAR_SAMP(<value>) OVER (<analytic_clause>)
See VAR_POP Demo above
VARIANCE

Returns the variance of an expression 		VARIANCE([DISTINCT | ALL] <value>) OVER (<analytic_clause>)
conn oe/oe

SELECT last_name, salary,
VARIANCE(salary) OVER (ORDER BY hire_date) AS VARIANCE
FROM employees
WHERE department_id = 30;
Additional Demos
Another example:

This one written by Maxim Demenko 		CREATE TABLE test (id, quality, weight) AS
SELECT 1,'A',10 FROM dual UNION ALL
SELECT 2,'A',11 FROM dual UNION ALL
SELECT 3,'A',12 FROM dual UNION ALL
SELECT 4,'B',11 FROM dual UNION ALL
SELECT 5,'B',19 FROM dual UNION ALL
SELECT 6,'A',9 FROM dual UNION ALL
SELECT 7,'A',14 FROM dual UNION ALL
SELECT 8,'C',4 FROM dual UNION ALL
SELECT 9,'C',7 FROM dual;

SELECT *
FROM test;

SELECT MAX(id) ID, MAX(quality) QUALITY, SUM(weight) WEIGHT
FROM (
  SELECT id, quality, weight, SUM(new_seq) OVER (ORDER BY id) new_grp
  FROM (
    SELECT id, quality, weight, DECODE(LAG(quality) OVER (ORDER BY id),
    quality, 0, id) new_seq
FROM test))
GROUP BY new_grp
ORDER BY 1;
Related Topics
Date Functions
Numeric Functions
Rank
String Functions
Contact Us � Legal Notices and Terms of Use � Privacy Statement


Oracle Built-in Functions
Version 10.2
Function Name | Analytic | Collection | Conver sion | Date Time | Data Mining | Misc. | Model Clause | Null Handling | Numeric | Object | String | XML
ABS |  |  |  |  |  |  |  |  |  |  |  |
ACOS |  |  |  |  |  |  |  |  |  |  |  |
ADD_MONTHS |  |  |  |  |  |  |  |  |  |  |  |
ADJ_DATE |  |  |  |  |  |  |  |  |  |  |  |
APPENDCHILDXML |  |  |  |  |  |  |  |  |  |  |  |
ASCII |  |  |  |  |  |  |  |  |  |  |  |
ASCIISTR |  |  |  |  |  |  |  |  |  |  |  |
ASIN |  |  |  |  |  |  |  |  |  |  |  |
ATAN |  |  |  |  |  |  |  |  |  |  |  |
ATAN2 |  |  |  |  |  |  |  |  |  |  |  |
AVG |  |  |  |  |  |  |  |  |  |  |  |
BFILENAME |  |  |  |  |  |  |  |  |  |  |  |
BIN_TO_NUM |  |  |  |  |  |  |  |  |  |  |  |
BIT_COMPLEMENT |  |  |  |  |  |  |  |  |  |  |  |
BIT_OR |  |  |  |  |  |  |  |  |  |  |  |
BIT_XOR |  |  |  |  |  |  |  |  |  |  |  |
BITAND |  |  |  |  |  |  |  |  |  |  |  |
BOOL_TO_INT |  |  |  |  |  |  |  |  |  |  |  |
CARDINALITY |  |  |  |  |  |  |  |  |  |  |  |
CASE |  |  |  |  |  |  |  |  |  |  |  |
CAST |  |  |  |  |  |  |  |  |  |  |  |
CAST_FROM_BINARY _DOUBLE |  |  |  |  |  |  |  |  |  |  |  |
CAST_FROM_BINARY _FLOAT |  |  |  |  |  |  |  |  |  |  |  |
CAST_FROM_BINARY _INTEGER |  |  |  |  |  |  |  |  |  |  |  |
CAST_FROM_NUMBER |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_BINARY _DOUBLE |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_BINARY_FLOAT |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_BINARY _INTEGER |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_NUMBER |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_NVARCHAR2 |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_RAW |  |  |  |  |  |  |  |  |  |  |  |
CAST_TO_VARCHAR |  |  |  |  |  |  |  |  |  |  |  |
CEIL |  |  |  |  |  |  |  |  |  |  |  |
CHARTOROWID |  |  |  |  |  |  |  |  |  |  |  |
CHR |  |  |  |  |  |  |  |  |  |  |  |
CLUSTER_ID |  |  |  |  |  |  |  |  |  |  |  |
CLUSTER_PROBABILITY |  |  |  |  |  |  |  |  |  |  |  |
CLUSTER_SET |  |  |  |  |  |  |  |  |  |  |  |
COALESCE |  |  |  |  |  |  |  |  |  |  |  |
COLLECT |  |  |  |  |  |  |  |  |  |  |  |
COMPOSE |  |  |  |  |  |  |  |  |  |  |  |
CONCAT |  |  |  |  |  |  |  |  |  |  |  |
CONVERT |  |  |  |  |  |  |  |  |  |  |  |
CORR |  |  |  |  |  |  |  |  |  |  |  |
CORR_K |  |  |  |  |  |  |  |  |  |  |  |
CORR_S |  |  |  |  |  |  |  |  |  |  |  |
COS |  |  |  |  |  |  |  |  |  |  |  |
COSH |  |  |  |  |  |  |  |  |  |  |  |
COUNT |  |  |  |  |  |  |  |  |  |  |  |
COVAR_POP |  |  |  |  |  |  |  |  |  |  |  |
COVAR_SAMP |  |  |  |  |  |  |  |  |  |  |  |
CUME_DIST |  |  |  |  |  |  |  |  |  |  |  |
CURRENT_DATE |  |  |  |  |  |  |  |  |  |  |  |
CURRENT_TIMESTAMP |  |  |  |  |  |  |  |  |  |  |  |
CV |  |  |  |  |  |  |  |  |  |  |  |
DBTIMEZONE |  |  |  |  |  |  |  |  |  |  |  |
DENSE_RANK |  |  |  |  |  |  |  |  |  |  |  |
DECODE |  |  |  |  |  |  |  |  |  |  |  |
DECOMPOSE |  |  |  |  |  |  |  |  |  |  |  |
DELETEXML |  |  |  |  |  |  |  |  |  |  |  |
DEPTH |  |  |  |  |  |  |  |  |  |  |  |
DEREF |  |  |  |  |  |  |  |  |  |  |  |
DUMP |  |  |  |  |  |  |  |  |  |  |  |
EMPTY_BLOB (large object) |  |  |  |  |  |  |  |  |  |  |  |
EMPTY_CLOB (large object) |  |  |  |  |  |  |  |  |  |  |  |
ESTIMATE_CPU_UNITS |  |  |  |  |  |  |  |  |  |  |  |
EXISTSNODE |  |  |  |  |  |  |  |  |  |  |  |
EXP |  |  |  |  |  |  |  |  |  |  |  |
EXTRACT |  |  |  |  |  |  |  |  |  |  |  |
EXTRACTVALUE |  |  |  |  |  |  |  |  |  |  |  |
FEATURE_ID |  |  |  |  |  |  |  |  |  |  |  |
FEATURE_SET |  |  |  |  |  |  |  |  |  |  |  |
FEATURE_VALUE |  |  |  |  |  |  |  |  |  |  |  |
FIRST |  |  |  |  |  |  |  |  |  |  |  |
FIRST_VALUE |  |  |  |  |  |  |  |  |  |  |  |
FLOOR |  |  |  |  |  |  |  |  |  |  |  |
FROM_TZ |  |  |  |  |  |  |  |  |  |  |  |
GET_CLOCK_TIME |  |  |  |  |  |  |  |  |  |  |  |
GET_DDL |  |  |  |  |  |  |  |  |  |  |  |
GET_DEPENDENT_DDL |  |  |  |  |  |  |  |  |  |  |  |
GET_DEPENDENT_XML |  |  |  |  |  |  |  |  |  |  |  |
GET_GRANTED_DDL |  |  |  |  |  |  |  |  |  |  |  |
GET_GRANTED_XDL |  |  |  |  |  |  |  |  |  |  |  |
GET_HASH |  |  |  |  |  |  |  |  |  |  |  |
GET_REBUILD_COMMAND |  |  |  |  |  |  |  |  |  |  |  |
GET_SCN |  |  |  |  |  |  |  |  |  |  |  |
GET_XML |  |  |  |  |  |  |  |  |  |  |  |
GREATEST |  |  |  |  |  |  |  |  |  |  |  |
GROUP_ID |  |  |  |  |  |  |  |  |  |  |  |
GROUPING |  |  |  |  |  |  |  |  |  |  |  |
GROUPING_ID |  |  |  |  |  |  |  |  |  |  |  |
HEXTORAW |  |  |  |  |  |  |  |  |  |  |  |
INITCAP |  |  |  |  |  |  |  |  |  |  |  |
INSERTCHILDXML |  |  |  |  |  |  |  |  |  |  |  |
INSERTXMLBEFORE |  |  |  |  |  |  |  |  |  |  |  |
INSTR |  |  |  |  |  |  |  |  |  |  |  |
INSTRB |  |  |  |  |  |  |  |  |  |  |  |
INSTRC |  |  |  |  |  |  |  |  |  |  |  |
INSTR2 |  |  |  |  |  |  |  |  |  |  |  |
INSTR4 |  |  |  |  |  |  |  |  |  |  |  |
INT_TO_BOOL |  |  |  |  |  |  |  |  |  |  |  |
INTERVAL |  |  |  |  |  |  |  |  |  |  |  |
ITERATE |  |  |  |  |  |  |  |  |  |  |  |
ITERATE UNTIL |  |  |  |  |  |  |  |  |  |  |  |
ITERATION_NUMBER |  |  |  |  |  |  |  |  |  |  |  |
LAG |  |  |  |  |  |  |  |  |  |  |  |
LAST |  |  |  |  |  |  |  |  |  |  |  |
LAST_DAY |  |  |  |  |  |  |  |  |  |  |  |
LAST_VALUE |  |  |  |  |  |  |  |  |  |  |  |
LEAD |  |  |  |  |  |  |  |  |  |  |  |
LEAST |  |  |  |  |  |  |  |  |  |  |  |
LENGTH |  |  |  |  |  |  |  |  |  |  |  |
LENGTHB |  |  |  |  |  |  |  |  |  |  |  |
LENGTHC |  |  |  |  |  |  |  |  |  |  |  |
LENGTH2 |  |  |  |  |  |  |  |  |  |  |  |
LENGTH4 |  |  |  |  |  |  |  |  |  |  |  |
LN |  |  |  |  |  |  |  |  |  |  |  |
LNNVL |  |  |  |  |  |  |  |  |  |  |  |
LOCALTIMESTAMP |  |  |  |  |  |  |  |  |  |  |  |
LOG |  |  |  |  |  |  |  |  |  |  |  |
LOWER |  |  |  |  |  |  |  |  |  |  |  |
LPAD |  |  |  |  |  |  |  |  |  |  |  |
LTRIM |  |  |  |  |  |  |  |  |  |  |  |
MAKEREF |  |  |  |  |  |  |  |  |  |  |  |
MAX |  |  |  |  |  |  |  |  |  |  |  |
MEDIAN |  |  |  |  |  |  |  |  |  |  |  |
MIN |  |  |  |  |  |  |  |  |  |  |  |
MONTHS_BETWEEN |  |  |  |  |  |  |  |  |  |  |  |
MOD |  |  |  |  |  |  |  |  |  |  |  |
NANVL |  |  |  |  |  |  |  |  |  |  |  |
NEW_TIME |  |  |  |  |  |  |  |  |  |  |  |
NEXT_DAY |  |  |  |  |  |  |  |  |  |  |  |
NLS_CHARSET_DECL_LEN |  |  |  |  |  |  |  |  |  |  |  |
NLS_CHARSET_ID |  |  |  |  |  |  |  |  |  |  |  |
NLS_CHARSET_NAME |  |  |  |  |  |  |  |  |  |  |  |
NLS_INITCAP |  |  |  |  |  |  |  |  |  |  |  |
NLS_LOWER |  |  |  |  |  |  |  |  |  |  |  |
NLSSORT |  |  |  |  |  |  |  |  |  |  |  |
NLS_UPPER |  |  |  |  |  |  |  |  |  |  |  |
NTILE |  |  |  |  |  |  |  |  |  |  |  |
NULLIF |  |  |  |  |  |  |  |  |  |  |  |
NUMTODSINTERVAL |  |  |  |  |  |  |  |  |  |  |  |
NUMTOHEX |  |  |  |  |  |  |  |  |  |  |  |
NUMTOYMINTERVAL |  |  |  |  |  |  |  |  |  |  |  |
NVL |  |  |  |  |  |  |  |  |  |  |  |
NVL2 |  |  |  |  |  |  |  |  |  |  |  |
ORA_HASH |  |  |  |  |  |  |  |  |  |  |  |
PATH |  |  |  |  |  |  |  |  |  |  |  |
PERCENT_RANK |  |  |  |  |  |  |  |  |  |  |  |
PERCENTILE_CONT |  |  |  |  |  |  |  |  |  |  |  |
PERCENTILE_DISC |  |  |  |  |  |  |  |  |  |  |  |
POWER |  |  |  |  |  |  |  |  |  |  |  |
POWERMULTISET |  |  |  |  |  |  |  |  |  |  |  |
POWERMULTISET_BY_ CARDINALITY |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION_BOUNDS |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION_COST |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION_DETAILS |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION_PROBABILITY |  |  |  |  |  |  |  |  |  |  |  |
PREDICTION_SET |  |  |  |  |  |  |  |  |  |  |  |
PRESENTNNV |  |  |  |  |  |  |  |  |  |  |  |
PRESENTV |  |  |  |  |  |  |  |  |  |  |  |
PREVIOUS |  |  |  |  |  |  |  |  |  |  |  |
QUOTE DELIMITERS |  |  |  |  |  |  |  |  |  |  |  |
RANDOMBYTES |  |  |  |  |  |  |  |  |  |  |  |
RANDOMINTEGER |  |  |  |  |  |  |  |  |  |  |  |
RANDOMNUMBER |  |  |  |  |  |  |  |  |  |  |  |
RANK |  |  |  |  |  |  |  |  |  |  |  |
RATIO_TO_REPORT |  |  |  |  |  |  |  |  |  |  |  |
RAW_TO_CHAR |  |  |  |  |  |  |  |  |  |  |  |
RAW_TO_NCHAR |  |  |  |  |  |  |  |  |  |  |  |
RAW_TO_VARCHAR2 |  |  |  |  |  |  |  |  |  |  |  |
RAWTOHEX |  |  |  |  |  |  |  |  |  |  |  |
RAWTONHEX |  |  |  |  |  |  |  |  |  |  |  |
RAWTONUM |  |  |  |  |  |  |  |  |  |  |  |
REF |  |  |  |  |  |  |  |  |  |  |  |
REFTOHEX |  |  |  |  |  |  |  |  |  |  |  |
REGEXP_INSTR |  |  |  |  |  |  |  |  |  |  |  |
REGEXP_REPLACE |  |  |  |  |  |  |  |  |  |  |  |
REGEXP_SUBSTR |  |  |  |  |  |  |  |  |  |  |  |
REGR_AVGX |  |  |  |  |  |  |  |  |  |  |  |
REGR_AVGY |  |  |  |  |  |  |  |  |  |  |  |
REGR_COUNT |  |  |  |  |  |  |  |  |  |  |  |
REGR_INTERCEPT |  |  |  |  |  |  |  |  |  |  |  |
REGR_R2 |  |  |  |  |  |  |  |  |  |  |  |
REGR_SLOPE |  |  |  |  |  |  |  |  |  |  |  |
REGR_SXX |  |  |  |  |  |  |  |  |  |  |  |
REGR_SXY |  |  |  |  |  |  |  |  |  |  |  |
REGR_SYY |  |  |  |  |  |  |  |  |  |  |  |
REMAINDER |  |  |  |  |  |  |  |  |  |  |  |
REPLACE |  |  |  |  |  |  |  |  |  |  |  |
REVERSE |  |  |  |  |  |  |  |  |  |  |  |
ROUND |  |  |  |  |  |  |  |  |  |  |  |
ROW_NUMBER |  |  |  |  |  |  |  |  |  |  |  |
ROWIDTOCHAR |  |  |  |  |  |  |  |  |  |  |  |
ROWIDTONCHAR |  |  |  |  |  |  |  |  |  |  |  |
RPAD |  |  |  |  |  |  |  |  |  |  |  |
RTRIM |  |  |  |  |  |  |  |  |  |  |  |
SCNTOTIMESTAMP |  |  |  |  |  |  |  |  |  |  |  |
SESSIONTIMEZONE |  |  |  |  |  |  |  |  |  |  |  |
SET |  |  |  |  |  |  |  |  |  |  |  |
SIGN |  |  |  |  |  |  |  |  |  |  |  |
SIN |  |  |  |  |  |  |  |  |  |  |  |
SINH |  |  |  |  |  |  |  |  |  |  |  |
SOUNDEX |  |  |  |  |  |  |  |  |  |  |  |
SQRT |  |  |  |  |  |  |  |  |  |  |  |
SQLCODE (exception) |  |  |  |  |  |  |  |  |  |  |  |
SQLERRM (exception) |  |  |  |  |  |  |  |  |  |  |  |
STATS_BINOMIAL_TEST |  |  |  |  |  |  |  |  |  |  |  |
STATS_CROSSTAB |  |  |  |  |  |  |  |  |  |  |  |
STATS_F_TEST |  |  |  |  |  |  |  |  |  |  |  |
STATS_KS_TEST |  |  |  |  |  |  |  |  |  |  |  |
STATS_MODE |  |  |  |  |  |  |  |  |  |  |  |
STATS_MW_TEST |  |  |  |  |  |  |  |  |  |  |  |
STATS_ONE_WAY_ANOVA |  |  |  |  |  |  |  |  |  |  |  |
STATS_T_TEST |  |  |  |  |  |  |  |  |  |  |  |
STATS_WSR_TEST |  |  |  |  |  |  |  |  |  |  |  |
STDDEV |  |  |  |  |  |  |  |  |  |  |  |
STDDEV_POP |  |  |  |  |  |  |  |  |  |  |  |
STDDEV_SAMP |  |  |  |  |  |  |  |  |  |  |  |
STRING_TO_RAW |  |  |  |  |  |  |  |  |  |  |  |
SUBSTR |  |  |  |  |  |  |  |  |  |  |  |
SUBSTRB |  |  |  |  |  |  |  |  |  |  |  |
SUBSTRC |  |  |  |  |  |  |  |  |  |  |  |
SUBSTR2 |  |  |  |  |  |  |  |  |  |  |  |
SUBSTR4 |  |  |  |  |  |  |  |  |  |  |  |
SUM |  |  |  |  |  |  |  |  |  |  |  |
SYS_CONNECT_BY_PATH (hierarchical) |  |  |  |  |  |  |  |  |  |  |  |
SYS_CONTEXT (environment) |  |  |  |  |  |  |  |  |  |  |  |
SYS_DBURIGEN |  |  |  |  |  |  |  |  |  |  |  |
SYS_EXTRACT_UTC |  |  |  |  |  |  |  |  |  |  |  |
SYS_GUID (identifier) |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_DESCEND |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_DISTINCT |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_GUID |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_LBID |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_MAP_NONNULL |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_RAWTONUM |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_RPB |  |  |  |  |  |  |  |  |  |  |  |
SYS_OP_TOSETID |  |  |  |  |  |  |  |  |  |  |  |
SYS_TYPEID |  |  |  |  |  |  |  |  |  |  |  |
SYS_XMLAGG |  |  |  |  |  |  |  |  |  |  |  |
SYS_XMLGEN |  |  |  |  |  |  |  |  |  |  |  |
SYSDATE |  |  |  |  |  |  |  |  |  |  |  |
SYSTIMESTAMP |  |  |  |  |  |  |  |  |  |  |  |
TABLE |  |  |  |  |  |  |  |  |  |  |  |
TAN |  |  |  |  |  |  |  |  |  |  |  |
TANH |  |  |  |  |  |  |  |  |  |  |  |
TIMESTAMPTOSCN |  |  |  |  |  |  |  |  |  |  |  |
TO_BINARYDOUBLE |  |  |  |  |  |  |  |  |  |  |  |
TO_BINARYFLOAT |  |  |  |  |  |  |  |  |  |  |  |
TO_CHAR |  |  |  |  |  |  |  |  |  |  |  |
TO_CLOB |  |  |  |  |  |  |  |  |  |  |  |
TO_DATE |  |  |  |  |  |  |  |  |  |  |  |
TO_DSINTERVAL |  |  |  |  |  |  |  |  |  |  |  |
TO_LOB |  |  |  |  |  |  |  |  |  |  |  |
TO_MULTI_BYTE |  |  |  |  |  |  |  |  |  |  |  |
TO_NCHAR |  |  |  |  |  |  |  |  |  |  |  |
TO_NCLOB |  |  |  |  |  |  |  |  |  |  |  |
TO_NUMBER |  |  |  |  |  |  |  |  |  |  |  |
TO_SINGLE_BYTE |  |  |  |  |  |  |  |  |  |  |  |
TO_TIMESTAMP |  |  |  |  |  |  |  |  |  |  |  |
TO_TIMESTAMP_TZ |  |  |  |  |  |  |  |  |  |  |  |
TO_YMINTERVAL |  |  |  |  |  |  |  |  |  |  |  |
TRANSLATE |  |  |  |  |  |  |  |  |  |  |  |
TRANSLATE USING |  |  |  |  |  |  |  |  |  |  |  |
TRANSLITERATE |  |  |  |  |  |  |  |  |  |  |  |
TREAT |  |  |  |  |  |  |  |  |  |  |  |
TRIM |  |  |  |  |  |  |  |  |  |  |  |
TRUNC |  |  |  |  |  |  |  |  |  |  |  |
TZ_OFFSET |  |  |  |  |  |  |  |  |  |  |  |
UID (environment) |  |  |  |  |  |  |  |  |  |  |  |
UNISTR |  |  |  |  |  |  |  |  |  |  |  |
UPDATEXML |  |  |  |  |  |  |  |  |  |  |  |
UPPER |  |  |  |  |  |  |  |  |  |  |  |
USER (environment) |  |  |  |  |  |  |  |  |  |  |  |
USERENV (environment) |  |  |  |  |  |  |  |  |  |  |  |
VALUE (object) |  |  |  |  |  |  |  |  |  |  |  |
VAR_POP |  |  |  |  |  |  |  |  |  |  |  |
VAR_SAMP |  |  |  |  |  |  |  |  |  |  |  |
VARIANCE |  |  |  |  |  |  |  |  |  |  |  |
VERIFY_OWNER |  |  |  |  |  |  |  |  |  |  |  |
VERIFY_TABLE |  |  |  |  |  |  |  |  |  |  |  |
VERTICAL BARS |  |  |  |  |  |  |  |  |  |  |  |
VSIZE |  |  |  |  |  |  |  |  |  |  |  |
WIDTH_BUCKET |  |  |  |  |  |  |  |  |  |  |  |
XMLAGG |  |  |  |  |  |  |  |  |  |  |  |
XMLCAST |  |  |  |  |  |  |  |  |  |  |  |
XMLCDATA |  |  |  |  |  |  |  |  |  |  |  |
XMLCOLLATVAL |  |  |  |  |  |  |  |  |  |  |  |
XMLCOMMENT |  |  |  |  |  |  |  |  |  |  |  |
XMLCONCAT |  |  |  |  |  |  |  |  |  |  |  |
XMLDIFF |  |  |  |  |  |  |  |  |  |  |  |
XMLELEMENT |  |  |  |  |  |  |  |  |  |  |  |
XMLEXISTS |  |  |  |  |  |  |  |  |  |  |  |
XMLFOREST |  |  |  |  |  |  |  |  |  |  |  |
XMLISVALID |  |  |  |  |  |  |  |  |  |  |  |
XMLPARSE |  |  |  |  |  |  |  |  |  |  |  |
XMLPATCH |  |  |  |  |  |  |  |  |  |  |  |
XMLPI |  |  |  |  |  |  |  |  |  |  |  |
XMLQUERY |  |  |  |  |  |  |  |  |  |  |  |
XMLROOT |  |  |  |  |  |  |  |  |  |  |  |
XMLSEQUENCE |  |  |  |  |  |  |  |  |  |  |  |
XMLSERIALIZE |  |  |  |  |  |  |  |  |  |  |  |
XMLTABLE |  |  |  |  |  |  |  |  |  |  |  |
XMLTRANSFORM |  |  |  |  |  |  |  |  |  |  |  |


Oracle CAST Function Multicast

Oracle CAST Function
CAST With Collections

Using Multiset With A VARRAY 		CAST(MULTISET(<select statement>) AS <data_type>)
CREATE OR REPLACE TYPE cust_address_t
OID '53A970B3F5024BEC8EFD4F84CAD5E09E'
AS OBJECT (
street_address VARCHAR2(40),
postal_code    VARCHAR2(10),
city           VARCHAR2(30),
state_province VARCHAR2(2),
country_id     VARCHAR(2));
/

CREATE OR REPLACE TYPE address_book_t AS TABLE OF cust_address_t;
/

CREATE TABLE cust_address (
custno         NUMBER(10),
street_address VARCHAR2(40),
postal_code    VARCHAR2(10),
city           VARCHAR2(30),
state_province VARCHAR2(2),
country_id     VARCHAR2(2));

INSERT INTO cust_address
VALUES (1,'123 Main St.','98040','Mercer Island','WA','US');
INSERT INTO cust_address
VALUES (2,'1 Broadway','10202','New York','NY','US');
INSERT INTO cust_address
VALUES (3,'2462 Edgar Crest','V6L 2C4','Vancouver','BC','CN');
COMMIT;

CREATE TABLE cust_short (
custno NUMBER(10),
name   VARCHAR2(30));

INSERT INTO cust_short VALUES (1,'Morgan');
INSERT INTO cust_short VALUES (2,'Cline');
INSERT INTO cust_short VALUES (3,'Scott');

SELECT s.custno, s.name,
  CAST(MULTISET(SELECT ca.street_address,
    ca.postal_code,
    ca.city,
    ca.state_province,
    ca.country_id
  FROM cust_address ca
  WHERE s.custno = ca.custno) AS address_book_t)
FROM cust_short s;

Using Multiset With a PL/SQL Table 		CAST(MULTISET(<select statement>) AS <data_type>)
CREATE OR REPLACE TYPE project_table_t AS
TABLE OF VARCHAR2(25);
/

CREATE TABLE projects (
person_id    NUMBER(10),
project_name VARCHAR2(20));

CREATE TABLE pers_short (
person_id NUMBER(10),
last_name VARCHAR2(25));

INSERT INTO projects VALUES (1, 'Teach');
INSERT INTO projects VALUES (1, 'Code');
INSERT INTO projects VALUES (2, 'Code');
INSERT INTO pers_short VALUES (1, 'Morgan');
INSERT INTO pers_short VALUES (2, 'Cline');
INSERT INTO pers_short VALUES (3, 'Scott');
COMMIT;

SELECT * FROM projects;

SELECT * FROM pers_short;

SELECT e.last_name, CAST(MULTISET(
  SELECT p.project_name
  FROM projects p
  WHERE p.person_id = e.person_id
  ORDER BY p.project_name) AS project_table_t)
FROM pers_short e;

Using Multiset With A Multi-column Collection 		CAST(MULTISET(<select statement>) AS <data_type>)
CREATE OR REPLACE TYPE uob_type AS OBJECT (
object_name VARCHAR2(128), object_type VARCHAR2(18));
/

CREATE OR REPLACE TYPE t_uob_type AS TABLE OF uob_type;
/

set serveroutput on

DECLARE
 x t_uob_type;
BEGIN
  SELECT CAST(MULTISET(
    SELECT object_name, object_type
    FROM user_objects
    WHERE rownum <10) AS t_uob_type)
  INTO x
  FROM dual;

  FOR i IN 1 .. x.COUNT
  LOOP
    dbms_output.put_line(x(i).object_name || ' - '
    || x(i).object_type);
  END LOOP;
END;
/

Converting a Varray Type Column Into A Nested Table 		CAST(<column_or_value> AS <data_type>)
CREATE OR REPLACE TYPE district_t AS OBJECT (
region_no NUMBER(2),
title VARCHAR2(35),
cost NUMBER(7,2));
/

CREATE TYPE DistList_t AS TABLE OF district_t;
/

CREATE TYPE DistrictList AS VARRAY(10) OF district_t;
/

CREATE TABLE region_tab (
reg_id NUMBER(2),
reg_name VARCHAR2(15),
district DistrictList);

set describe depth all linenum on indent on

desc region_tab

SELECT * FROM region_tab;

INSERT INTO region_tab
VALUES(30, 'Northwest',
DistrictList (District_t(1, 'Alaska', 3250),
District_t(2, 'Washington', 12350),
District_t(3, 'Oregon', 2750),
District_t(4, 'Idaho', 1425)));

INSERT INTO region_tab
VALUES(40, 'Southwest',
DistrictList (District_t(1, 'Arizona', 3250),
District_t(2, 'California', 12350),
District_t(3, 'Nevada', 2750),
District_t(4, 'New Mexico', 1425)));

SELECT CAST(s.district AS DistList_t)
FROM region_tab s
WHERE s.reg_id = 30;
CAST With Dates
Date | CAST(<column_or_value> AS <data_type>)
SELECT CAST('01-JAN-2004' AS DATE) CDate
FROM dual;
Timestamp | CAST(<column_or_value> AS <data_type>)
SELECT CAST(SYSDATE AS TIMESTAMP WITH LOCAL TIME ZONE) DTWTZ
FROM dual;
CAST With Numbers
Number | CAST(<column_or_value> AS <data_type>)
SELECT 1 + CAST(3.14 * 0.152 AS NUMBER(10,7)) FLOATING
FROM dual;
CAST With Strings
Varchar2 | CAST(<column_or_value> AS <data_type>)
SELECT object_name
FROM user_objects;

SELECT CAST(object_name AS VARCHAR2(30)) OBJ_NAME
FROM user_objects;
Related Topics
Types
VArrays


Oracle NLS Character Set Functions
NLS_CHARSET_DECL_LEN
Returns the declaration length (in number of characters) of an NCHAR column | NLS_CHARSET_DECL_LEN(<byte_count>, 'character_set_id'>);
SELECT NLS_CHARSET_DECL_LEN(200, nls_charset_id('ja16eucfixed'))
FROM dual;
NLS_CHARSET_ID
Returns the character set ID number corresponding to character set name string | NLS_CHARSET_ID(<string>)
SELECT NLS_CHARSET_ID('ja16euc')
FROM dual;
NLS_CHARSET_NAME
Returns the name of the character set corresponding to ID number number | NLS_CHARSET_NAME(<number>);
SELECT NLS_CHARSET_NAME(2)
FROM dual;
Related Topics
Character Sets
UTL_GDK


Oracle NLS Character Sets Changing

Oracle NLS Character Sets
Demo

Changing Character Sets 		Note: Depending on the character sets involved this may result in data loss. Try this in test environments before proceeding in production.
conn / as sysdba

col parameter format a30
col value format a30

SELECT view_name
FROM dba_views
WHERE view_name LIKE '%NLS%';

SELECT *
FROM gv_$nls_parameters;

SHUTDOWN IMMEDIATE;
STARTUP RESTRICT;
ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
ALTER SYSTEM SET AQ_TM_PROCESSES=0;

ALTER DATABASE CHARACTER SET WE8MSWIN1252;

-- if the above fails:
ALTER DATABASE CHARACTER SET INTERNAL_USE WE8MSWIN1252;
SHUTDOWN IMMEDIATE;
STARTUP;

SELECT *
FROM gv_$nls_parameters;
Related Topics
Character Set Functions
UTL_GDK


Oracle Collection Functions
Note: The collection functions operate on nested tables and varrays
CARDINALITY
Returns the number of elements in a nested table | CARDINALITY(<nested_table>)
See Nested Table and Collections Demos
COLLECT
Takes a column of any type and creates a nested table of the input type out of the rows selected | COLLECT(<column>)
CREATE TYPE phone_book_t AS TABLE OF phone_list_typ;
/

SELECT CAST(COLLECT(phone_numbers) AS phone_book_t)
H FROM customers;
POWERMULTISET
Takes a nested table and returns a nested table of nested tables containing all nonempty subsets (called submultisets) of the input nested table | POWERMULTISET(<expression>)
CREATE TYPE cust_address_tab_tab_typ
AS TABLE OF cust_address_tab_typ;

SELECT CAST(POWERMULTISET(cust_address_ntab)
AS cust_address_tab_tab_typ)
FROM customers_demo;
POWERMULTISET_BY_CARDINALITY
Takes a nested table and a cardinality and returns a nested table of nested tables containing all nonempty subsets (called submultisets) of the nested table of the specified cardinality | POWERMULTISET_BY_CARDINALITY(<expression>, <cardinality>)
UPDATE customers_demo
SET cust_address_ntab = cust_address_ntab MULTISET UNION cust_address_ntab;

SELECT CAST(POWERMULTISET_BY_CARDINALITY(cust_address_ntab, 2)
AS cust_address_tab_tab_typ)
FROM customers_demo;
SET
Converts a nested table into a set by eliminating duplicates | SET(<nested_table>)
SELECT customer_id, SET(cust_address_ntab) address
FROM customers_demo;
Related Topics
Collections
Date Functions
Nested Tables
Numeric Functions
String Functions
Timestamp


Oracle Collections Table Expressions

Oracle Collections & TABLE Expression
General Information
A nested table is a table stored within the structure of another table.
Data Dictionary Objects
collection$ type$ dba_types all_types user_types
System Privileges
CREATE TYPE | CREATE TABLE
CREATE ANY TYPE | CREATE ANY TABLE
DROP ANY TYPE | DROP ANY TABLE

Create Types And Table 		You can perform DML operations on nested tables only if they are defined as columns of a table. Therefore, when the query_table_expression_clause of an INSERT, DELETE, or UPDATE statement is a table_collection_expression, the collection expression must be a subquery that uses the TABLE function to select the table's nested table column. The examples that follow are based on the following scenario:

Suppose the database contains a table hr_info with columns department_id, location, and manager_id, and a column of nested table type people which has last_name, department_id, and salary columns for all the employees of each respective manager:
CREATE OR REPLACE TYPE people_typ AS OBJECT (
last_name     VARCHAR2(25),
department_id NUMBER(4),
salary        NUMBER(8,2));
/

desc people_typ

SELECT text
FROM user_source
WHERE name = 'PEOPLE_TYP';

SELECT typecode, attributes, incomplete, final, instantiable
FROM user_types
WHERE type_name LIKE 'PEOPLE%TYP';

CREATE OR REPLACE TYPE people_tab_typ AS TABLE OF people_typ;
/

desc people_tab_typ

SELECT text
FROM user_source
WHERE name = 'PEOPLE_TAB_TYP';

 SELECT typecode, attributes, incomplete, final, instantiable
FROM user_types
WHERE type_name LIKE 'PEOPLE%TYP';

CREATE TABLE hr_info (
department_id NUMBER(4),
location_id   NUMBER(4),
manager_id    NUMBER(6),
people        people_tab_typ)
NESTED TABLE people STORE AS people_stor_tab;

desc hr_info

set describe depth all linenum on indent on

desc hr_info

col data_type format a30

SELECT column_name, data_type
FROM user_tab_cols
WHERE table_name = 'HR_INFO';
DML with Collections

Insert 		INSERT INTO hr_info
(department_id, location_id, manager_id, people)
VALUES
(280, 1800, 999, people_tab_typ());

INSERT INTO hr_info
(department_id, location_id, manager_id, people)
VALUES
(205, 2000, 881, people_tab_typ());

SELECT * FROM hr_info;

-- The following example inserts into the people nested
-- table column of hr_info table's department numbered 280:

INSERT INTO TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 280)
VALUES ('Smith', 280, 1750);

INSERT INTO TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 205)
VALUES ('Smith', 999, 1750);

COMMIT;

SELECT * FROM hr_info;

-- another insert into the people table nested in hr_info
INSERT INTO TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 280)
VALUES ('Jones', 280, 919);

SELECT * FROM hr_info;

SELECT cardinality(people)
FROM hr_info;

Update All Nested Rows 		UPDATE TABLE(
SELECT <alias.column_name>
FROM <able_name alias>
WHERE <alias.column_name> = <value)
VALUES (<value, value, value>);
-- Updates department 280's people nested table:

UPDATE TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 280) p
SET p.salary = p.salary + 100;

SELECT * FROM hr_info;

Update Selected Nested Row 		Updates only Smith's record
UPDATE TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 280) p
SET p.salary = p.salary - 500
WHERE p.last_name = 'Smith';

SELECT * FROM hr_info;

Select (Collection Unnesting) 		To select data from a nested table column, you use the TABLE function to treat the nested table as the columns of a table. This process is called collection unnesting.

You could get all the rows from hr_info, which was created in the preceding example, and all the rows from the people nested table column of hr_info using the following statement.
SELECT t1.department_id, t2.*
FROM hr_info t1, TABLE(t1.people) t2
WHERE t2.department_id = t1.department_id;
Now suppose that people is not a nested table column of hr_info, but is instead a separate table with columns last_name, department_id, address, hiredate, and salary. You can extract the same rows as in the preceding example with this statement.
CREATE TABLE t (
department_id NUMBER(4),
last_name     VARCHAR2(25),
salary        NUMBER(8,2));

INSERT INTO t
SELECT t1.department_id, t2.last_name, t2.salary
FROM hr_info t1, TABLE(t1.people) t2
WHERE t2.department_id = t1.department_id;

SELECT *
FROM t;

Delete 		Delete from Department 280's people nested table
DELETE TABLE(
  SELECT h.people
  FROM hr_info h
  WHERE h.department_id = 280) p
WHERE p.salary > 1200;
Comparing Collections

Comparing Collections 		Collections cannot be directly compared for equality or inequality. For instance, the following IF condition is not allowed:

set serveroutput on

DECLARE
 TYPE clientele IS TABLE OF VARCHAR2(64);
 group1 clientele := clientele('Customer 1', 'Customer 2');
 group2 clientele := clientele('Customer 1', 'Customer 3');
BEGIN
  -- Equality test causes compilation error
  IF group1 = group2 THEN
    dbms_output.put_line('Equal');
  ELSE
    dbms_output.put_line('Not Equal');
  END IF;
END;
/

 This restriction also applies to implicit comparisons. For example, collections cannot appear in a DISTINCT,
GROUP BY, or ORDER BY list. Individual elements, however can be compared. For example:

DECLARE
 TYPE Clientele IS TABLE OF VARCHAR2(64);
 group1 Clientele := Clientele('Customer 1', 'Customer 2');
 group2 Clientele := Clientele('Customer 1', 'Customer 3');
BEGIN
  -- Equality test causes compilation error
  IF group1(1) = group2(1) THEN
    dbms_output.put_line('Equal');
  ELSE
    dbms_output.put_line('Not Equal');
  END IF;
END;
/

and

DECLARE
 TYPE Clientele IS TABLE OF VARCHAR2(64);
 group1 Clientele := Clientele('Customer 1', 'Customer 2');
 group2 Clientele := Clientele('Customer 1', 'Customer 3');
BEGIN
  -- Equality test causes compilation error
  IF group1(2) = group2(2) THEN
    dbms_output.put_line('Equal');
  ELSE
    dbms_output.put_line('Not Equal');
  END IF;
END;
/

so ...

DECLARE
 TYPE Clientele IS TABLE OF VARCHAR2(64);
 group1 Clientele := Clientele('Customer 1', 'Customer 2');
 group2 Clientele := Clientele('Customer 1', 'Customer 3');
BEGIN
  -- Equality test causes compilation error
  FOR i IN 1..2
  LOOP
    IF group1(i) = group2(i) THEN
      dbms_output.put_line('Equal');
    ELSE
      dbms_output.put_line(group1(i) ||
      ' Is Not The Same As ' || group2(i));
    END IF;
  END LOOP;
END;
/
Related Topics
Collection Functions
Nested Tables
REF Cursors
Types
VArrays


Oracle Connect By

Oracle Connect By Function
Syntax 1 | CONNECT BY [NOCYCLE] <condition> START WITH <condition>
Syntax 2 | START WITH <condition> CONNECT BY [NOCYCLE] <condition>
CONNECT BY PRIOR
A condition that identifies the relationship between parent rows and child rows of the hierarchy | CONNECT BY <child_value> = <parent_value>
conn hr/hr

SELECT employee_id, last_name, manager_id
FROM employees
CONNECT BY PRIOR employee_id = manager_id;
START WITH
Specifies a condition that identifies the row(s) to be used as the root(s) of a hierarchical query | START WITH (column_name) = <value>
conn hr/hr

SELECT last_name, employee_id, manager_id, LEVEL
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id;

SELECT last_name, employee_id, manager_id, LEVEL
FROM employees
START WITH employee_id = 101
CONNECT BY PRIOR employee_id = manager_id;

set pagesize 0
col last_name format a30

SELECT LEVEL, LPAD(' ', LEVEL*3) || LAST_NAME AS LAST_NAME
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id;

set pagesize 20
ORDER SIBLINGS BY
SIBLINGS BY preserves any ordering specified in the hierarchical query clause and then applies the order_by_clause to the siblings of the hierarchy | ORDER SIBLINGS BY (column_name)
conn hr/hr

SELECT last_name, employee_id, manager_id, LEVEL
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY last_name;
CONNECT_BY_ROOT
CONNECT_BY_ROOT is a unary operator that is valid only in hierarchical queries. When you qualify a column with this operator, Oracle returns the column value using data from the root row.

Cannot be specified with the START WITH or CONNECT BY condition. 		The following example returns the last name of each employee in department 110, each manager above that employee in the hierarchy, the number of levels between manager and employee, and the path between the two:
conn hr/hr

set linesize 121
col emp format a20
col mgr format a20

SELECT "Name", SUM(salary) "Total_Salary"
FROM (
  SELECT CONNECT_BY_ROOT last_name "Name", salary
  FROM employees
  WHERE department_id = 110
  CONNECT BY PRIOR employee_id = manager_id)
GROUP BY "Name";

-- Thanks Colin for the correction
CONNECT_BY_ISCYCLE Pseudocolumn
The CONNECT_BY_ISCYCLE pseudocolumn returns 1 if the current row has a child which is also its ancestor. Otherwise it returns 0
conn hr/hr

UPDATE employees SET manager_id = 145
WHERE employee_id = 100;

set linesize 121
col path format a50

SELECT last_name, LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
WHERE LEVEL <= 3 AND department_id = 80
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id AND LEVEL <= 4;
ERROR:
ORA-01436: CONNECT BY loop in user data

SELECT last_name, CONNECT_BY_ISCYCLE "Cycle", LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
WHERE LEVEL <= 3 AND department_id = 80
START WITH last_name = 'King'
CONNECT BY NOCYCLE PRIOR employee_id = manager_id
AND LEVEL <= 4;

ROLLBACK;
CONNECT_BY_ISLEAF Pseudocolumn
The CONNECT_BY_ISLEAF pseudocolumn returns 1 if the current row is a leaf of the tree defined by the CONNECT BY condition. Otherwise it returns 0. This information indicates whether a given row can be further expanded to show more of the hierarchy.
conn hr/hr

SELECT last_name "Employee", CONNECT_BY_ISLEAF "IsLeaf",
LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') "Path"
FROM employees
WHERE level <= 3
AND department_id = 80
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id
AND LEVEL <= 4;
LEVEL Pseudocolumn
For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root row, 2 for a child of a root, and so on
conn hr/hr

SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
CONNECT BY PRIOR employee_id = manager_id;

SELECT LPAD(' ',2*(LEVEL-1)) || last_name ORG_CHART,
employee_id, manager_id, job_id
FROM employees
START WITH job_id = 'AD_VP'
CONNECT BY PRIOR employee_id = manager_id;
SYS_CONNECT_BY_PATH
Returns the path of a column value from root to node, with column values separated by char for each row returned by CONNECT BY condition
SYS_CONNECT_BY_PATH(<column>, <char>)
conn scott/tiger

col empname format a20
col cbp format a30

SELECT LPAD(' ', 2*LEVEL, ' ' ) || ename empName, dname, job,
sys_connect_by_path( ename, '/' ) cbp
FROM emp e, dept d
WHERE e.deptno = d.deptno
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
ORDER SIBLINGS BY job;

SELECT LPAD(' ', 2*LEVEL, ' ' ) || ename empName, dname, job,
sys_connect_by_path(empno, '.') cbp
FROM scott.emp emp, scott.dept dept
WHERE emp.deptno = dept.deptno
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
ORDER SIBLINGS BY ename;
Function Demo

Use A Function To Receive The Current Node and Search for Parents of the Current Node
CREATE OR REPLACE FUNCTION permissions_sub_tree_root (
the_id IN NUMBER,
the_level IN NUMBER)
RETURN NUMBER IS

sub_tree_root NUMBER(10);

BEGIN
  SELECT id
  INTO sub_tree_root
  FROM hierarchy
  WHERE level = the_level
  -- Connect 'upwards', i.e. find the parent
  CONNECT BY PRIOR PARENT = id
  START WITH ID = the_id;

  RETURN sub_tree_root;
END permissions_sub_tree_root;
/

SELECT id, name, username
FROM (
  SELECT ID, PARENT, NAME,
  permissions_sub_tree_root(id, LEVEL) ROOT
  FROM hierarchy
  CONNECT BY PRIOR id = PARENT) HIERARCHY, permissions
WHERE ROOT = hierarchy_id;
GROUP BY Demo
Group By Demo with CONNECT_BY_ROOT and
CONNECT_BY_PRIOR
conn hr/hr

SELECT name, SUM(salary) "Total_Salary"
FROM (
  SELECT CONNECT_BY_ROOT last_name name, salary
  FROM employees
  WHERE department_id = 110
  CONNECT BY PRIOR employee_id = manager_id)
GROUP BY name;
Demos
Indenting conn hr/hr

col lname format a30

SELECT LPAD(' ', level*2, ' ') || last_name LNAME, d.department_id
FROM employees e, departments d
WHERE e.department_id = d.department_id
START WITH employee_id = 100
CONNECT BY PRIOR e.employee_id = e.manager_id;
Hierarchical Query with IN | In a [NOT] IN condition in a WHERE clause, if the right-hand side of the condition is a subquery, you cannot use LEVEL on the left-hand side of the condition. However, you can specify LEVEL in a subquery of the FROM clause to achieve the same result. For example, the following statement is not valid:
SELECT employee_id, last_name FROM employees
WHERE (employee_id, LEVEL)
IN (SELECT employee_id, 2 FROM employees)
START WITH employee_id = 2
CONNECT BY PRIOR employee_id = manager_id;
But the following statement is valid because it encapsulates the query containing the LEVEL information in the FROM clause:
SELECT v.employee_id, v.last_name, v.lev
FROM (
  SELECT employee_id, last_name, LEVEL lev
  FROM employees v
  START WITH employee_id = 100
  CONNECT BY PRIOR employee_id = manager_id) v
WHERE (v.employee_id, v.lev) IN (
  SELECT employee_id, 2 FROM employees);
Related Topics
Select


Oracle Constraints Primary Key Foreign Unique Check Referential Integrity

Oracle Constraints
General Constraint Information
Data Dictionary Objects Related To Constraints
con$ | ind$ | icol$
ccol$ |  |
DBA | ALL | USER
dba_cons_columns | all_cons_columns | user_cons_columns
dba_constraints | all_constraints | user_constraints
dba_indexes | all_indexes | user_indexes
dba_ind_partitions | all_ind_partitions | user_ind_partitions
dba_ind_subpartitions | all_ind_subpartitions | user_ind_subpartitions
Privileges Related To Constraints | To create a foreign key constraint on an object in a different schema you must have the REFERENCES privilege on the columns of the referenced key in the parent table or view.
Constraint Types & Codes
Type Code | Type Description | Acts On Level
C | Check on a table | Column
O | Read Only on a view | Object
P | Primary Key | Object
R | Referential AKA Foreign Key | Column
U | Unique Key | Column
V | Check Option on a view | Object
Alter Constraint | Constraints can not be altered. They must be dropped and recreated. Some modifications are allowed via ALTER TABLE.
Definitions
DISABLE | Allows incoming data, regardless of whether it conforms to the constraint
ENABLE | Ensures that all incoming data conforms to the constraint
FREELISTS | Specifies the number of lists of available index blocks. Oracle ignores this if the tablespace in which the object resides is in automatic segment-space management (ASSM) mode.
INITRANS | Specify the initial number of concurrent transaction entries allocated within each data block allocated to the database object. This value can range from 1 to 255 and defaults to 2 for indexes.
NORELY | Do not enforce the enabled constraint
NOVALIDATE | Validates changes but does not validate data previously existing in the table
PCTFREE | Control the amount of free space in the index data block for updating. In a Primary Key constraint's index it would be rare that this not be set to zero (0).
RELY | Enforce the enabled constraint
Surrogate Key Exposed locators such as IDENTITY are not surrogate keys. A surrogate is totally hidden from users and maintained by the system -- think of how an index works. If you change a natural key, the DRI actions will
cascade it for you. Hell does not break loose. But if your autonumber and real key are out of synch, then you are screwed. Just enter the same record several times to get different autonumbers on duplicate
rows. Drop all but one of the dups and then try to find all of the referenced rows in other tables.

If you maintain the exposed locator by hand, you have extra work, extra disk seeks and will eventually make a mistake, thus destroying your data integrity. How would you validate and verify your data?

The UPC code just went from 10 to 13 digits. It does not matter if you used an autonumber or the UPC, the UPC has to be updated. If you had used a proper RDBMS design and SQL-92, you would do an ALTER DOMAIN and a single update with CASCADE. This is one of the MANY reasons that rows are not records. This is a problem in SQL Server because it is still based on a contiguous storage model, but other products are not, so wind up using tools to write scripts.

~ Joe Celko in comp.databases.ms-sqlserver 10/13/2005
TABLESPACE | The tablespace where any associated index will be built
VALIDATE | Validate previously existing data as well as all changes
Tables For Constraint Demo

Table DDL 		CREATE TABLE person (
person_id  NUMBER(10),
last_name  VARCHAR2(30) NOT NULL,
per_age    NUMBER(3),
per_state  VARCHAR2(2),
per_zip    VARCHAR2(5),
ssn        VARCHAR2(11),
status     VARCHAR2(1));

CREATE TABLE uclass (
class_id   NUMBER(7),
class_name VARCHAR2(35),
reg_fee    NUMBER(6,2),
reg_date   DATE);

CREATE TABLE person_uclass_ie (
person_id NUMBER(10),
class_id  NUMBER(7));

CREATE TABLE state_zip (
state    VARCHAR2(2),
zip_code VARCHAR2(5));

INSERT INTO state_zip VALUES ('WA', '98004');
INSERT INTO state_zip VALUES ('WA', '98101');
INSERT INTO state_zip VALUES ('OR', '97405');
INSERT INTO state_zip VALUES ('CA', '94002');
INSERT INTO state_zip VALUES ('NY', '10010');
COMMIT;
Primary Key - Type P

Create Single Column Primary Key 		ALTER TABLE <table_name>
ADD CONSTRAINT <primary_key_constraint_name>
PRIMARY KEY (<column_name>)
USING INDEX
PCTFREE <percentage of block available for update>
INITRANS <integer>
MAXTRANS <integer>
STORAGE (FREELISTS <integer>)
TABLESPACE <tablespace_name>;
desc person

SELECT constraint_name, constraint_type
FROM user_constraints
WHERE table_name = 'PERSON';

ALTER TABLE person
ADD CONSTRAINT pk_person
PRIMARY KEY (person_id)
USING INDEX
PCTFREE 0
TABLESPACE uwdata;

desc person

set linesize 121

SELECT constraint_name, constraint_type, index_name, generated, status, deferrable
FROM user_constraints
WHERE table_name = 'PERSON';

-- note a unique index is created
SELECT index_type, uniqueness, clustering_factor
FROM user_indexes
WHERE table_name = 'PERSON';

exec dbms_stats.gather_index_stats(USER, 'PK_PERSON');

SELECT index_type, uniqueness, clustering_factor
FROM user_indexes
WHERE table_name = 'PERSON';

col column_name format a30

SELECT constraint_name, position, column_name
FROM user_cons_columns
WHERE table_name = 'PERSON';

SELECT index_name, column_position, column_name, descend
FROM user_ind_columns
WHERE table_name = 'PERSON';

INSERT INTO person
(person_id, last_name)
VALUES
(1, 'Morgan');

INSERT INTO person
(person_id, last_name)
VALUES
(2, 'Cline');

INSERT INTO person
(person_id, last_name)
VALUES
(1, 'Lofstrom');

SELECT *
FROM person;

Create Composite Primary Key 		ALTER TABLE <table_name>
ADD CONSTRAINT <primary_key_constraint_name>
PRIMARY KEY <column_name, column_name, ....>
USING INDEX
PCTFREE <percentage of block available for update>
TABLESPACE <tablespace_name>;
desc person_uclass_ie

SELECT COUNT(*)
FROM user_constraints
WHERE table_name = 'PERSON_UCLASS_IE';

ALTER TABLE person_uclass_ie
ADD CONSTRAINT pk_person_uclass_ie
PRIMARY KEY (person_id, class_id)
USING INDEX
PCTFREE 0;

desc person_uclass_ie

SELECT constraint_name, constraint_type, index_name, generated, status, deferrable
FROM user_constraints
WHERE table_name = 'PERSON_UCLASS_IE';

-- note a unique index is created
SELECT index_type, uniqueness, clustering_factor
FROM user_indexes
WHERE table_name = 'PERSON_UCLASS_IE';

exec dbms_stats.gather_index_stats(USER, 'PK_PERSON_UCLASS_IE');

SELECT index_type, uniqueness, clustering_factor
FROM user_indexes
WHERE table_name = 'PERSON_UCLASS_IE';

col column_name format a30

SELECT constraint_name, position, column_name
FROM user_cons_columns
WHERE table_name = 'PERSON_UCLASS_IE'
ORDER BY 2;

SELECT index_name, column_position, column_name, descend
FROM user_ind_columns
WHERE table_name = 'PERSON_UCLASS_IE'
ORDER BY 2;

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(1, 1);

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(2, 1);

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(3, NULL);

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(1, 1);

SELECT *
FROM person_uclass_ie;

Create Deferrable Primary Key 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
PRIMARY KEY (<column_name_list>)
DEFERRABLE INITIALLY < IMMEDIATE | DEFERRED >
USING INDEX
PCTFREE <integer>
TABLESPACE <tablespace_name>;
desc uclass

SELECT COUNT(*)
FROM user_constraints
WHERE table_name = 'UCLASS';

ALTER TABLE uclass
ADD CONSTRAINT pk_uclass
PRIMARY KEY (class_id)
INITIALLY DEFERRED DEFERRABLE
USING INDEX
PCTFREE 0;

desc uclass
-- note NOT NULL not created on class_id

SELECT constraint_name, constraint_type, index_name, generated, status, deferrable
FROM user_constraints
WHERE table_name = 'UCLASS';

-- note a non-unique index is created
SELECT index_type, uniqueness, clustering_factor
FROM user_indexes
WHERE table_name = 'UCLASS';

col column_name format a30

SELECT constraint_name, position, column_name
FROM user_cons_columns
WHERE table_name = 'UCLASS';

SELECT index_name, column_position, column_name, descend
FROM user_ind_columns
WHERE table_name = 'UCLASS';

INSERT INTO uclass
(class_id)
VALUES
(1);

INSERT INTO uclass
(class_id)
VALUES
(2);

INSERT INTO uclass
(class_id)
VALUES
(1);

SELECT *
FROM uclass;

COMMIT;

SELECT *
FROM uclass;

Disabling and Enabling Primary Key Constraints 		ALTER TABLE <table_name> DISABLE PRIMARY KEY;
CREATE TABLE t (
rid NUMBER(5));

ALTER TABLE t
ADD CONSTRAINT pk_t
PRIMARY KEY (rid)
USING INDEX
PCTFREE 0;

SELECT index_name, index_type, uniqueness, pct_free
FROM user_indexes
WHERE table_name = 'T';

ALTER TABLE t DISABLE PRIMARY KEY;

SELECT index_name, index_type, uniqueness
FROM user_indexes
WHERE table_name = 'T';

ALTER TABLE t ENABLE PRIMARY KEY;

SELECT index_name, index_type, uniqueness, pct_free
FROM user_indexes
WHERE table_name = 'T';

Disable Validate to make a table read only 		ALTER TABLE <table_name> MODIFY CONSTRAINT <constraint_name>
DISABLE VALIDATE
SELECT constraint_name, status, validated
FROM user_constraints;

ALTER TABLE uclass MODIFY CONSTRAINT pk_uclass
DISABLE VALIDATE;

SELECT constraint_name, status, validated
FROM user_constraints
WHERE constraint_type = 'P';

INSERT INTO uclass (class_id) VALUES (201);

COMMIT;

Enable Primary Key without validation of pre-existing data 		ALTER TABLE <table_name> ENABLE NOVALIDATE PRIMARY KEY;
ALTER TABLE uclass ENABLE NOVALIDATE PRIMARY KEY;

SELECT constraint_name, status, validated
FROM user_constraints
WHERE constraint_type = 'P';

INSERT INTO uclass (class_id) VALUES (101);

COMMIT;

ALTER TABLE uclass DROP PRIMARY KEY;

INSERT INTO uclass (class_id) VALUES (101);
INSERT INTO uclass (class_id) VALUES (101);
INSERT INTO uclass (class_id) VALUES (101);
COMMIT;

SELECT *
FROM uclass;

ALTER TABLE uclass
ADD CONSTRAINT pk_uclass
PRIMARY KEY (class_id)
INITIALLY IMMEDIATE DEFERRABLE
NOVALIDATE;

SELECT constraint_name, status, validated
FROM user_constraints
WHERE constraint_type = 'P';

INSERT INTO uclass (class_id) VALUES (1);
COMMIT;

INSERT INTO uclass (class_id) VALUES (101);
COMMIT;

DELETE FROM uclass
WHERE class_id = 101
AND rownum < 4;

COMMIT;
Unique - Type U

Create unique constraint on a single column 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
UNIQUE (<column_name>)
USING INDEX
PCTFREE <pct of block available for update>
TABLESPACE <tablespace_name>
ALTER TABLE state_zip
ADD CONSTRAINT uc_state_zip_state
UNIQUE (state);

DELETE state_zip
WHERE ROWID IN (
  SELECT LEAD(ROWID)
  OVER (PARTITION BY state ORDER BY NULL)
FROM state_zip);

ALTER TABLE state_zip
ADD CONSTRAINT uc_state_zip_state
UNIQUE (state);

SELECT constraint_name, constraint_type
FROM user_constraints
WHERE table_name = 'STATE_ZIP';

col column_name format a30

SELECT constraint_name, column_name, position
FROM user_cons_columns
ORDER BY constraint_name, position;

SELECT * FROM state_zip;

INSERT INTO state_zip
(state, zip_code)
VALUES
('WA', '98004');

Create unique constraint with USING INDEX clause 		ALTER TABLE <table_name>
ADD CONSTRAINT <primary_key_constraint_name>
UNIQUE <column_name, column_name, ....>
USING INDEX
PCTFREE <pct of block available for update>
TABLESPACE <tablespace_name>;
ALTER TABLE state_zip
DROP CONSTRAINT uc_state_zip_state;

ALTER TABLE state_zip
ADD CONSTRAINT uc_state_zip_state
UNIQUE (state)
USING INDEX
PCTFREE 0
TABLESPACE uwdata;

SELECT constraint_name, constraint_type
FROM user_constraints
WHERE table_name = 'STATE_ZIP';

SELECT index_name
FROM user_indexes
WHERE table_name = 'STATE_ZIP';
Referential - Type R (Foreign Key)

Create Foreign Key an a single column 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
FOREIGN KEY (<column_name>)
REFERENCING <table_name> (<column_name>)
DEFERRABLE INITIALLY < IMMEDIATE | DEFERRED >;
ALTER TABLE person_uclass_ie
ADD CONSTRAINT fk_person_uclass_person_id
FOREIGN KEY (person_id)
REFERENCING person (person_id)
INITIALLY DEFERRED DEFERRABLE;

ALTER TABLE person
ADD CONSTRAINT pk_person
PRIMARY KEY (person_id)
INITIALLY DEFERRED DEFERRABLE
USING INDEX
PCTFREE 0;

ALTER TABLE person_uclass_ie
ADD CONSTRAINT fk_person_uclass_person_id
FOREIGN KEY (person_id)
REFERENCING person (person_id)
INITIALLY DEFERRED DEFERRABLE;

SELECT constraint_name, constraint_type, status
FROM user_constraints
WHERE table_name = 'PERSON_UCLASS_IE';

SELECT t.owner CHILD_OWNER,
t.table_name CHILD_TABLE,
t.constraint_name FOREIGN_KEY_NAME,
r.owner PARENT_OWNER,
r.table_name PARENT_TABLE,
r.constraint_name PARENT_CONSTRAINT
FROM user_constraints t, user_constraints r
WHERE t.r_constraint_name = r.constraint_name
AND t.r_owner = r.owner
AND t.constraint_type='R'
AND t.table_name = 'PERSON_UCLASS_IE';

-- check for index on FK
set linesize 121
col status format a6
col columns format a30 word_wrapped
col table_name format a30 word_wrapped

SELECT DECODE(b.table_name, NULL, '****', 'Ok' ) STATUS, a.table_name, a.columns, b.columns from (
  SELECT SUBSTR(a.table_name,1,30) table_name,
  SUBSTR(a.constraint_name,1,30) constraint_name, MAX(DECODE(position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(position, 2,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 3,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 4,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 5,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 6,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 7,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 8,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 9,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,10,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,11,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,12,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,13,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,14,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,15,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,16,', '|| SUBSTR(column_name,1,30),NULL)) columns from user_cons_columns a, user_constraints b
WHERE a.constraint_name = b.constraint_name
AND constraint_type = 'R'
GROUP BY SUBSTR(a.table_name,1,30), SUBSTR(a.constraint_name,1,30) ) a, (
  SELECT SUBSTR(table_name,1,30) table_name,
  SUBSTR(index_name,1,30) index_name, MAX(DECODE(column_position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(column_position, 2,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 3,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 4,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 5,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 6,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 7,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 8,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 9,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,10,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,11,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,12,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,13,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,14,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,15,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,16,', '||SUBSTR(column_name,1,30),NULL)) columns from user_ind_columns group by SUBSTR(table_name,1,30), SUBSTR(index_name,1,30) ) b where a.table_name = b.table_name (+) and b.columns (+) like a.columns || '%';

-- FK should be indexed to prevent deadlocks
CREATE INDEX ix_puie_person_id
ON person_uclass_ie (person_id);

-- Verify FK problem addressed
SELECT DECODE(b.table_name, NULL, '****', 'Ok' ) STATUS, a.table_name, a.columns, b.columns from (
  SELECT SUBSTR(a.table_name,1,30) table_name,
  SUBSTR(a.constraint_name,1,30) constraint_name, MAX(DECODE(position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(position, 2,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 3,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 4,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 5,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 6,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 7,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 8,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 9,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,10,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,11,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,12,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,13,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,14,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,15,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,16,', '|| SUBSTR(column_name,1,30),NULL)) columns from user_cons_columns a, user_constraints b
WHERE a.constraint_name = b.constraint_name
AND constraint_type = 'R'
GROUP BY SUBSTR(a.table_name,1,30), SUBSTR(a.constraint_name,1,30) ) a, (
  SELECT SUBSTR(table_name,1,30) table_name,
  SUBSTR(index_name,1,30) index_name, MAX(DECODE(column_position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(column_position, 2,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 3,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 4,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 5,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 6,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 7,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 8,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 9,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,10,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,11,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,12,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,13,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,14,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,15,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,16,', '||SUBSTR(column_name,1,30),NULL)) columns from user_ind_columns group by SUBSTR(table_name,1,30), SUBSTR(index_name,1,30) ) b where a.table_name = b.table_name (+) and b.columns (+) like a.columns || '%';

SELECT * FROM person;

SELECT * FROM person_uclass_ie;

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(2, 202);
COMMIT;

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(3, 202);
COMMIT;

SELECT * FROM person_uclass_ie;

INSERT INTO person
(person_id, last_name)
VALUES
(3, 'Havemeyer');

INSERT INTO person_uclass_ie
(person_id, class_id)
VALUES
(3, 202);
COMMIT;

SELECT * FROM person;

SELECT * FROM person_uclass_ie;

Create Composite Foreign Key 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
FOREIGN KEY (<column_name, column_name, ....>)
REFERENCING <table_name> (<column_name,column_name,....>);
ALTER TABLE state_zip
ADD CONSTRAINT pk_state_zip
PRIMARY KEY (state, zip_code)
USING INDEX
PCTFREE 0;

ALTER TABLE person
ADD CONSTRAINT fk_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code);

col column_name format a30

SELECT constraint_name, column_name, position
FROM user_cons_columns
WHERE table_name = 'PERSON'
ORDER BY 1,3;

UPDATE person
SET per_state = 'WA', per_zip = '98004'
WHERE person_id = 1;

UPDATE person
SET per_state = 'WA', per_zip = '98005'
WHERE person_id = 2;

Create deferrable foreign key 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
FOREIGN KEY (<column_name, column_name, ....>)
REFERENCING <table_name> (<column_name,column_name,....>)
INITIALLY DEFERRED DEFERRABLE;
ALTER TABLE person
DROP CONSTRAINT fk_person_state_zip;

ALTER TABLE person
ADD CONSTRAINT fk_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code)
INITIALLY DEFERRED DEFERRABLE;

UPDATE person
SET per_state = 'WA', per_zip = '98004'
WHERE person_id = 1;

UPDATE person
SET per_state = 'WA', per_zip = '98005'
WHERE person_id = 2;

COMMIT;

SET CONSTRAINTS 		SET CONSTRAINTS <IMMEDIATE | DEFERRED>;
SELECT constraint_name, constraint_type, deferrable, deferred
FROM user_constraints
WHERE table_name = 'PERSON';

SET CONSTRAINTS ALL IMMEDIATE;

SELECT constraint_name, constraint_type, deferrable, deferred
FROM user_constraints
WHERE table_name = 'PERSON';

SELECT * FROM person;

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'WA', '98005');

SET CONSTRAINTS ALL DEFERRED;

SELECT constraint_name, constraint_type, deferrable, deferred
FROM user_constraints
WHERE table_name = 'PERSON';

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'WA', '98005');

COMMIT;

Disable constraint 		ALTER TABLE <table_name>
DISABLE CONSTRAINT <constraint_name>;
ALTER TABLE person
DISABLE CONSTRAINT fk_person_state_zip;

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'WA', '98005');

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'OR', '98005');

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'XX', 'ABCDE');

COMMIT;

-- fix the data if the constraint does not re-enable and repeat enable

Enable constraint with EXCEPTIONS INTO clause 		ALTER TABLE <table_name>
ENABLE CONSTRAINT <constraint_name>;
ALTER TABLE person
DISABLE CONSTRAINT pk_person;

SELECT constraint_name, status
FROM user_constraints
WHERE table_name = 'PERSON';

@?\rdbms\admin\utlexcpt.sql

desc exceptions

ALTER TABLE person
ENABLE PRIMARY KEY
EXCEPTIONS INTO exceptions;

SELECT * FROM exceptions;

ALTER TABLE person
ENABLE CONSTRAINT fk_person_state_zip
EXCEPTIONS INTO exceptions;

SELECT * FROM exceptions;

On Delete Cascade 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
FOREIGN KEY (<column_name>)
REFERENCES <table_name> (<column_name>)
ON DELETE CASCADE;
INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(1, 'Morgan', 54, 'WA', '98004');

INSERT INTO person
(person_id, last_name, per_age, per_state, per_zip)
VALUES
(2, 'Cline', 57, 'NY', '10010');
COMMIT;

ALTER TABLE person
ADD CONSTRAINT fkocd_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code)
ON DELETE CASCADE;

SELECT constraint_name, delete_rule
FROM user_constraints;

SELECT * FROM person;

SELECT * FROM state_zip;

DELETE FROM state_zip
WHERE zip_code = '10010';

On Delete Set NULL 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
FOREIGN KEY (<column_name>)
REFERENCES <table_name> (<column_name>)
ON DELETE SET NULL;
ALTER TABLE person
DROP CONSTRAINT fkocd_person_state_zip;

ALTER TABLE person
ADD CONSTRAINT fkdsn_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code)
ON DELETE SET NULL;

SELECT constraint_name, delete_rule
FROM user_constraints;

SELECT * FROM person;

SELECT * FROM state_zip;

DELETE FROM state_zip
WHERE zip_code = '98004';

SELECT * FROM state_zip;

SELECT * FROM person;
Check - Type C

Create Check Constraint with EQUALS 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name> = <condition>);
col search_condition format a40

SELECT table_name, constraint_name, search_condition
FROM user_constraints
WHERE constraint_type = 'C';

desc person

ALTER TABLE person
ADD CONSTRAINT cc_person_status
CHECK (status = 'X');

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET status = 'X'
WHERE person_id = 1;

UPDATE person
SET status = NULL
WHERE person_id = 2;

UPDATE person
SET status = 'Z'
WHERE person_id = 3;

ALTER TABLE person
DROP CONSTRAINT cc_person_status;

Create Check Constraint With NOT EQUALS 		ALTER TABLE
ADD CONSTRAINT <constraint_name>
CHECK (<column_name> != <value>);
ALTER TABLE person
ADD CONSTRAINT cc_person_status
CHECK (status != 'X');

UPDATE person
SET status = NULL;

ALTER TABLE person
ADD CONSTRAINT cc_person_status
CHECK (status != 'X');

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET status = 'A'
WHERE person_id = 1;

UPDATE person
SET status = '4'
WHERE person_id = 2;

UPDATE person
SET status = 'X'
WHERE person_id = 3;

Create Check Constraint with LIKE 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name> LIKE <condition>);
ALTER TABLE person
ADD CONSTRAINT cc_person_ssn
CHECK (ssn LIKE '___-__-____');

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET ssn = '333-22-4444'
WHERE person_id = 1;

UPDATE person
SET ssn = '123-45-6789'
WHERE person_id = 2;

UPDATE person
SET ssn = 'Oops'
WHERE person_id = 3;

ALTER TABLE uclass
ADD CONSTRAINT cc_uclass_class_name
CHECK (class_name LIKE 'Ora%');

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'UCLASS';

INSERT INTO uclass VALUES (101, 'Oracle');
INSERT INTO uclass VALUES (201, 'Orxcle');

Create Check Constraint with NOT LIKE 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name> NOT LIKE <condition>);
ALTER TABLE uclass
ADD CONSTRAINT cc_uclass_class_name
CHECK (class_name NOT LIKE '%O%');

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'UCLASS';

INSERT INTO uclass VALUES (101, 'Basic Oracle');
INSERT INTO uclass VALUES (201, 'Oracle SQL');
INSERT INTO uclass VALUES (301, 'oracle SQL');

Create Check Constraint with IN 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name>
IN (<comma delimited list of values>);
ALTER TABLE person DROP CONSTRAINT cc_person_status;

UPDATE person
SET status = NULL;

ALTER TABLE person
ADD CONSTRAINT cc_person_status
CHECK (status IN ('N', 'Y'));

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET status = 'Y'
WHERE person_id = 1;

UPDATE person
SET status = 'N'
WHERE person_id = 1;

UPDATE person
SET status = 'y'
WHERE person_id = 1;

Create Check Constraint with NOT IN 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name>
NOT IN (<comma delimited list of values>);
ALTER TABLE person DROP CONSTRAINT cc_person_status;

UPDATE person
SET status = NULL;

ALTER TABLE person
ADD CONSTRAINT cc_person_status
CHECK (status NOT IN ('A','B','C','D'));

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET status = 'A'
WHERE person_id = 1;

UPDATE person
SET status = 'D'
WHERE person_id = 1;

UPDATE person
SET status = 'E'
WHERE person_id = 1;

Create Check Constraint with BETWEEN 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name> BETWEEN <lower_value>
AND <higher_value>);
ALTER TABLE person
ADD CONSTRAINT cc_person_age
CHECK (per_age BETWEEN 18 AND 60);

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET per_age = 57
WHERE person_id = 1;

UPDATE person
SET per_age = 59
WHERE person_id = 2;

UPDATE person
SET per_age = 17
WHERE person_id = 3;

Create Check Constraint with NOT BETWEEN 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name>
NOT BETWEEN <lower_value> AND <higher_value>);
ALTER TABLE person
ADD CONSTRAINT cc_person_age
CHECK (per_age NOT BETWEEN 18 AND 60);

SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'PERSON';

UPDATE person
SET per_age = 54
WHERE person_id = 1;

UPDATE person
SET per_age = 17
WHERE person_id = 3;

Create Check Constraint with Boolean Operator 		ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>
CHECK (<column_name>) > (<condition>);
ALTER TABLE person
ADD CONSTRAINT cc_person_age
CHECK (per_age > 30);

UPDATE person
SET per_age = 57
WHERE person_id = 1;

UPDATE person
SET per_age = 27
WHERE person_id = 3;

Functions Can Be Used In A Check Constraint But Not To Make Assignments 		ALTER TABLE uclass
ADD CONSTRAINT cc_uclass_reg_fee
CHECK (reg_fee =  ROUND(reg_fee,0));

INSERT INTO uclass
(class_id, class_name, reg_fee)
VALUES
(401, 'Check Constraints', 23.0);

INSERT INTO uclass
(class_id, class_name, reg_fee)
VALUES
(401, 'Check Constraints', 23.1);

-- SYSDATE, SYSTIMESTAMP, and USER can not be used in a check constraint
ALTER TABLE uclass
ADD CONSTRAINT cc_uclass_reg_date
CHECK (reg_date > SYSDATE);
Deferrable Constraints
Note: The following correspondence is with Julian Dyke in the UK and valuable enough I thought I should share it here in the library.
From: Daniel A. Morgan [mailto:damorgan@u.washington.edu]
Sent: 05 November 2007 01:41
To: info@juliandyke.com
Subject: Deferrable Constraints

I've stumbled trying to answer a student question and wonder if you might know the answer. A thorough search of the docs has proven that either the answer is not documented or I am not good at entering search criteria.

I create a deferrable referential constraint such as this:

ALTER TABLE person
ADD CONSTRAINT fk_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code)
INITIALLY DEFERRED DEFERRABLE;

Look in the data dictionary

SELECT constraint_name, deferrable, deferred
FROM user_constraints
WHERE table_name = 'PERSON';

and I see this:

CONSTRAINT_NAME                DEFERRABLE     DEFERRED
------------------------------ -------------- ---------
FK_PERSON_STATE_ZIP            DEFERRABLE     DEFERRED

all is well.

Then I do this:

SET CONSTRAINTS ALL IMMEDIATE;

and if I again query the data dictionary I still see this:

CONSTRAINT_NAME                DEFERRABLE     DEFERRED
------------------------------ -------------- ---------
FK_PERSON_STATE_ZIP            DEFERRABLE     DEFERRED

which is technically correct because my SET CONSTRAINTS only affects my session and not others. But the question is where in Oracle is it
storing the fact that within my specific session I have altered the behaviour of that constraint?

Thanks.
Here is Julian's initial reply
The answer is that SET CONSTRAINTS ALL IMMEDIATE is implemented as a transaction callback which is a type of state object.

When you initially create a transaction you allocate a ktxcb structure from a segmented array. You can see these structures in X$KTCXB and once the transaction has started in V$TRANSACTION. If you do a state object dump (SYSTEMSTATE level 10), you can see the transactions currently in progress for each session (and process).

When you issue SET CONSTRAINTS ALL IMMEDIATE, a transaction callback state object is created. This is chained from the transaction object

Both transaction (ktcxb) and transaction callback (ktccts?) are segmented arrays with names "transaction" and "txncallback" respectively. The amount of memory allocated to these structures can be seen in V$SGASTAT (again with names "transaction" and "txncallback" respectively).

I can't find any X$ tables which externalise the transaction callback structure. However, it is easy to find in the system state dump.

Following is an extract from a level 10 SYSTEMSTATE dump which following the execution of SET CONSTRAINTS ALL IMMEDIATE in a transaction:

 SO: 0x3dace118, type: 49, owner: 0x3daa4198, flag: -/-/-/0x00 if:
0x1 c: 0x1
proc=0x3f256af0, name=txncallback, file=ktccts.h LINE:336, pg=0
(cmtcbk)
type: constraint commit callback act: 1
Dump of memory from 0x3C434118 to 0x3C4341A8
3C434110 00000301 00000357 [....W...]
3C434120 3DAA4198 3F256AF0 3DAA41C8 3DACE128 [.A.=.j%?.A.=(..=]
3C434130 00000000 00000000 00000000 00000000 [................]
3C434140 00000000 00000000 3C434148 3C434148 [........HAC<HAC<]
3C434150 200010B4 00001024 00000000 37D204FC [... $..........7]
3C434160 37D20504 00000000 00000000 02010200 [...7............]
3C434170 00000000 00001014 6E617274 74636173 [........transact]
3C434180 206E6F69 20006F63 7FFF7FFF 7FFF7FFF [ion co. ........]
3C434190 00000200 00000000 3C434198 3C434198 [.........AC<.AC<]
3C4341A0 37D20514 00000000 [...7....]

I don't know what happens if with SET CONSTRAINTS ALL DEFERRED yet.

Any use?

Julian
More later if we figure it out.
Defer One Constraint | SET CONSTRAINT <constraint_name> DEFERRED;
SET CONSTRAINT fk_person_state_zip DEFERRED;
Defer All Constraints | SET CONSTRAINTS ALL DEFERRED;
Stop Constraint Deferment | SET CONSTRAINT <constraint_name> IMMEDIATE;
SET CONSTRAINT fk_person_state_zip IMMEDIATE;
Stop All Constraint Deferment | SET CONSTRAINTS ALL IMMEDIATE;
Note: A non-deferrable constraint is generally policed by a unique index (a unique index is created unless a suitable index already exists). A deferrable constraint must be policed by a non-unique index (as it's possible for a point of time during a transaction for duplicate values to exist). This is why it is not possible to alter a constraint from non-deferrable to deferrable. Doing so would require Oracle to drop and recreate the index.

A PK enforces uniqueness procedurally without relying on a unique index. The main advantage of a non-unique index is the constraint can be disabled and re-enabled without the index being dropped and recreated.
ALTER CONSTRAINT
Alter Constraint syntax does not exist.
DROP CONSTRAINT

Generic Constraint Drop. Will drop any constraint by name 		ALTER TABLE <table_name>
DROP CONSTRAINT <primary_key_constraint_name>;
SELECT constraint_name, table_name
FROM user_constraints;

ALTER TABLE person DROP CONSTRAINT pk_person;

SELECT constraint_name, table_name
FROM user_constraints;

Specific Primary Key Drop 		ALTER TABLE <table_name> DROP PRIMARY KEY
ALTER TABLE uclass DROP PRIMARY KEY;

SELECT constraint_name, table_name
FROM user_constraints
WHERE constraint_type = 'P';

Index Drop After PK Drop Demo 		conn / as sysdba

GRANT select ON ind$ TO uwclass;

conn uwclass/uwclass

CREATE TABLE t (
idcol NUMBER(5),
chcol VARCHAR2(5));

ALTER TABLE t
ADD CONSTRAINT pk_t
PRIMARY KEY(idcol)
USING INDEX
PCTFREE 0;

SELECT constraint_name, table_name, index_name
FROM user_constraints
WHERE constraint_type = 'P';

col object_name format a30

SELECT object_id, object_name
FROM user_objects
WHERE object_type = 'INDEX';

SELECT property
FROM sys.ind$
WHERE obj# = 63069;
-- property = 4097

ALTER TABLE t DROP PRIMARY KEY;

SELECT table_name, index_name
FROM user_indexes
ORDER BY 1;

CREATE UNIQUE INDEX ix_t
ON t(idcol);

ALTER TABLE t
ADD CONSTRAINT pk_t
PRIMARY KEY(idcol)
USING INDEX;

SELECT constraint_name, table_name, index_name
FROM user_constraints
WHERE constraint_type = 'P';

SELECT object_id, object_name
FROM user_objects
WHERE object_type = 'INDEX';

SELECT property
FROM sys.ind$
WHERE obj# = 63070;
-- property = 1

ALTER TABLE t DROP PRIMARY KEY;

SELECT table_name, index_name
FROM user_indexes
ORDER BY 1;

Specific unique constraint drop 		ALTER TABLE DROP UNIQUE (<column_name>);
ALTER TABLE state_zip
ADD CONSTRAINT uc_state_zip_state
UNIQUE (state)
USING INDEX
PCTFREE 0;

ALTER TABLE state_zip DROP UNIQUE (state);

Drop unique constraint with dependencies 		ALTER TABLE <table_name>
DROP CONSTRAINT <constraint_name>
CASCADE;
ALTER TABLE state_zip
ADD CONSTRAINT uc_state_zip_state
UNIQUE (state, zip_code)
USING INDEX
PCTFREE 0;

ALTER TABLE person
ADD CONSTRAINT fk_person_state_zip
FOREIGN KEY (per_state, per_zip)
REFERENCES state_zip (state, zip_code);

ALTER TABLE state_zip DROP CONSTRAINT uc_state_zip_state;

ALTER TABLE state_zip DROP CONSTRAINT uc_state_zip_state CASCADE;
Drop foreign key ALTER TABLE <table_name>
DROP CONSTRAINT <constraint_name>;
ALTER TABLE person
DROP CONSTRAINT fk_person_state_zip;

Drop Primary Key with a Foreign Key dependency 		ALTER TABLE <table_name>
DROP CONSTRAINT <primary_key_constraint_name>
CASCADE CONSTRAINTS;
ALTER TABLE state_zip DROP PRIMARY KEY;

ALTER TABLE state_zip DROP PRIMARY KEY CASCADE;

SELECT table_name, constraint_name, constraint_type
FROM user_constraints;

Table Drop with Foreign Key Constraint 		DROP TABLE <table_name> CASCADE CONSTRAINTS [PURGE];
SELECT table_name, constraint_name, r_constraint_name
FROM user_constraints
WHERE constraint_type = 'R';

SELECT table_name
FROM user_constraints
WHERE constraint_name = 'PK_STATE_ZIP';

DROP TABLE state_zip;

DROP TABLE state_zip CASCADE CONSTRAINTS;

SELECT object_name, original_name, type
FROM recyclebin;

FLASHBACK TABLE state_zip TO BEFORE DROP;

SELECT constraint_name, constraint_type
FROM user_constraints
WHERE table_name = 'STATE_ZIP';
Rename Constraint

Rename Constraint 		ALTER TABLE <table_name>
RENAME CONSTRAINT <current_constraint_name>
TO <new_constraint_name>;
SELECT constraint_name
FROM user_constraints;

ALTER TABLE state_zip
RENAME CONSTRAINT "BIN$HY86N3B2RQi/1ODAiR9CTw==$0"
TO pk_state_zip;

SELECT constraint_name
FROM user_constraints;
Constraint Related Queries
List a child table's referential constraints and their associated parent table. SELECT t.owner CHILD_OWNER,
t.table_name CHILD_TABLE,
t.constraint_name FOREIGN_KEY_NAME,
r.owner PARENT_OWNER,
r.table_name PARENT_TABLE,
r.constraint_name PARENT_CONSTRAINT
FROM user_constraints t, user_constraints r
WHERE t.r_constraint_name = r.constraint_name
AND t.r_owner = r.owner
AND t.constraint_type='R'
AND t.table_name = <child_table_name>;

List foreign keys and referenced table and columns 		SELECT DECODE(c.status,'ENABLED','C','c') t,
SUBSTR(c.constraint_name,1,31) relation,
SUBSTR(cc.column_name,1,24) columnname,
SUBSTR(p.table_name,1,20) tablename
FROM all_cons_columns cc, all_constraints p,
     all_constraints c
WHERE c.owner = upper('UWCLASS')
AND c.table_name = upper('PERSON')
AND c.constraint_type = 'R'
AND p.owner = c.r_owner
AND p.constraint_name = c.r_constraint_name
AND cc.owner = c.owner
AND cc.constraint_name = c.constraint_name
AND cc.table_name = c.table_name
UNION ALL
SELECT DECODE(c.status,'ENABLED','P','p') t,
SUBSTR(c.constraint_name,1,31) relation,
SUBSTR(cc.column_name,1,24) columnname,
SUBSTR(c.table_name,1,20) tablename
FROM all_cons_columns cc, all_constraints p,
     all_constraints c
WHERE p.owner = upper('UWCLASS')
AND p.table_name = upper('PERSON')
AND p.constraint_type in ('P','U')
AND c.r_owner = p.owner
AND c.r_constraint_name = p.constraint_name
AND c.constraint_type = 'R'
AND cc.owner = c.owner
AND cc.constraint_name = c.constraint_name
AND cc.table_name = c.table_name
ORDER BY 1, 4, 2, 3
/

Procedure to DISABLE all constraints 		CREATE OR REPLACE PROCEDURE disable_fk_constraint IS

CURSOR fke_cur IS
SELECT table_name, constraint_name
FROM user_constraints
WHERE constraint_type = 'R'
AND status = 'ENABLED';

ExStr VARCHAR2(4000);

BEGIN
  FOR fke_rec IN fke_cur LOOP
    ExStr := 'ALTER TABLE ' || fke_rec.table_name ||
             'DISABLE CONSTRAINT ' ||
              fke_rec.constraint_name;
    BEGIN
      EXECUTE IMMEDIATE ExStr;
    EXCEPTION
      WHEN OTHERS THEN
        NULL;
    END;
  END LOOP;
END disable_fk_constraint;
/

Find Unindexed Foreign Keys

This script was found at OraQA and attributed to Tom Kyte of Oracle though the link to his site was not working. 		set linesize 121
col status format a6
col columns format a30 word_wrapped
col table_name format a30 word_wrapped

SELECT DECODE(b.table_name, NULL, '****', 'Ok' ) STATUS, a.table_name, a.columns, b.columns from (
  SELECT SUBSTR(a.table_name,1,30) table_name,
  SUBSTR(a.constraint_name,1,30) constraint_name, MAX(DECODE(position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(position, 2,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 3,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 4,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 5,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 6,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 7,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 8,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position, 9,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,10,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,11,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,12,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,13,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,14,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,15,', '|| SUBSTR(column_name,1,30),NULL)) || max(DECODE(position,16,', '|| SUBSTR(column_name,1,30),NULL)) columns from user_cons_columns a, user_constraints b
WHERE a.constraint_name = b.constraint_name
AND constraint_type = 'R'
GROUP BY SUBSTR(a.table_name,1,30), SUBSTR(a.constraint_name,1,30) ) a, (
  SELECT SUBSTR(table_name,1,30) table_name,
  SUBSTR(index_name,1,30) index_name, MAX(DECODE(column_position, 1,
  SUBSTR(column_name,1,30),NULL)) || MAX(DECODE(column_position, 2,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 3,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 4,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 5,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 6,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 7,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 8,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position, 9,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,10,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,11,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,12,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,13,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,14,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,15,', '||SUBSTR(column_name,1,30),NULL)) || max(DECODE(column_position,16,', '||SUBSTR(column_name,1,30),NULL)) columns from user_ind_columns group by SUBSTR(table_name,1,30), SUBSTR(index_name,1,30) ) b where a.table_name = b.table_name (+) and b.columns (+) like a.columns || '%';
Related Topics
DBMS_ERRLOG
Nested Table Constraints
Type O Constraints
Read Only on a view
Type V Constraints
Check option on a view


Oracle Contexts
General
Related Data Dictionary Objects ALL_CONTEXT
GLOBAL_CONTEXT
SESSION_CONTEXT
Related Topics
Advanced Queueing (DBMS_AQ)
Advanced Queueing (DBMS_AQADM)
DBMS_APPLICATION_INFO
DBMS_RLS
DBMS_SESSION
DBMS_WM
Fine Grained Access Control
SYS_CONTEXT
System Privileges
Virtual Private Database


Oracle Convert Conversion Functions

Oracle Conversion Functions
Note: Functions for converting to date, numeric, string, and timestamp data types can be found through the related links.
ASCIISTR
Converts An ASCII String To An ASCII String In The Database's Character Set ASCIISTR(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT ASCIISTR(CHR(128) || 'Hello' || CHR(255))
FROM dual;
BFILENAME
Returns a BFILE from a combination of a directory and a file name BFILENAME(directory IN VARCHAR2, filename IN VARCHAR2)
RETURN BFILE;
DECLARE
 src_file BFILE;
BEGIN
  src_file := bfilename('CTEMP', 'myfile.txt');
END;
/
BIN_TO_NUM
Converts a bit vector to a number | BIN_TO_NUM(<value>,<value>,....)
SELECT BIN_TO_NUM(1, 0, 1, 0) FROM dual;
CAST
Converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value | CAST(<string_or_column> AS <DATATYPE>)
SELECT CAST(15402 AS VARCHAR2(30))
FROM dual;
CHARTOROWID
Converts a value from CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to ROWID datatype | CHARTOROWID(<char>);
conn hr/hr

SELECT rowid
FROM employees;

SELECT last_name
FROM employees
WHERE ROWID = CHARTOROWID('AAAQvRAAFAAAABYAAp');
COMPOSE
Convert a string in any data type to a Unicode string COMPOSE(<string_or_column>)

Unistring Value | Resulting character
unistr('\0300') | grave accent (`)
unistr('\0301') | acute accent (�)
unistr('\0302') | circumflex (ˆ)
unistr('\0303') | tilde (~)
unistr('\0308') | umlaut (�)
SELECT 'ol' || COMPOSE('e' || UNISTR('\0301')) FROM dual;
CONVERT
Converts a character string from one character set to another | CONVERT(<char>, <dest_char_set>, <source_char_set>)
SELECT CONVERT('� � � � � A B C D E','US7ASCII','WE8ISO8859P1')
FROM dual;
DECOMPOSE
Converts a unicode string to a string | DECOMPOSE(<unicode_string>)
SELECT DECOMPOSE('ol' || COMPOSE('e' || UNISTR('\0301')))
FROM dual;
HEXTORAW
Converts char containing hexadecimal digits in the CHAR, VARCHAR2, NCHAR, or NVARCHAR2 character set to a raw value | HEXTORAW(<hex_value>)
CREATE TABLE test (
raw_col RAW(10));

desc test

INSERT INTO test VALUES (HEXTORAW('7D'));

SELECT * FROM test;
NUMTODSINTERVAL
Converts a number to an INTERVAL DAY TO SECOND literal | NUMTODSINTERVAL(n, <interval_unit>)
SELECT NUMTODSINTERVAL(120, 'DAY') FROM dual;

SELECT NUMTODSINTERVAL(1200, 'HOUR') FROM dual;

SELECT NUMTODSINTERVAL(12000, 'MINUTE') FROM dual;

SELECT NUMTODSINTERVAL(120000, 'SECOND') FROM dual;
NUMTOYMINTERVAL
Converts n to an INTERVAL YEAR TO MONTH literal | NUMTOYMINTERVAL(n, <interval_unit>)
conn hr/hr

SELECT last_name, hire_date, salary, SUM(salary)
OVER (ORDER BY hire_date
RANGE NUMTOYMINTERVAL(1, 'YEAR') PRECEDING) AS t_sal
FROM employees;
RAWTOHEX
Converts raw to a character value containing its hexadecimal equivalent | RAWTOHEX(<raw_value>)
CREATE TABLE test (
raw_col RAW(10));

desc test

INSERT INTO test VALUES (HEXTORAW('7D'));

SELECT * FROM test;
SELECT RAWTOHEX(raw_col) HEXVAL
FROM test;
RAWTONHEX
Converts raw to an NVARCHAR2 character value containing its hexadecimal equivalent | RAWTONHEX(<raw_value>);
col dumpcol format a30

SELECT RAWTONHEX(raw_col) HEXVAL, dump(raw_col) dumpcol
FROM test;
REFTOHEX
Converts argument expr to a character value containing its hexadecimal equivalent. expr must return a REF. | REFTOHEX(<expression>);
conn oe/oe

CREATE TABLE warehouse_table OF warehouse_typ
(PRIMARY KEY (warehouse_id));

CREATE TABLE location_table (
location_number NUMBER,
building        REF warehouse_typ SCOPE IS warehouse_table);

INSERT INTO warehouse_table VALUES (1, 'Downtown', 99);

INSERT INTO location_table SELECT 10, REF(w)
FROM warehouse_table w;

SELECT REFTOHEX(building) FROM location_table;

DROP TABLE warehouse_table PURGE;
ROWIDTOCHAR
Converts a rowid value to VARCHAR2 datatype | ROWIDTOCHAR(rowid);
SELECT COUNT(*)
FROM servers;

SELECT rowid
FROM servers
WHERE rownum < 11;

SELECT ROWID
FROM servers
WHERE ROWIDTOCHAR(ROWID) LIKE '%AAB%';
ROWIDTONCHAR
Converts a rowid value to NVARCHAR2 datatype | ROWIDTOCHAR(rowid)
See ROWIDTOCHAR demo above
SCN_TO_TIMESTAMP
Returns the approximate Timestamp for an SCN | SCN_TO_TIMESTAMP(<scn>);
SELECT current_scn
FROM gv$database;

SELECT SCN_TO_TIMESTAMP(8215026-250000)
FROM dual;
TIMESTAMP_TO_SCN
Returns the approximate SCN for a timestamp | TIMESTAMP_TO_SCN(<timestamp>)
SELECT TIMESTAMP_TO_SCN(SYSTIMESTAMP)
FROM dual;
TO_BINARY_DOUBLE
Converts a Value to the BINARY_DOUBLE Data Type | TO_BINARY_DOUBLE(<value>);
See TO_NUMBER demo, below.
TO_BINARY_FLOAT
Converts a Value to the BINARY_FLOAT Data Type | TO_BINARY_FLOAT(<value>) RETURN BINARY_FLOAT
See TO_NUMBER demo, below.
TO_CHAR
Convert Datatype To String | TO_CHAR(<string_or_column>, <format>) RETURN VARCHAR2
SELECT TO_CHAR(SYSDATE, 'MM/DD/YYYY HH:MI:SS') FROM dual;
Converts DATE and TIMESTAMP to VARCHAR2 with the specified format | TO_DATE(<date_string>, <format mask>, <NLS_PARAMETER>)
SELECT TO_CHAR(datecol1, 'DAY-MONTH-YY') COL1,
       TO_CHAR(datecol2, 'D-MM/YYYY HH24:MI:SS') COL2,
       TO_CHAR(datecol2, 'YYYY-MON-DD HH24') COL3
FROM t;
Demo of FM Formatting From Tom Kyte (Oracle Magazine 3-4/2004) SELECT TO_CHAR(dt, 'HH:MI AM') A,
       TO_CHAR(dt, 'FMHH:MI AM') B,
       TO_CHAR(dt, 'FMHHFM:MI AM') C
FROM (SELECT TO_DATE('09:01 am', 'HH:MI AM') dt FROM dual);
Convert NUMBER to CHARACTER | TO_CHAR(number)
SELECT TO_CHAR(123)
FROM dual;
Convert NUMBER to HEX | TO_CHAR(NUMBER) RETURN HEX
SELECT TO_CHAR(1048576,'XXXXXXXX')
FROM dual;
TO_CLOB
Converts CHAR, NCHAR, VARCHAR2, NVARCHAR2, or NCLOB values to CLOB values | TO_CLOB(<char_or_lob_column_or_value>) RETURN CLOB
SELECT TO_CLOB('Some value')
FROM dual;
TO_DATE
Convert A String With Default Format To A Date | TO_DATE(<string>) RETURN DATE
SELECT TO_DATE('01-JAN-2004') FROM dual;
Convert A String With A Non-Default Format To A Date | TO_DATE(<string>, <format mask>)
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM dual;
Convert A String With A Non-Default Format And Specify The Language | TO_DATE(<string>, <format mask>) RETURN DATE
SELECT TO_DATE('January 12, 2005, 11:03 A.M.', 'MONTH DD, YYYY, HH:MI A.M.', 'NLS_DATE_LANGUAGE = American')
FROM dual;
Convert A String With A Non-Default Format And Specify The Language | TO_DATE(<date_string>, <format mask>, <NLS_PARAMETER>) RETURN DATE
ALTER SESSION SET NLS_TERRITORY = 'JAPAN';

SELECT TO_DATE('January 12, 2005, 11:03 A.M.', 'Month dd, YYYY, HH:MI A.M.', 'NLS_DATE_LANGUAGE = American')
FROM DUAL;

ALTER SESSION SET NLS_TERRITORY = 'AMERICA';
Convert A String To 24 Hour Time | TO_DATE(<date_string>, <format mask>) RETURN DATE
SELECT TO_CHAR(SYSDATE, 'MM/DD/YY HH24:MI:SS') FROM dual;
TO_DSINTERVAL
Converts A String To An INTERVAL DAY TO SECOND DataType | TO_DSINTERVAL(<date_string>, <format mask>, <NLS_PARAMETER>)
conn hr/hr

SELECT employee_id, last_name
FROM employees
WHERE hire_date + TO_DSINTERVAL('100 10:00:00') <= DATE '1990-01-01';
TO_LOB
Converts LONG or LONG RAW values in the column long_column to LOB values | TO_LOB(long_column) RETURN LOB
desc user_triggers

CREATE TABLE lobtest (
testcol CLOB);

INSERT INTO lobtest
SELECT TO_LOB(trigger_body)
FROM user_triggers;
TO_MULTI_BYTE
Returns char with all of its single-byte characters converted to their corresponding multibyte characters | TO_MULTI_BYTE(character_string)
-- must be run in a UTF8 database to see the difference
SELECT dump('A') FROM dual;

SELECT dump(TO_MULTI_BYTE('A')) FROM dual;
TO_NCHAR
Converts a DATE or TIMESTAMP from the database character set to the National Character Set specificed TO_NCHAR(<date_string | interval | CLOB | number>,
<format mask>, <NLS_PARAMETER>) RETURN NCHAR
SELECT TO_NCHAR('ABC')
FROM dual;

SELECT TO_NCHAR(1048576)
FROM dual;

conn oe/oe

SELECT TO_NCHAR(order_date)
FROM orders
WHERE order_status > 9;
TO_NCLOB
Converts CLOB values in a LOB column or other character strings to NCLOB | TO_NCLOB(lob_or_character_value) RETURN NCLOB
CREATE TABLE nclob_test(
nclobcol  NCLOB);

desc nclob_test

INSERT INTO nclob_test
(nclobcol)
VALUES
(TO_NCLOB('Convert this text into the NCLOB data type'));
TO_NUMBER
Converts a string to the NUMBER data type | TO_NUMBER(<value>[, <format>, <NLS parameter>]) RETURN NUMBER
CREATE TABLE test (
testcol VARCHAR2(10));

INSERT INTO test VALUES ('12345.67');

SELECT TO_BINARY_DOUBLE(testcol) BIN_DOUBLE, TO_BINARY_FLOAT(testcol) BIN_FLOAT, TO_NUMBER(testcol) NMBR
FROM test;
Converts a HEX number to FLOAT | TO_NUMBER(<value>, <format>);
SELECT TO_NUMBER('0A', 'XX')
FROM dual;
Converts a HEX number to DECIMAL TO_NUMBER(<binary_float | binary_double | number>,
'<hex mask>') RETURN <binary_float | binary_double | number>;
SELECT TO_NUMBER(100000,'XXXXXXXX')
FROM dual;
TO_SINGLE_BYTE
Returns char with all of its multibyte characters converted to their corresponding single-byte characters | TO_SINGLE_BYTE(character_string)
-- must be run in a UTF8 database to see the difference

SELECT TO_SINGLE_BYTE(CHR(15711393))
FROM dual;
TO_TIMESTAMP
Converts a string to an Timestamp Data Type TO_TIMESTAMP(<date_string>, <format mask>, <NLS_PARAMETER>)
RETURN TIMESTAMP
SELECT TO_TIMESTAMP('2004-12-01 11:00:00','YYYY-MM-DD HH:MI:SS')
FROM dual;
TO_TIMESTAMP_TZ
Converts a string to an Timestamp with Timezone Data Type TO_TIMESTAMP(<date_string>, <format mask>, <NLS_PARAMETER>)
RETURN TIMESTAMP WITH TIMEZONE
SELECT TO_TIMESTAMP_TZ('2004-12-01 11:00:00 -8:00',
'YYYY-MM-DD HH:MI:SS TZH:TZM') FROM dual;
TO_YMINTERVAL
Converts a character string of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to an INTERVAL YEAR TO MONTH type | TO_YMINTERVAL(<char>) RETURN YMINTERVAL
SELECT hire_date, hire_date+TO_YMINTERVAL('01-02') "14 months"
FROM emp;
TRANSLATE USING
Converts char into the character set specified for conversions between the database character set and the national character set | TRANSLATE(char_string USING <CHAR_CS character_set | NCHAR_CS character set>)
conn oe/oe

CREATE TABLE translate_tab (
char_col  VARCHAR2(100),
nchar_col NVARCHAR2(50));

desc translate_tab

INSERT INTO translate_tab
SELECT NULL, translated_name
FROM product_descriptions
WHERE product_id = 3501;

col char_col format a30
col nchar_col format a30

SELECT * FROM translate_tab;

UPDATE translate_tab
SET char_col = TRANSLATE(nchar_col USING CHAR_CS);

SELECT * FROM translate_tab;
UNISTR
Convert String To The National Character Set (either UTF8 or UTF16) | UNISTR(ch VARCHAR2 CHARACTER SET ANY_CS) RETURN NVARCHAR2;
SELECT UNISTR(ASCIISTR(CHR(128) || 'Hello' || CHR(255)))
FROM dual;
Related Topics
Date Functions
Numeric Functions
String Functions
Timestamp
XML Functions


Oracle Data Mining Functions

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
Note: The data mining functions operate on models that have been built using the DBMS_DATA_MINING package or the Oracle Data Mining Java API.
CLUSTER_ID
Returns the cluster identifier of the predicted cluster with the highest probability for the set of predictors specified in the mining_attribute_clause | CLUSTER_ID(<schame.model> <mining_attribute_clause>)
SELECT CLUSTER_ID(km_sh_clus_sample USING *) AS clus, COUNT(*) AS cnt
FROM km_sh_sample_apply_prepared
GROUP BY CLUSTER_ID(km_sh_clus_sample USING *)
ORDER BY cnt DESC;
CLUSTER_PROBABILITY
Returns a measure of the degree of confidence of membership of an input row in a cluster associated with the specified model. | CLUSTER_PROBABILITY(<schema.model>, <cluster_id> <mining_attribute_clause>)
SELECT *
FROM (
  SELECT cust_id, CLUSTER_PROBABILITY(km_sh_clus_sample, 2 USING *)
  prob
  FROM km_sh_sample_apply_prepared
  ORDER BY prob DESC)
WHERE ROWNUM < 11;
CLUSTER_SET

Returns a varray of objects containing all possible clusters that a given row belongs to. Each object in the varray is a pair of scalar values containing the cluster ID and the cluster probability. The object fields are named CLUSTER_ID and PROBABILITY, and both are Oracle NUMBER 		CLUSTER_SET(<schema.model>, <top N>, <cutoff>
<mining_attribute_clause>)
WITH clus_tab AS (SELECT id, A.attribute_name aname,
A.conditional_operator op, NVL(A.attribute_str_value,
ROUND(DECODE(A.attribute_name, N.col,
A.attribute_num_value * N.scale + N.shift,
A.attribute_num_value),4)) val,
A.attribute_support support,
A.attribute_confidence confidence
FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_KM('km_sh_clus_sample')) T,
TABLE(T.rule.antecedent) A, km_sh_sample_norm N
WHERE A.attribute_name = N.col(+) AND A.attribute_confidence > 0.55),
clust AS (
  SELECT id, CAST(COLLECT(Cattr(aname, op, TO_CHAR(val), support,
  confidence)) AS Cattrs) cl_attrs
  FROM clus_tab
  GROUP BY id), custclus AS (
    SELECT T.cust_id, S.cluster_id, S.probability
    FROM (
      SELECT cust_id, CLUSTER_SET(km_sh_clus_sample, NULL, 0.2 USING *)
      pset
      FROM km_sh_sample_apply_prepared
      WHERE cust_id = 101362) T,
      TABLE(T.pset) S)
    SELECT A.probability prob, A.cluster_id cl_id, B.attr, B.op, B.val,
    B.supp, B.conf
    FROM custclus A, (
      SELECT T.id, C.*
      FROM clust T, TABLE(T.cl_attrs) C) B
      WHERE A.cluster_id = B.id
      ORDER BY prob DESC, cl_id ASC, conf DESC, attr ASC, val ASC;
FEATURE_ID
Returns an Oracle NUMBER that is the identifier of the feature with the highest coefficient value | FEATURE_ID(<schame.model> <mining_attribute_clause>)
SELECT FEATURE_ID(nmf_sh_sample USING *) AS feat, COUNT(*) AS cnt
FROM nmf_sh_sample_apply_prepared
GROUP BY FEATURE_ID(nmf_sh_sample USING *)
ORDER BY cnt DESC;
FEATURE_SET
Returns a varray of objects containing all possible features. Each object in the varray is a pair of scalar values containing the feature ID and the feature value. The object fields are named FEATURE璤ID and VALUE, and both are Oracle NUMBERs. FEATURE_SET(<schema.model>, <top N>, <cutoff>
<mining_attribute_clause>)
WITH
feat_tab AS (
SELECT F.feature_id fid,
       A.attribute_name attr,
       TO_CHAR(A.attribute_value) val,
       A.coefficient coeff
  FROM TABLE(DBMS_DATA_MINING.GET_MODEL_DETAILS_NMF('nmf_sh_sample')) F,
       TABLE(F.attribute_set) A
 WHERE A.coefficient > 0.25), feat AS (
SELECT fid,
       CAST(COLLECT(Featattr(attr, val, coeff)) AS Featattrs) f_attrs
  FROM feat_tab
GROUP BY fid
),
cust_10_features AS (
SELECT T.cust_id, S.feature_id, S.value
  FROM (SELECT cust_id, FEATURE_SET(nmf_sh_sample, 10 USING *) pset
        FROM nmf_sh_sample_apply_prepared
        WHERE cust_id = 100002) T, TABLE(T.pset) S)
SELECT A.value, A.feature_id fid,
       B.attr, B.val, B.coeff
  FROM cust_10_features A,
       (SELECT T.fid, F.*
        FROM feat T, TABLE(T.f_attrs) F) B
 WHERE A.feature_id = B.fid
ORDER BY A.value DESC, A.feature_id ASC, coeff DESC, attr ASC, val ASC;
FEATURE_VALUE
Returns the value of a given feature. If you omit the feature_id argument, then the function returns the highest feature value. You can use this form in conjunction with the FEATURE_ID function to obtain the largest feature/value combo. | FEATURE_VALUE(<schema.model>,<feature_id><mining_attribute_clause>)
SELECT *
FROM (
  SELECT cust_id, FEATURE_VALUE(nmf_sh_sample,3 USING *) match_qual
  FROM nmf_sh_sample_apply_prepared
  ORDER BY match_quality DESC)
WHERE ROWNUM < 11;
PREDICTION
Returns the best prediction for the model. The datatype returned depends on the target value type used during the build of the model. For regression models, this function returns the expected value. PREDICTION(<schema.model>, <cost_matrix_clause>
<mining_attribute_clause>)
SELECT cust_gender, COUNT(*) AS cnt, ROUND(AVG(age)) AS avg_age
FROM mining_data_apply_v
WHERE PREDICTION(DT_SH_Clas_sample COST MODEL
USING cust_marital_status, education, household_size) = 1
GROUP BY cust_gender
ORDER BY cust_gender;
PREDICTION_BOUNDS (new in 11g)
Ffor use only with generalized linear models. It returns an object with two NUMBER fields LOWER and UPPER. PREDICTION_BOUNDS(<schema.model>, <confidence_level>, <class_value>
USING <* | schema.table.* | expression AS alias>
SELECT cust_marital_status, COUNT(cust_id) AS CUST_COUNT
FROM (
  SELECT cust_id, cust_marital_status
  FROM mining_data_apply_v
  WHERE PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).LOWER > 24
  AND PREDICTION_BOUNDS(glmr_sh_regr_sample,0.98 USING *).UPPER < 46)
GROUP BY cust_marital_status;
PREDICTION_COST
Returns a measure of cost for a given prediction as an Oracle NUMBER PREDICTION_COST(<schema.model>, <class> <cost_matrix_clause>
<mining_attribute_clause>)
WITH cust_italy AS (
  SELECT cust_id
  FROM mining_data_apply_v
  WHERE country_name = 'Italy'
  ORDER BY PREDICTION_COST(DT_SH_Clas_sample,1 COST MODEL USING *) ASC,1)
SELECT cust_id
FROM cust_italy
WHERE rownum < 11;
PREDICTION_DETAILS
Returns an XML string containing model-specific information related to the scoring of the input row | PREDICTION_DETAILS(<schema.model> <mining_attribute_clause>)
SELECT cust_id, education,
PREDICTION_DETAILS(DT_SH_Clas_sample using *) treenode
FROM mining_data_apply_v
WHERE occupation = 'TechSup' AND age < 25
ORDER BY cust_id;
PREDICTION_PROBABILITY
Returns the probability for a given prediction as an Oracle NUMBER PREDICTION_PROBABILITY(<schema.model> <class>
<mining_attribute_clause>)
SELECT cust_id
FROM (
  SELECT cust_id
  FROM mining_data_apply_v
  WHERE country_name = 'Italy'
  ORDER BY PREDICTION_PROBABILITY(DT_SH_Clas_sample, 1 USING *)
  DESC, cust_id)
WHERE rownum < 11;
PREDICTION_SET
Returns a varray of objects containing all classes in a multiclass classification scenario PREDICTION_SET(<schema.model>, <best N>, <cutoff>
<cost_matrix_clause> <mining_attribute_clause>)
SELECT T.cust_id, S.prediction, S.probability, S.cost
FROM (
  SELECT cust_id,
 PREDICTION_SET(dt_sh_clas_sample COST MODEL USING *) pset
  FROM mining_data_apply_v
  WHERE cust_id < 100011) T,
TABLE(T.pset) S
ORDER BY cust_id, S.prediction;
Related Topics
Date Functions
Numeric Functions
String Functions
Timestamp


Oracle Date Functions

MOracle Date Functions

Would you like to learn Oracle from Ace Director Dan Morgan the author of this library?

If so the "Database Essentials" class will begin November 19, 2007 at SQL University ... Try the free Sample Courses and then check out the list of classes and topics. The first class covers materials in the library, including this page, with live demos in SQL*Plus.

The SQL University Registration Page will be active the first day of OpenWorld.

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
Date
Current Date CURRENT_DATE
SYSDATE
SELECT TO_CHAR(CURRENT_DATE, 'DD-MON-YYYY HH:MI:SS') FROM dual;

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH:MI:SS') FROM dual;
Formats
Day | Month | Year | Fill Mode | Julian Date
D | MM | YY | FM | J
DD | MON | YYYY |  |
DDTH |  | RR |  |
DAY |  | RRRR |  |

Formats That Can Be Used With ROUND And TRUNC Functions 		- One greater than the first two digits of a four-digit year
CC
SCC

- Year (rounds up on July 1)
SYYYY
YYYY
YEAR
SYEAR
YYY
YY
Y

- ISO Year
IYYY
IY
IY
I

- Quarter (rounds up on 16th day of the 2nd month of the quarter)
Q

- Month (rounds up on the sixteenth day)
MONTH
MON
MM
RM

- Week of the year
WW

- Same day of the week as the first day of the ISO year
IW

- Same day of the week as the first day of the month
W

- Day
DDD
DD
J

- Starting day of the week
DAY
DY
D

- Hours
HH
HH12
HH24

- Minute
MI
+ AND -
+ <date> + <integer>
SELECT SYSDATE + 1 FROM dual;
- <date> - <integer>
SELECT SYSDATE - 1 FROM dual;
ADD_MONTHS

Add A Month To A Date 		ADD_MONTHS(<date>, <number of months_integer>
SELECT add_months(SYSDATE, 2) FROM dual;

-- but be aware of what it is doing
SELECT add_months(TO_DATE('27-JAN-2007'), 1) FROM dual;

SELECT add_months(TO_DATE('28-JAN-2007'), 1) FROM dual;

SELECT add_months(TO_DATE('29-JAN-2007'), 1) FROM dual;

SELECT add_months(TO_DATE('30-JAN-2007'), 1) FROM dual;

SELECT add_months(TO_DATE('31-JAN-2007'), 1) FROM dual;

SELECT add_months(TO_DATE('01-FEB-2007'), 1) FROM dual;
CURRENT_DATE

Returns the current date of the server as a value in the Gregorian calendar of datatype DATE
col sessiontimezone format a30

SELECT sessiontimezone, current_date
FROM dual;

ALTER SESSION SET TIME_ZONE = '-5:0';

SELECT sessiontimezone, current_date
FROM dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT sessiontimezone, current_date
FROM dual;

ALTER SESSION SET TIME_ZONE = '-7:0';

SELECT sessiontimezone, current_date
FROM dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
DUMP
Returns The Number Of Bytes And Datatype Of A Value | DUMP(<value>)
SELECT DUMP(SYSDATE) FROM dual;
GREATEST

Return the Latest Date 		LEAST(<date>, <date>, <date>, ...)
CREATE TABLE t (
datecol1 DATE,
datecol2 DATE,
datecol3 DATE)
PCTFREE 0;

INSERT INTO t VALUES (SYSDATE+23, SYSDATE-10, SYSDATE-24);
INSERT INTO t VALUES (SYSDATE-15, SYSDATE, SYSDATE+15);
INSERT INTO t VALUES (SYSDATE-7, SYSDATE-18, SYSDATE-9);
COMMIT;

SELECT * FROM t;

SELECT GREATEST(datecol1, datecol2, datecol3)
FROM t;
INTERVAL

Interval to adjust date-time 		INTERVAL '<integer>' <unit>
SELECT TO_CHAR(SYSDATE, 'HH:MI:SS')
FROM dual;

SELECT TO_CHAR(SYSDATE + INTERVAL '10' MINUTE, 'HH:MI:SS')
FROM dual;

SELECT TO_CHAR(SYSDATE - INTERVAL '10' MINUTE, 'HH:MI:SS')
FROM dual;
LAST_DAY
Returns The Last Date Of A Month | LAST_DAY(<date>)
SELECT * FROM t;

SELECT LAST_DAY(datecol1) FROM t;
LEAST
Return the Earliest Date | LEAST(<date>, <date>, <date>, ...)
SELECT * FROM t;

SELECT LEAST(datecol1, datecol2, datecol3) FROM t;
LENGTH
Returns length in characters | LENGTH(<date>)
SELECT LENGTH(last_ddl_time) FROM user_objects;
LENGTHB
Returns length in bytes | LENGTHB(<date>)
SELECT LENGTHB(last_ddl_time) FROM user_objects;
Note: Additional forms of LENGTH (LENGTHC, LENGTH2, and LENGTH4) are also available.
MAX
Return the Latest Date | MAX(<date>)
SELECT * FROM t;

SELECT MAX(datecol1) FROM t;
MIN
Return the Earliest Date | MIN(<date>)
SELECT * FROM t;

SELECT MIN(datecol1) FROM t;
MONTHS_BETWEEN
Returns The Months Separating Two Dates | MONTHS_BETWEEN(<latest_date>, <earliest_date>)
SELECT MONTHS_BETWEEN(SYSDATE+365, SYSDATE-365) FROM dual;

SELECT MONTHS_BETWEEN(SYSDATE-365, SYSDATE+365) FROM dual;
NEW_TIME

Returns the date and time in time zone zone2 when date and time in time zone zone1 are date 		Before using this function, you must set the NLS_DATE_FORMAT parameter to display 24-hour time.
SELECT NEW_TIME(TO_DATE('11-10-99 01:23:45',
'MM-DD-YY HH24:MI:SS'), 'AST', 'PST') "New Date and Time"
FROM dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT NEW_TIME(TO_DATE('11-10-99 01:23:45',
'MM-DD-YY HH24:MI:SS'), 'AST', 'PST') "New Date and Time"
FROM dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
NEXT_DAY
Date of next specified date following a date NEXT_DAY(<date>, <day of the week>)

Options are SUN, MON, TUE, WED, THU, FRI, and SAT
SELECT NEXT_DAY(SYSDATE, 'FRI') FROM dual;
ROUND
Returns date rounded to the unit specified by the format model. If you omit the format, the date is rounded to the nearest day | ROUND(<date_value>, <format>)
SELECT ROUND(TO_DATE('27-OCT-00'),'YEAR') NEW_YEAR
FROM dual;
Spelled Out Using TO_CHAR

Spelled Demo
DDSP HH24SP MISP MMSP SSSP
SELECT TO_CHAR(TO_DATE('10:30:18', 'HH24:MI:SS'), 'HH24SP:MISP:SSSP')
FROM dual;

SELECT TO_CHAR(TO_DATE('01-JAN-2008', 'DD-MON-YYYY'), 'DDSP-MONTH-YYYYSP')
FROM dual;

SELECT TO_CHAR(TO_DATE('01-JAN-2008', 'DD-MM-YYYY'), 'DDSP-MMSP-YYYYSP')
FROM dual;
SYSDATE
Returns the current session DateTime | SYSDATE
SELECT SYSDATE FROM dual;
TRUNC

Convert a date to the date at midnight 		TRUNC(<date_time>)
CREATE TABLE t (
datecol DATE);

INSERT INTO t (datecol) VALUES (SYSDATE);

INSERT INTO t (datecol) VALUES (TRUNC(SYSDATE));

INSERT INTO t (datecol) VALUES (TRUNC(SYSDATE, 'HH'));

INSERT INTO t (datecol) VALUES (TRUNC(SYSDATE, 'MI'));

COMMIT;

SELECT TO_CHAR(datecol, 'DD-MON-YYYY HH:MI:SS')
FROM t;

Selectively remove part of the date information

Special thanks to Dave Hayes for reminding me of this. 		TRUNC(<date_time>, '<format>')
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH:MI:SS')
FROM dual;

-- first day of the month
SELECT TO_CHAR(TRUNC(SYSDATE, 'MM'), 'DD-MON-YYYY HH:MI:SS')
FROM dual;

SELECT TO_CHAR(TRUNC(SYSDATE, 'MON'), 'DD-MON-YYYY HH:MI:SS')
FROM dual;

SELECT TO_CHAR(TRUNC(SYSDATE, 'MONTH'), 'DD-MON-YYYY HH:MI:SS')
FROM dual;

-- first day of the year
SELECT TO_CHAR(TRUNC(SYSDATE, 'YYYY'), 'DD-MON-YYYY HH:MI:SS')
FROM dual;

SELECT TO_CHAR(TRUNC(SYSDATE, 'YEAR'), 'DD-MON-YYYY HH:MI:SS')
FROM dual;

Dates in WHERE Clause Joins 		SELECT SYSDATE FROM dual;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT SYSDATE FROM dual;

/

/

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';

CREATE TABLE t (
datecol DATE);

INSERT INTO t
(datecol)
VALUES
(SYSDATE);

SELECT * FROM t;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT * FROM t;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';

SELECT * FROM t;

SELECT SYSDATE FROM dual;

SELECT * FROM t
WHERE datecol = SYSDATE;

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT * FROM t;

SELECT SYSDATE FROM dual;

SELECT TRUNC(SYSDATE) FROM dual;

SELECT * FROM t
WHERE TRUNC(datecol) = TRUNC(SYSDATE);

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
VSIZE
Returns The Number Of Bytes Required By A Value | VSIZE(e IN DATE) RETURN NUMBER
SELECT VSIZE(SYSDATE) FROM dual;
Date Calculations

Returns A Day A Specified Number Of Days In The Future Skipping Weekends 		CREATE OR REPLACE FUNCTION business_date (start_date DATE,
Days2Add NUMBER) RETURN DATE IS
 Counter  NATURAL := 0;
 CurDate  DATE := start_date;
 DayNum   POSITIVE;
 SkipCntr NATURAL := 0;
BEGIN
  WHILE Counter < Days2Add LOOP
    CurDate := CurDate+1;
    DayNum := TO_CHAR(CurDate, 'D');

    IF DayNum BETWEEN 2 AND 6 THEN
      Counter := Counter + 1;
    ELSE
      SkipCntr := SkipCntr + 1;
    END IF;
  END LOOP;
  RETURN start_date + Counter + SkipCntr;
END business_date;
/

Business Date function, above, enhanced by Larry Benton to handle negative values for the days2add parameter. 		CREATE OR REPLACE FUNCTION business_date (start_date DATE,
days2add NUMBER) RETURN DATE IS
 Counter NATURAL := 0;
 CurDate DATE := start_date;
 DayNum POSITIVE;
 SkipCntr NATURAL := 0;
 Direction INTEGER := 1;  -- days after start_date
 BusinessDays NUMBER := Days2Add;
BEGIN
  IF Days2Add < 0 THEN
    Direction := - 1; -- days before start_date
    BusinessDays := (-1) * BusinessDays;
  END IF;

  WHILE Counter < BusinessDays LOOP
    CurDate := CurDate + Direction;
    DayNum := TO_CHAR( CurDate, 'D');

    IF DayNum BETWEEN 2 AND 6 THEN
      Counter := Counter + 1;
    ELSE
      SkipCntr := SkipCntr + 1;
    END IF;
  END LOOP;

  RETURN start_date + (Direction * (Counter + SkipCntr));
END business_date;
/

Returns The First Day Of A Month 		CREATE OR REPLACE FUNCTION fday_ofmonth(value_in DATE)
RETURN DATE IS
 vMo VARCHAR2(2);
 vYr VARCHAR2(4);
BEGIN
  vMo := TO_CHAR(value_in, 'MM');
  vYr := TO_CHAR(value_in, 'YYYY');
  RETURN TO_DATE(vMo || '-01-' || vYr, 'MM-DD-YYYY');
EXCEPTION
  WHEN OTHERS THEN
    RETURN TO_DATE('01-01-1900', 'MM-DD-YYYY');
END fday_ofmonth;
/
Time Calculations

Returns The Number Of Seconds Between Two Date-Time Values 		CREATE OR REPLACE FUNCTION time_diff (
DATE_1 IN DATE, DATE_2 IN DATE) RETURN NUMBER IS

NDATE_1   NUMBER;
NDATE_2   NUMBER;
NSECOND_1 NUMBER(5,0);
NSECOND_2 NUMBER(5,0);

BEGIN
  -- Get Julian date number from first date (DATE_1)
  NDATE_1 := TO_NUMBER(TO_CHAR(DATE_1, 'J'));

  -- Get Julian date number from second date (DATE_2)
  NDATE_2 := TO_NUMBER(TO_CHAR(DATE_2, 'J'));

  -- Get seconds since midnight from first date (DATE_1)
  NSECOND_1 := TO_NUMBER(TO_CHAR(DATE_1, 'SSSSS'));

  -- Get seconds since midnight from second date (DATE_2)
  NSECOND_2 := TO_NUMBER(TO_CHAR(DATE_2, 'SSSSS'));

  RETURN (((NDATE_2 - NDATE_1) * 86400)+(NSECOND_2 - NSECOND_1));
END time_diff;
/
Calculating time from seconds

Posted by John K. Hinsdale
12/30/06 to c.d.o.misc 		SELECT DECODE(FLOOR(999999/86400), 0, '',
              FLOOR(999999/86400) || ' day(s), ') ||
   TO_CHAR(TO_DATE(MOD(999999, 86400),'SSSSS'), 'HH24:MI:SS') AS elapsed
FROM dual;
Related Topics
Cast
Conversion Functions
Miscellaneous Functions
Numeric Functions
String Functions
Timestamp


Oracle DBMS_ASYNCRPC_PUSH
General Information
Source | {ORACLE_HOME}/rdbms/admin/prvtarpp.plb
Dependencies
DBMS_DEFER | DBMS_REPCAT_SNA_UTL
DBMS_DEFER_QUERY_UTL | DBMS_REPCAT_UTL
DBMS_DEFER_REPCAT | DBMS_REPCAT_UTL3
DBMS_DEFER_SYS | DBMS_SYSTEM
DBMS_DEFER_SYS_PART1 | DBMS_SYS_ERROR
DBMS_LOCK | DEF$_DESTINATION
DBMS_OFFLINE_RGT | DEFTRANDEST
DBMS_REPCAT_DECL | REPCAT$_EXTENSION
Object Privileges | execute on dbms_asyncrpc_push
GRANT execute on dbms_asyncrpc_push TO uwclass;
CHECK_DATABASE_CAPABILITY
Undocumented dbms_asyncrpc_push.check_database_capability(
nodename   VARCHAR2,
userid     BINARY_INTEGER,
capability BINARY_INTEGER)
RETURN BOOLEAN
TBD
ERROR_CALL_POSITION
Undocumented dbms_asyncrpc_push.error_call_position(
nodename  IN  VARCHAR2,
userid    IN  BINARY_INTEGER,
position  OUT BINARY_INTEGER)
TBD
GET_CLOCK_TIME
Get current time on system clock | dbms_asyncrpc_push.get_clock_time RETURN NUMBER;
SELECT dbms_asyncrpc_push.get_clock_time FROM dual;

SELECT dbms_utility.get_time FROM dual;
GET_SCN
Returns current system change | dbms_asyncrpc_push.get_scn RETURN NUMBER;
SELECT dbms_asyncrpc_push.get_scn FROM dual;

SELECT current_scn FROM gv$database;
PROPAGATE_PARALLEL

Undocumented 		dbms_asyncrpc_push.propagate_parallel(
canon_queue          IN VARCHAR2,
userid               IN BINARY_INTEGER,
stop_on_error        IN BOOLEAN,
new_txn_count        IN BINARY_INTEGER,
startup_seconds      IN BINARY_INTEGER,
execution_seconds    IN BINARY_INTEGER,
delay_seconds        IN BINARY_INTEGER,
num_threads          IN BINARY_INTEGER,
heap_size            IN BINARY_INTEGER,
write_trace          IN BOOLEAN,
delivery_order_limit IN NUMBER,
catchup              IN RAW)
RETURN BINARY_INTEGER;
TBD
PROPAGATE_SERIAL
Undocumented dbms_asyncrpc_push.propagate_serial(
queue             IN VARCHAR2,
userid            IN BINARY INTEGER,
stop_on_error     IN BOOLEAN,
new_txn_count     IN BINARY INTEGER,
execution_seconds IN BINARY INTEGER,
delay_seconds     IN BINARY INTEGER,
txn_batch_size    IN BINARY_INTEGER)
TBD
PURGE_PARALLEL
Undocumented dbms_asyncrpc_push.purge_paralle(
method            IN     BINARY_INTEGER,
rollback_segment  IN     VARCHAR2,
execution_seconds IN OUT BINARY_INTEGER,
delay_seconds     IN     BINARY_INTEGER,
write_trace       IN     BOOLEAN,
transaction_count IN OUT BINARY_INTEGER)
RETURN BINARY_INTEGER;
TBD
PUSH_PENDING_CALLS
Undocumented dbms_asyncrpc_push.push_pending_calls(
query_type  IN BINARY_INTEGER,
nodename    IN VARCHAR2,
userid      IN BINARY_INTEGER,
buffer_size IN BINARY_INTEGER,
tid         IN VARCHAR2,
call_type   IN BINARY_INTEGER)
RETURN BINARY_INTEGER;
TBD
STAMP_QUEUE_BATCH
Undocumented | dbms_asyncrpc_push.stamp_queue_batch(scn_limit OUT NUMBER);
set serveroutput on

DECLARE
 n NUMBER;
BEGIN
  dbms_asyncrpc_push.stamp_queue_batch(n);
  dbms_output.put_line(n);
END;
/
UPDATE_PURGE_STATISTICS
Undocumented dbms_asyncrpc_push.update_purge_statistics(
txnspurged IN BINARY_INTEGER)
TBD


Oracle DBMS_CRYPTO Encryption Cryptography Security

Oracle DBMS_CRYPTO
General Information
Source | {ORACLE_HOME}/rdbms/admin/dbmsobtk.sql
First Available | 10.1

Algorithm Constants
Name | Data Type | Value
Hash Functions
HASH_MD4 (128 bit hash) | PLS_INTEGER | 1
HASH_MD5 (128 bit hash) | PLS_INTEGER | 2
HASH_SH1 (160 bit hash) | PLS_INTEGER | 3
MAC Functions
HMAC_MD5 (128 bit hash) | PLS_INTEGER | 1
HMAC_SH1 (160 bit hash) | PLS_INTEGER | 2
Block Cipher Algorithms
ENCRYPT_DES (56 bit) | PLS_INTEGER | 1; -- 0x0001
ENCRYPT_3DES_2KEY (128 bit) | PLS_INTEGER | 2; -- 0x0002
ENCRYPT_3DES | PLS_INTEGER | 3; -- 0x0003
ENCRYPT_AES | PLS_INTEGER | 4; -- 0x0004
ENCRYPT_PBE_MD5DES | PLS_INTEGER | 5; -- 0x0005
ENCRYPT_AES128 (128 bit) | PLS_INTEGER | 6; -- 0x0006
ENCRYPT_AES192 (192 bit) | PLS_INTEGER | 7; -- 0x0007
ENCRYPT_AES256 (256 bit) | PLS_INTEGER | 8; -- 0x0008
ENCRYPT_RC4 (Stream Cipher) | PLS_INTEGER | 129; -- 0x0081
Block Cipher Chaining Modifiers
CHAIN_CBC (Cipher Block Chaining) | PLS_INTEGER | 256; -- 0x0100
CHAIN_CFB (Cipher Feedback) | PLS_INTEGER | 512; -- 0x0200
CHAIN_ECB (Electronic cookbook) | PLS_INTEGER | 768; -- 0x0300
CHAIN_OFB (Output Feedback) | PLS_INTEGER | 1024; -- 0x0400
Block Cipher Padding Modifiers
PAD_PKCS5 (Complies with PKCS #5) | PLS_INTEGER | 4096; -- 0x1000
PAD_NONE (No padding) | PLS_INTEGER | 8192; -- 0x2000
PAD_ZERO (Pad with zeros) | PLS_INTEGER | 12288; -- 0x3000
PAD_ORCL | PLS_INTEGER | 16384; -- 0x4000
Block Ciphers Suites
DES3_CBC_PKCS5 PLS_INTEGER ENCRYPT_3DES
+ CHAIN_CBC
+ PAD_PKCS5;
DES3_CBC_PKCS5 PLS_INTEGER ENCRYPT_3DES
+ CHAIN_CBC
+ PAD_PKCS5;
AES_CBC_PKCS5 PLS_INTEGER ENCRYPT_AES
+ CHAIN_CBC
+ PAD_PKCS5;
Dependencies
DBMS_CRYPTO_FFI | DECRYPTBYTES | ENCRYPTBYTES
DECRYPT | ENCRYPT | UTL_RAW

Exceptions
Error Code | Reason
28827 | The specified cipher suite is not defined
28829 | No value has been specified for the cipher suite to be used
28233 | Source data was previously encrypted
28234 | DES: Specified key size too short. DES keys must be at least 8 bytes (64 bits). AES: Specified key size is not supported. AES keys must be 128, 192, or 256 bits
28239 | The encryption key has not been specified or contains a NULL value
DECRYPT
Decrypt crypt text data using stream or block cipher with user supplied key and optional iv

Overload 1 		dbms_crypto.decrypt(
src IN RAW,
typ IN PLS_INTEGER,
key IN RAW,
iv  IN RAW DEFAULT NULL) RETURN RAW;
See Encrypt Overload 1 demo
Overload 2 dbms_crypto.decrypt(
dst IN OUT NOCOPY BLOB,
src IN            BLOB,
typ IN            PLS_INTEGER,
key IN            RAW,
iv  IN            RAW DEFAULT NULL);
Overload 3 dbms_crypto.decrypt (
dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src IN            BLOB,
typ IN            PLS_INTEGER,
key IN            RAW,
iv  IN            RAW DEFAULT NULL);
ENCRYPT

Encrypt plain text data using stream or block cipher with user supplied key and optional iv

Overload 1 		dbms_crypto.encrypt(
src IN RAW,
typ IN PLS_INTEGER,
key IN RAW,
iv  IN RAW DEFAULT NULL)
RETURN RAW;
set serveroutput on

set linesize 121

DECLARE
 l_credit_card_no VARCHAR2(19) := '1234-5678-9012-3456';
 l_ccn_raw RAW(128) := utl_raw.cast_to_raw(l_credit_card_no);
 l_key     RAW(128) := utl_raw.cast_to_raw('abcdefgh');

 l_encrypted_raw RAW(2048);
 l_decrypted_raw RAW(2048);
BEGIN
  dbms_output.put_line('Original : ' || l_credit_card_no);

  l_encrypted_raw := dbms_crypto.encrypt(l_ccn_raw,
  dbms_crypto.des_cbc_pkcs5, l_key);

  dbms_output.put_line('Encrypted : ' ||
  RAWTOHEX(utl_raw.cast_to_raw(l_encrypted_raw)));

  l_decrypted_raw := dbms_crypto.decrypt(src => l_encrypted_raw,
  typ => dbms_crypto.des_cbc_pkcs5, key => l_key);

  dbms_output.put_line('Decrypted : ' ||
  utl_raw.cast_to_varchar2(l_decrypted_raw));
END;
/
set serveroutput on

DECLARE
 enc_val   RAW(2000);
 l_key     RAW(2000);
 l_key_len NUMBER := 128/8; -- convert bits to bytes
 l_mod     NUMBER := dbms_crypto.ENCRYPT_AES128
 + dbms_crypto.CHAIN_CBC + dbms_crypto.PAD_ZERO;

BEGIN
  l_key := dbms_crypto.randombytes(l_key_len);

  enc_val := dbms_crypto.encrypt(
  utl_i18n.string_to_raw('1234-5678-9012-3456', 'AL32UTF8'),
  l_mod, l_key);

  dbms_output.put_line(enc_val);
END;
/
Overload 2 dbms_crypto.encrypt(
dst IN OUT NOCOPY BLOB,
src IN     BLOB,
typ IN     PLS_INTEGER,
key IN     RAW,
iv  IN     RAW DEFAULT NULL);
Overload 3 dbms_crypto.encrypt(
dst IN OUT NOCOPY BLOB,
src IN     CLOB CHARACTER SET ANY_CS,
typ IN     PLS_INTEGER, key IN RAW,
iv  IN     RAW DEFAULT NULL);
dbms_crypto.encrypt(UTL_RAW.CAST_TO_RAW(CONVERT('XXX','AL32UTF8')),typ,key);
HASH

Hash source data by cryptographic hash type

Overload 1 		dbms_crypto.hash(src IN RAW, typ IN PLS_INTEGER) RETURN RAW;
set serveroutput on

DECLARE
 l_credit_card_no VARCHAR2(19) := '1234-5678-9012-3456';
 l_ccn_raw RAW(128) := utl_raw.cast_to_raw(l_credit_card_no);
 l_encrypted_raw RAW(2048);
BEGIN
  dbms_output.put_line('CC:  ' || l_ccn_raw);

  l_encrypted_raw := dbms_crypto.hash(l_ccn_raw, 1);
  dbms_output.put_line('MD4: ' || l_encrypted_raw);

  l_encrypted_raw := dbms_crypto.hash(l_ccn_raw, 2);
  dbms_output.put_line('MD5: ' || l_encrypted_raw);

  l_encrypted_raw := dbms_crypto.hash(l_ccn_raw, 3);
  dbms_output.put_line('SH1: ' || l_encrypted_raw);
END;
/
Overload 2 | dbms_crypto.hash(src IN BLOB, typ IN PLS_INTEGER) RETURN RAW;
Overload 3 | dbms_crypto.hash(src IN CLOB CHARACTER SET ANY_CS, typ IN PLS_INTEGER) RETURN RAW;
MAC

Message Authentication Code algorithms provide keyed message protection

Overload 1 		dbms_crypto.mac(src IN RAW, typ IN PLS_INTEGER, key IN RAW) RETURN RAW;
set serveroutput on

DECLARE
 l_credit_card_no VARCHAR2(19) := '1234-5678-9012-3456';
 l_ccn_raw RAW(128) := utl_raw.cast_to_raw(l_credit_card_no);
 l_key     RAW(128) := utl_raw.cast_to_raw('abcdefgh');
 l_encrypted_raw RAW(2048);
BEGIN
  dbms_output.put_line('CC:  ' || l_ccn_raw);
  dbms_output.put_line('Key: ' || l_key);

  l_encrypted_raw := dbms_crypto.mac(l_ccn_raw, 1, l_key);
  dbms_output.put_line('MD5: ' || l_encrypted_raw);

  l_encrypted_raw := dbms_crypto.mac(l_ccn_raw, 2, l_key);
  dbms_output.put_line('SH1: ' || l_encrypted_raw);
END;
/
Overload 2 | dbms_crypto.mac(src IN BLOB, typ IN PLS_INTEGER, key IN RAW) RETURN RAW;
Overload 3 dbms_crypto.mac(
src IN CLOB CHARACTER SET ANY_CS,
typ IN PLS_INTEGER, key IN RAW) RETURN RAW;
RANDOMBYTES

Returns a raw value containing a pseudo-random sequence of bytes 		dbms_crypto.randomnytes(number_bytes PLS_INTEGER) RETURN RAW;
SELECT dbms_crypto.randombytes(1) FROM dual;
SELECT LENGTH(dbms_crypto.randombytes(1)) FROM dual;

SELECT dbms_crypto.randombytes(28) FROM dual;
SELECT LENGTH(dbms_crypto.randombytes(28)) FROM dual;

SELECT dbms_crypto.randombytes(64) FROM dual;
SELECT LENGTH(dbms_crypto.randombytes(64)) FROM dual;
RANDOMINTEGER
Returns a random BINARY_INTEGER | dbms_crypto.randominteger RETURN NUMBER;
SELECT dbms_crypto.randominteger FROM dual;
RANDOMNUMBER
Returns a random Oracle Number | dbms_crypto.randomnumber RETURN NUMBER;
SELECT dbms_crypto.randomnumber FROM dual;
Related Topics
DBMS_CRYPTO_TOOLKIT_TYPES
DBMS_OBFUSCATION_TOOLKIT
DBMS_RANDOM
Label Security
Net Services
Oracle IDentity (OID)
Transparent Data Encryption (TDE)
UTL_I18N
UTL_RAW


/Oracle DBMS_CRYPTO_TOOLKIT_TYPES
General
Data types used by the DBMS_CRYPTO packages
Source {ORACLE_HOME}/rdbms/admin/dbmsoctk.sql
Dependencies
DBMS_CRYPTO_TOOLKIT DBMS_CRYPTO_TOOLKIT_FFI
Data Structures alias_string_length VARCHAR2(512);
SUBTYPE Alias_String IS alias_string_length%TYPE;

comment_string_length VARCHAR2(512);
SUBTYPE Comment_String IS comment_string_length%TYPE;

-- This data structure describes an identity. An identity may
-- either be myself (a persona) or another trusted identity
TYPE Identity_Description IS RECORD (
alias   Alias_String,
comment Comment_String);

-- This table serves as list of the retrieved identity descriptions
TYPE Identity_Description_List IS TABLE OF Identity_Description
INDEX BY BINARY_INTEGER;

-- This record contains the printable alias for a persona as well as the
-- complete identity and persona.
-- NOTE: the size of the persona field must match that contained within
-- the Persona type. PL/SQL will not allow a record to contain another
-- record so the Persona could not be used directly.
TYPE Persona_Description IS RECORD (
alias    Alias_String,
comment  Comment_String,
identity Identity_Internal,
persona  Persona_Internal);

TYPE Persona_List IS TABLE OF
Persona_Description
INDEX BY BINARY_INTEGER;

-- This data structure is a place holder until it is determined
-- what private information is needed to create a persona.
Private_Persona_Info_Size RAW(200);
SUBTYPE Private_Persona_Info_Internal IS Private_Persona_Info_Size%TYPE;
TYPE Private_Persona_Information is RECORD
(information Private_Persona_Info_Internal);
Opaque Datatypes -- These data types are intended to be opaque. The contents of the
-- records are either not visible to the caller or are to be accessed
-- using convenience functions. Unfortunately, PL/SQL does not allow
-- type definitions to be hidden inside the package bodies.

-- Records are used in order to enforce type checking as PL/SQL will
-- otherwise do automatic type conversion.

-- Dummy variables are used to get around PL/SQL restriction which does
-- not allow constrained subtypes, e.g. SUBTYPE foo is VARCHAR(15) is
-- not allowed.

wallet_size RAW(200);
SUBTYPE Wallet_Internal IS wallet_size%TYPE;
TYPE Wallet IS RECORD (Wallet Wallet_Internal);

persona_internal_size RAW(200);
SUBTYPE Persona_Internal IS persona_internal_size%TYPE;
TYPE Persona IS RECORD (Persona Persona_Internal);

identity_internal_size RAW(200);
SUBTYPE Identity_Internal IS identity_internal_size%TYPE;
TYPE Identity IS RECORD (Descriptor Identity_Internal);

identity_array_internal_size RAW(200);
SUBTYPE Identity_Array_Internal IS identity_array_internal_size%TYPE;
TYPE Identity_Array IS RECORD (
Descriptor_Array Identity_Array_Internal);
Subtypes SUBTYPE Crypto_Engine_Function IS POSITIVE;

SUBTYPE Crypto_Engine_State IS POSITIVE;

SUBTYPE Identity_Type IS POSITIVE;

SUBTYPE Cipher IS POSITIVE;

SUBTYPE Data_Unit_Format IS POSITIVE;
Related Topics
DBMS_CRYPTO


Oracle DBMS_I_INDEX_UTL Index Utility Rebuild

Oracle DBMS_I_INDEX_UTL
General
Note: For moving the OLAP catalog
Source | $ORACLE_HOME/rdbms/admin/prvtidxu.plb
First Available | 10.1
Dependencies
DBA_SCHEDULER_JOBS | DBMS_SCHEDULER | IDX_RB$JOBSEQ
DBMS_ASSERT | DBMS_SNAPSHOT | IND$
DBMS_EXPORT_EXTENSION | DBMS_SYSTEM | INDPART_PARAM$
DBMS_INDEX_UTL | DBMS_SYS_ERROR | OBJ$
DBMS_ISCHED | DUAL | PLITBLM
DBMS_JOB | GV$DB_PIPES | USER$
DBMS_ODCI | GV$INSTANCE | X$KSPPCV
DBMS_PIPE | GV$PARAMETER | X$KSPPI
Exceptions
Number Name
ORA-20001 Index <index_name> does not exist in schema <schema_name>.
or
User <schema_name> does not exist.
COLLECT_PARAMETERS
Undocumented dbms_i_index_utl.collect_parameters(
parameters OUT VARCHAR2 dbms_i_index_utl.parametername_array,
paramvals  OUT VARCHAR2 dbms_i_index_utl.parameterval_array,
events     OUT NUMBER   dbms_i_index_utl.number_array,
eventvals  OUT NUMBER   dbms_i_index_utl.number_array);
TBD
DROP_IDX_JOB
Undocumented | dbms_i_index_utl.drop_idx_job(jobname IN VARCHAR2);
TBD
FIX_QUOTES
Undocumented | dbms_i_index_utl.fix_quotes(instr IN VARCHAR2) RETURN VARCHAR2
-- do nothing

select dbms_i_index_utl.fix_quotes('UWCLASS.SERVERS') FROM dual;

select dbms_i_index_utl.fix_quotes('"UWCLASS.SERVERS"') FROM dual;
GET_DOM_IDX_PARAM_STR (new 11g)
Undocumented dbms_i_index_utl.get_dom_idx_param_str(
index_name     IN VARCHAR2,
idx_owner_name IN VARCHAR2,
cname          IN VARCHAR2)
RETURN VARCHAR2
TBD
GET_REBUILD_COMMAND

Constructs the command to rebuild an index 		dbms_i_index_utl.get_rebuild_command(
ctype  IN VARCHAR2,  -- G=global, L=local
iowner IN VARCHAR2,
iname  IN VARCHAR2,
cname  IN VARCHAR2)
RETURN VARCHAR2
set serveroutput on

DECLARE
 oput VARCHAR2(1000);
BEGIN
  oput := dbms_i_index_utl.get_rebuild_command('G', 'UWCLASS', 'PK_SERVER', 'PK_SERVER');

  dbms_output.put_line(oput);
END;
/

DECLARE
 oput VARCHAR2(1000);
BEGIN
  oput := dbms_i_index_utl.get_rebuild_command('L', 'UWCLASS', 'PK_SERVER', NULL);

  dbms_output.put_line(oput);
END;
/
IS_DOMAIN_INDEX (new 11g)
Returns the object_id if the object is a domain index: Otherwise returns 0. dbms_i_index_utl.is_domain_index(
index_name     IN VARCHAR2,
idx_owner_name IN VARCHAR2)
RETURN BINARY_INTEGER
conn / as sysdba

SELECT index_name, index_type
FROM dba_indexes
WHERE owner = 'SH'

SELECT dbms_i_index_utl.is_domain_index('COST_PROD_BIX', 'SH')
FROM dual;

SELECT dbms_i_index_utl.is_domain_index('SUP_TEXT_IDX', 'SH')
FROM dual;
I_BUILD_INDEXES
Undocumented dbms_i_index_utl.i_build_indexes(
ctypes         IN     CHAR     dbms_i_index_utl.symbol_array,
iowners        IN     VARCHAR2 dbms_i_index_utl.name_array,
inames         IN     VARCHAR2 dbms_i_index_utl.name_array,
cnames         IN     VARCHAR2 dbms_i_index_utl.name_array,
degrees        IN     NUMBER   dbms_i_index_utl.number_array,
rowcnts        IN     NUMBER   dbms_i_index_utl.number_array,
concurrent     IN     BOOLEAN,
cont_after_err IN     BOOLEAN,
maxdop         IN     BINARY_INTEGER,
num_errors     IN OUT BINARY_INTEGER);
TBD
PACK_PARAMETERS
Undocumented dbms_i_index_utl.pack_parameters(
env_pipe   IN VARCHAR2 PL/SQL TABLE,
parameters IN VARCHAR2 dbms_i_index_utl.parametername_array,
paramvals  IN VARCHAR2 dbms_i_index_utl.parametername_array,
events     IN NUMBER   dbms_i_index_utl.number_array,
eventvals  IN NUMBER   dbms_i_index_utl.number_array);
TBD
REBUILD_INDEX
Undocumented dbms_i_index_utl.rebuild_index(
pipe   IN VARCHAR2,
jobno  IN BINARY_INTEGER,
ctype  IN VARCHAR2,
iowner IN VARCHAR2,
iname  IN VARCHAR2,
cname  IN VARCHAR2,
mvidx  IN BINARY_INTEGER,
rscs   IN BINARY_INTEGER);
TBD
REBUILD_INDEX_LIST
Undocumented dbms_i_index_utl.rebuild_index_list(
inpipe         IN VARCHAR2,
jobid          IN BINARY_INTEGER,
outpipe        IN VARCHAR2,
cont_after_err IN BINARY_INTEGER,
degree         IN BINARY_INTEGER);
TBD
REMOVE_PARAMETER_PIPES
Undocumented | dbms_i_index_utl.remove_parameter_pipes(pipe IN VARCHAR2);
TBD
SUBMIT_IDX_REBUILD_JOB
Undocumented dbms_i_index_utl.submit_idx_rebuild_job(
sched_class   IN  VARCHAR2,
jobname       IN  VARCHAR2,
jobaction     IN  VARCHAR2,
jobcomment    IN  VARCHAR2,
this_inst     IN  BINARY_INTEGER,
jobno         OUT BINARY_INTEGER,
submit_as_job IN  BOOLEAN);
TBD
UNPACK_PARAMETERS
Undocumented | dbms_i_index_utl.unpack_parameters(env_pipe IN VARCHAR2);
TBD
VERIFY_IDX_COMP
Undocumented dbms_i_index_utl.verify_idx_comp(
comp_name      IN VARCHAR2,
idx_name       IN VARCHAR2,
idx_owner_name IN VARCHAR2)
RETURN BINARY_INTEGER;
TBD
VERIFY_INDEX
Returns the OBJECT_ID for an index or ORA-20001 if it does not exist dbms_i_index_utl.verify_index(
index_name     IN VARCHAR2,
idx_owner_name IN VARCHAR2)
RETURN BINARY_INTEGER;
SELECT object_id
FROM dba_objects
WHERE object_name = 'PK_SERVERS'
AND object_type = 'INDEX';

SELECT dbms_i_index_utl.verify_index('PK_SERVERS', 'UWCLASS')
FROM dual;

SELECT dbms_i_index_utl.verify_index('KP_SERVERS', 'UWCLASS')
FROM dual;
VERIFY_OWNER
Returns the USER_ID for an schema owner or ORA-20001 if it does not exist dbms_i_index_utl.verify_owner(owner_name IN VARCHAR2)
RETURN BINARY_INTEGER;
SELECT user_id
FROM dba_users
WHERE username = 'UWCLASS';

SELECT dbms_i_index_utl.verify_owner('UWCLASS') FROM dual;

SELECT dbms_i_index_utl.verify_owner('UWCLASZ') FROM dual;
VERIFY_TABLE
Returns the OBJECT_ID for a table or ORA-20001 if it does not exist dbms_i_index_utl.verify_table(
table_name  IN VARCHAR2,
table_owner IN VARCHAR2)
RETURN BINARY_INTEGER;
SELECT object_id
FROM dba_objects
WHERE object_name = 'SERVERS'
AND object_type = 'TABLE';

SELECT dbms_i_index_utl.verify_table('SERVERS', 'UWCLASS')
FROM dual;

SELECT dbms_i_index_utl.verify_table('SERVERZ', 'UWCLASS')
FROM dual;
VERIFY_TAB_COMP

Undocumented 		dbms_i_index_utl.verify_tab_comp(
comp_name      IN VARCHAR2,
table_name     IN VARCHAR2,
tab_owner_name IN VARCHAR2)
RETURN BINARY_INTEGER;
SELECT comp_name FROM dba_registry ORDER BY 1;

COMP_NAME
----------------------------------
JServer JAVA Virtual Machine
OLAP Analytic Workspace
OLAP Catalog
Oracle Data Mining
Oracle Database Catalog Views
Oracle Database Java Packages
Oracle Database Packages and Types
Oracle Enterprise Manager
Oracle Expression Filter
Oracle OLAP API
Oracle Rules Manager
Oracle Text
Oracle Workspace Manager
Oracle XDK
Oracle XML Database
Oracle interMedia
Spatial

SELECT dbms_i_index_utl.verify_tab_comp('OLAP Catalog', 'SERVERS', 'UWCLASS')
FROM dual;

ERROR at line 1:
ORA-20001: Component "OLAP Catalog" does not exist in table "SERVERS" in schema "UWCLASS".
ORA-06512: at "SYS.DBMS_I_INDEX_UTL", line 779

Related Topics

DBMS_INDEX_UTL

DBMS_PCLXUTIL

Indexes


Oracle DBMS_INDEX_UTL Index Rebuild Online

Oracle DBMS_INDEX_UTL
General Information
Source | {ORACLE_HOME}/rdbms/admin/dbmsidxu.sql
First Available | 10.1
Dependencies
DBMS_I_INDEX_UTL | DBMS_SYSTEM | PLITBLM
DBMS_SNAPSHOT | DBMS_UTILITY |
BUILD_INDEXES

Provides an interface for finding and concurrently, and in parallel, rebuild all the index components (including
entire indexes, index partitions, and index subpartitions) for a list of indexes

Overload 1 		dbms_index_utl.build_indexes (
list           IN  VARCHAR2 DEFAULT NULL,
just_unusable  IN  BOOLEAN  DEFAULT TRUE,
locality       IN  VARCHAR2 DEFAULT 'ALL',
concurrent     IN  BOOLEAN  DEFAULT TRUE,
cont_after_err IN  BOOLEAN  DEFAULT FALSE,
max_slaves     IN  INT      DEFAULT NULL,
num_errors     OUT NOCOPY PLS_INTEGER);
SELECT index_name
FROM user_indexes;

set serveroutput on

DECLARE
 x PLS_INTEGER;
BEGIN
  dbms_index_utl.build_indexes('UWCLASS.PK_SERV_INST,
  UWCLASS.IX_SERV_INST', FALSE, 'ALL', FALSE, FALSE, 2, x);

  dbms_output.put_line('Failed to rebuild: ' || TO_CHAR(x));
END;
/

Overload 2 		dbms_index_utl.build_indexes (
list           IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL,);
SELECT index_name
FROM user_indexes;

exec dbms_index_utl.build_indexes('UWCLASS.PK_SERV_INST,
     UWCLASS.IX_SERV_INST', FALSE, 'ALL', FALSE, FALSE, 2);
BUILD_INDEX_COMPONENTS
Provide an interface for finding and concurrently, and in parallel, rebuilding a given list of index components (partitions and subparts). This will not rebuild entire indexes

Overload 1 		dbms_index_utl.build_index_components (
list           IN  VARCHAR2 DEFAULT NULL, -- <owner>.<index>.<comp>)
just_unusable  IN  BOOLEAN  DEFAULT TRUE,
locality       IN  VARCHAR2 DEFAULT 'ALL',
concurrent     IN  BOOLEAN  DEFAULT TRUE,
cont_after_err IN  BOOLEAN  DEFAULT FALSE,
max_slaves     IN  INT      DEFAULT NULL,
num_errors     OUT NOCOPY PLS_INTEGER);
TBD
Overload 2 dbms_index_utl.build_index_components (
list           IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL);
TBD
BUILD_SCHEMA_INDEXES

Provides an interface for finding and concurrently and rebuilding, in parallel, all the index components (including entire indexes, index partitions, and index subpartitions) for a list of schemas

Overload 1 		dbms_index_utl.build_schema_indexes (
list           IN  VARCHAR2 DEFAULT NULL,  -- comma delimited schemas
just_unusable  IN  BOOLEAN  DEFAULT TRUE,  -- unusable only or all
locality       IN  VARCHAR2 DEFAULT 'ALL', -- GLOBAL | LOCAL | ALL
concurrent     IN  BOOLEAN  DEFAULT TRUE,  -- if TRUE uses Jobs
cont_after_err IN  BOOLEAN  DEFAULT FALSE, -- TRUE | FALSE
max_slaves     IN  INT      DEFAULT NULL,  -- degree of parallelism
num_errors     OUT NOCOPY PLS_INTEGER);    -- number of failures
set serveroutput on

DECLARE
 x PLS_INTEGER;
BEGIN
  dbms_index_utl.build_schema_indexes('UWCLASS', FALSE, 'ALL', FALSE,
  FALSE, 2, x);

  dbms_output.put_line('Failed to rebuild: ' || TO_CHAR(x));
END;
/

Overload 2 		dbms_index_utl.build_schema_indexes (
list           IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL);
exec dbms_index_utl.build_schema_indexes('UWCLASS', FALSE, 'ALL', FALSE, FALSE, 2);
BUILD_TABLE_COMPONENT_INDEXES
Provide an interface for finding and concurrently, and in parallel rebuilding all the index components (including index partitions, and index subpartitions) for a given list of table components

Overload 1 		dbms_index_utl.build_table_component_indexes (
list           IN  VARCHAR2 DEFAULT NULL,
just_unusable  IN  BOOLEAN  DEFAULT TRUE,
locality       IN  VARCHAR2 DEFAULT 'ALL',
concurrent     IN  BOOLEAN  DEFAULT TRUE,
cont_after_err IN  BOOLEAN  DEFAULT FALSE,
max_slaves     IN  INT      DEFAULT NULL,
num_errors     OUT NOCOPY PLS_INTEGER);
TBD

Overload 2 		dbms_index_utl.build_table_component_indexes (
list           IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL);
TBD
BUILD_TABLE_INDEXES

Provide an interface for finding and concurrently rebuilding, in parallel, all the index components (including
entire indexes, index partitions, and index subpartitions) for a list of tables

Overload 1 		dbms_index_utl.build_table_indexes (
list           IN  VARCHAR2 DEFAULT NULL,  -- list of tables
just_unusable  IN  BOOLEAN  DEFAULT TRUE,
locality       IN  VARCHAR2 DEFAULT 'ALL',
concurrent     IN  BOOLEAN  DEFAULT TRUE,
cont_after_err IN  BOOLEAN  DEFAULT FALSE,
max_slaves     IN  INT      DEFAULT NULL,
num_errors     OUT NOCOPY PLS_INTEGER);
set serveroutput on

DECLARE
 x PLS_INTEGER;
BEGIN
  dbms_index_utl.build_table_indexes ('UWCLASS.SERVERS,
  UWCLASS.AIRPLANES', FALSE, 'ALL', FALSE, FALSE, 2, x);

  dbms_output.put_line('Failed to rebuild: ' || TO_CHAR(x));
END;
/

Overload 2 		dbms_index_utl.build_table_indexes (
list           IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL);
exec dbms_index_utl.build_table_indexes ('UWCLASS.SERVERS,
     UWCLASS.AIRPLANES', FALSE, 'ALL', FALSE, FALSE, 2);
MULTI_LEVEL_BUILD
Provide an interface for finding and concurrently, and in parallel, rebuilding all the index components (including index partitions, and index subpartitions) for several lists of schema objects. This function has an advantage over others in that it provides the maximum amount of concurrency possible by removing serialization forced by making sequential calls to different rebuild functions

Overload 1 		dbms_index_utl.multi_level_build (
schema_list    IN  VARCHAR2 DEFAULT NULL,
table_list     IN  VARCHAR2 DEFAULT NULL,
index_list     IN  VARCHAR2 DEFAULT NULL,
idx_comp_list  IN  VARCHAR2 DEFAULT NULL,
tab_comp_list  IN  VARCHAR2 DEFAULT NULL,
just_unusable  IN  BOOLEAN  DEFAULT TRUE,
locality       IN  VARCHAR2 DEFAULT 'ALL',
concurrent     IN  BOOLEAN  DEFAULT TRUE,
cont_after_err IN  BOOLEAN  DEFAULT FALSE,
max_slaves     IN  INT      DEFAULT NULL,
num_errors     OUT NOCOPY PLS_INTEGER);
TBD

Overload 2 		dbms_index_utl.multi_level_build (
schema_list    IN VARCHAR2 DEFAULT NULL,
table_list     IN VARCHAR2 DEFAULT NULL,
index_list     IN VARCHAR2 DEFAULT NULL,
idx_comp_list  IN VARCHAR2 DEFAULT NULL,
tab_comp_list  IN VARCHAR2 DEFAULT NULL,
just_unusable  IN BOOLEAN  DEFAULT TRUE,
locality       IN VARCHAR2 DEFAULT 'ALL',
concurrent     IN BOOLEAN  DEFAULT TRUE,
cont_after_err IN BOOLEAN  DEFAULT FALSE,
max_slaves     IN INT      DEFAULT NULL);
TBD
Related Topics
DBMS_I_INDEX_UTL
DBMS_PCLXUTIL
Indexes


Oracle DBMS_LOB BLOB CLOB

Oracle DBMS_LOB
General Information
Source | {ORACLE_HOME}/rdbms/admin/dbmslob.sql
First Available | 8.0

Constants
Name | Data Type | Value
call | PLS_INTEGER | 12
default_csid | INTEGER | 0
default_lang_ctx | INTEGER | 0
file_readonly | BINARY_INTEGER | 0
lob_readonly | BINARY_INTEGER | 0
lob_readwrite | BINARY_INTEGER | 1
lobmaxsize | INTEGER | 18446744073709551615
no_warning | INTEGER | 0
session | PLS_INTEGER | 10
transaction | PLS_INTEGER | 11
warn_inconvertible_char | INTEGER | 1
Option Types
opt_compress | PLS_INTEGER | 1
opt_encrypt | PLS_INTEGER | 2
opt_deduplicate | PLS_INTEGER | 4
Option Values
compress_off | PLS_INTEGER | 0
compress_on | PLS_INTEGER | 1
encrypt_off | PLS_INTEGER | 0
encrypt_on | PLS_INTEGER | 2
deduplicate_off | PLS_INTEGER | 0
deduplicate_on | PLS_INTEGER | 4

Data Types 		TYPE blob_deduplicate_region IS RECORD (
lob_offset         INTEGER,
len                INTEGER,
primary_lob        BLOB,
primary_lob_offset NUMBER,
mime_type          VARCHAR2(80));

TYPE blob_deduplicate_region_tab
IS TABLE OF blob_deduplicate_region
INDEX BY PLS_INTEGER;

TYPE clob_deduplicate_region IS RECORD (
lob_offset         INTEGER,
len                INTEGER,
primary_lob        CLOB,
primary_lob_offset NUMBER,
mime_type          VARCHAR2(80));

TYPE clob_deduplicate_region_tab
IS TABLE OF clob_deduplicate_region
INDEX BY PLS_INTEGER;

Dependencies 		SELECT name
FROM dba_dependencies
WHERE referenced_name = 'DBMS_LOB'
UNION
SELECT referenced_name
FROM dba_dependencies
WHERE name = 'DBMS_LOB';

Exceptions
Error Code | Reason
ORA-21560 | The argument is expecting a non-null, valid value but the argument value passed in is null, invalid, or out of range
ORA-22285 | The directory leading to the file does not exist
ORA-22286 | user does not have the necessary access privileges on the directory alias and/or file
ORA-22287 | directory alias is not valid
ORA-22288 | file operation failed
ORA-22288 | The file is not open for the required operation
ORA-22290 | open files has reached the maximum limit
ORA-22925 | operation exceeds maximum lob size
Object Privileges | Execute is granted to PUBLIC
APPEND

Appends the contents of a source internal LOB to a destination LOB

Overload 1 		dbms_lob.append(
dest_lob IN OUT NOCOPY BLOB,
src_lob  IN            BLOB);
CREATE OR REPLACE PROCEDURE Example_1a IS
 dest_lob BLOB;
 src_lob  BLOB;
BEGIN
  -- get the LOB locators
  -- note that the FOR UPDATE clause locks the row
   SELECT b_lob INTO dest_lob
  FROM lob_table
  WHERE key_value = 12
  FOR UPDATE;

  SELECT b_lob INTO src_lob
  FROM lob_table
  WHERE key_value = 21;

  dbms_lob.append(dest_lob, src_lob);
  COMMIT;
END;

Overload 2 		dbms_lob.append(
dest_lob IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src_lob  IN            CLOB CHARACTER SET dest_lob%CHARSET);
CREATE OR REPLACE PROCEDURE Example_1b IS
 dest_lob, src_lob BLOB;
BEGIN
  -- get the LOB locators
  SELECT b_lob INTO dest_lob
  FROM lob_table
  WHERE key_value = 12
  FOR UPDATE;

  SELECT b_lob INTO src_lob
  FROM lob_table
  WHERE key_value = 12;

  dbms_lob.append(dest_lob, src_lob);
  COMMIT;
END;
/
CLOSE
Closes a previously opened internal or external LOB

Overload 1 		dbms_lob.close(lob_loc IN OUT NOCOPY BLOB);
TBD
Overload 2 | dbms_lob.close(lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS);
See CREATETEMPORARY demo
Overload 3 | dbms_lob.close(file_loc IN OUT NOCOPY BFILE);
TBD
COMPARE

Compares two entire LOBs or parts of two LOBs

Overload 1 		dbms_lob.compare(
lob_1    IN BLOB,
lob_2    IN BLOB,
amount   IN INTEGER := 18446744073709551615,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
TBD

Overload 2 		dbms_lob.compare(
lob_1    IN CLOB CHARACTER SET ANY_CS,
lob_2    IN CLOB CHARACTER SET lob_1%CHARSET,
amount   IN INTEGER := 18446744073709551615,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
TBD

Overload 3 		dbms_lob.compare(
file_1   IN BFILE,
file_2   IN BFILE,
amount   IN INTEGER,
offset_1 IN INTEGER := 1,
offset_2 IN INTEGER := 1)
RETURN INTEGER;
TBD
CONVERTOBLOB

Reads character data from a source CLOB or NCLOB instance, converts the character data to the specified character, writes the converted data to a destination BLOB instance in binary format, and returns the new offsets 		dbms_lob.convertToBlob(
dest_lob     IN OUT NOCOPY BLOB,
src_clob     IN     CLOB CHARACTER SET ANY_CS,
amount       IN     INTEGER,
dest_offset  IN OUT INTEGER,
src_offset   IN OUT INTEGER,
blob_csid    IN     NUMBER,
lang_context IN OUT INTEGER,
warning         OUT INTEGER);
TBD
CONVERTOCLOB

Takes a source BLOB instance, converts the binary data in the source instance to character data using the specified character, writes the character data to a destination CLOB or NCLOB instance, and returns the new offsets 		dbms_lob.convertToClob(
dest_lob     IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src_blob     IN     BLOB,
amount       IN     INTEGER,
dest_offset  IN OUT INTEGER,
src_offset   IN OUT INTEGER,
blob_csid    IN     NUMBER,
lang_context IN OUT INTEGER,
warning         OUT INTEGER);
TBD
COPY

Copies all, or part, of the source LOB to the destination LOB

Overload 1 		dbms_lob.copy(
dest_lob    IN OUT NOCOPY BLOB,
src_lob     IN BLOB,
amount      IN INTEGER,
dest_offset IN INTEGER := 1,
src_offset  IN INTEGER := 1);
TBD

Overload 2 		dbms_lob.copy(
dest_lob    IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src_lob     IN CLOB CHARACTER SET dest_lob%CHARSET,
amount      IN INTEGER,
dest_offset IN INTEGER := 1,
src_offset  IN INTEGER := 1);
TBD
CREATETEMPORARY

Creates a temporary BLOB or CLOB and its corresponding index in the user's default temporary tablespace

Overload 1 		dbms_lob.createtemporary(
lob_loc IN OUT NOCOPY BLOB,
cache   IN BOOLEAN,
dur     IN PLS_INTEGER := 10);
DECLARE
 clobvar CLOB := EMPTY_CLOB;
 len     BINARY_INTEGER;
 x       VARCHAR2(80);
BEGIN
  dbms_lob.createtemporary(clobvar, TRUE);
  dbms_lob.open(clobvar, dbms_lob.lob_readwrite);
  x := 'before line break' || CHR(10) || 'after line break';
  len := length(x);
  dbms_lob.writeappend(clobvar, len, x);
  dbms_lob.close(clobvar);
END;
/

Overload 2 		dbms_lob.createtemporary(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
cache   IN            BOOLEAN,
dur     IN            PLS_INTEGER := 10);
TBD
EMPTY_BLOB

Null BLOB 		dbms_lob.empty_blob();
CREATE TABLE ebdemo (
fid   NUMBER(3),
iclob BLOB);

INSERT INTO ebdemo
(fid, iblob)
VALUES
(1, EMPTY_BLOB());
EMPTY_CLOB

Null CLOB 		dbms_lob.empty_clob();
CREATE TABLE ecdemo (
fid   NUMBER(3),
iclob CLOB);

INSERT INTO ecdemo
(fid, iclob)
VALUES
(1, EMPTY_CLOB());
ERASE
Erases all or part of a LOB

Overload 1 		dbms_lob.erase(
lob_loc IN OUT NOCOPY BLOB,
amount  IN OUT NOCOPY INTEGER,
offset  IN INTEGER := 1);
TBD
Overload 2 dbms_lob.erase(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount  IN OUT NOCOPY INTEGER,
offset  IN INTEGER := 1);
TBD
FILECLOSE
Closes a file opened with dbms_lob.file_open | dbms_lob.fileclose(file_loc IN OUT NOCOPY BFILE);
exec dbms_lob.fileclose(src_file);
FILECLOSEALL
Closes all files opened with dbms_lob.file_open | dbms_lob.filecloseall;
exec dbms_lob.fileclose;
FILEEXISTS
Determine whether a file exists | dbms_lob.fileexists(file_loc IN BFILE) RETURN INTEGER;
TBD
FILEGETNAME
Returns the source filename and directory given a BFILE dbms_lob.filegetname(
file_loc  IN  BFILE,
dir_alias OUT VARCHAR2,
filename  OUT VARCHAR2);
TBD
FILEISOPEN
Checks if the file was opened using the input BFILE locators | dbms_lob.fileisopen(file_loc IN BFILE) RETURN INTEGER;
TBD
FILEOPEN
Open a file for reading dbms_lob.fileopen(
file_loc  IN OUT NOCOPY BFILE,
open_mode IN            BINARY_INTEGER := file_readonly);
exec dbms_lob.fileopen(src_file, dbms_lob.file_readonly);
FRAGMENT_DELETE
Deletes the data at the given offset for the given length from the LOB

Overload 1 		dbms_lob.fragment_delete(
lob_loc IN OUT NOCOPY BLOB,
amount  IN     INTEGER,
offset  IN     INTEGER);
TBD
Overload 2 dbms_lob.fragment_delete(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount  IN     INTEGER,
offset  IN     INTEGER);
TBD
FRAGMENT_INSERT
Inserts the given data (limited to 32K) into the LOB at the given offset

Overload 1 		dbms_lob.fragment_insert(
lob_loc IN OUT NOCOPY BLOB,
amount  IN     INTEGER,
offset  IN     INTEGER,
buffer  IN     RAW);
TBD
Overload 2 dbms_lob.fragment_insert(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount  IN     INTEGER,
offset  IN     INTEGER,
buffer  IN     VARCHAR2 CHARACTER SET lob_loc%CHARSET);
TBD
FRAGMENT_MOVE
Moves the amount of bytes (BLOB) or characters (CLOB/NCLOB) from the given offset to the new offset specified

Overload 1 		dbms_lob.fragment_move(
lob_loc     IN OUT NOCOPY BLOB,
amount      IN     INTEGER,
src_offset  IN     INTEGER,
dest_offset IN     INTEGER);
TBD
Overload 2 dbms_lob.fragment_move(
lob_loc     IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount      IN     INTEGER,
src_offset  IN     INTEGER,
dest_offset IN     INTEGER);
TBD
FRAGMENT_REPLACE
Replaces the data at the given offset with the given data (not to exceed 32k)

Overload 1 		dbms_lob.fragment_replace(
lob_loc    IN OUT NOCOPY BLOB,
old_amount IN     INTEGER,
new_amount IN     INTEGER,
offset     IN     INTEGER,
buffer     IN     RAW);
TBD
Overload 2 dbms_lob.fragment_replace(
lob_loc    IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
old_amount IN INTEGER,
new_amount IN INTEGER,
offset     IN INTEGER,
buffer     IN VARCHAR2 CHARACTER SET lob_loc%CHARSET);
TBD
FREETEMPORARY

Frees the temporary BLOB or CLOB in the default temporary tablespace

Overload 1 		dbms_lob.freetemporary(lob_loc IN OUT NOCOPY BLOB);
conn pm/pm

desc print_media

SELECT ad_sourcetext
FROM print_media
WHERE product_id = 2056;

set long 100000

SELECT ad_sourcetext
FROM print_media
WHERE product_id = 2056;

set serveroutput on

DECLARE
 clobvar CLOB;
BEGIN
  SELECT ad_sourcetext
  INTO clobvar
  FROM print_media
  WHERE product_id = 2056;

  dbms_output.put_line('1: ' || clobvar);

  dbms_lob.freetemporary(clobvar);

  dbms_output.put_line('2: ' || clobvar);
END;
/
Overload 2 dbm_lob.freetemporary(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS);
TBD
GETCHUNKSIZE
Returns the amount of space used in the LOB chunk to store the LOB value

Overload 1 		dbms_lob.getchunksize(lob_loc IN BLOB) RETURN INTEGER;
TBD
Overload 2 dbms_lob.getchunksize(lob_loc IN CLOB CHARACTER SET ANY_CS)
RETURN INTEGER;
TBD
GETLENGTH

Gets the length of the LOB value

Overload 1 		dbms_lob.getlength(lob_loc IN BLOB) RETURN INTEGER;
conn pm/pm

desc print_media

SELECT dbms_lob.getlength(ad_photo)
FROM print_media;

Overload 2 		dbms_lob.getlength(lob_loc IN CLOB CHARACTER SET ANY_CS)
RETURN INTEGER;
conn pm/pm

desc print_media

SELECT dbms_lob.getlength(ad_sourcetext)
FROM print_media;

Overload 3 		dbms_lob.getlength(file_loc IN BFILE) RETURN INTEGER;
DECLARE
 src_file BFILE;
 dst_file BLOB;
 lgh_file BINARY_INTEGER;
BEGIN
  src_file := bfilename('CTEMP', 'myfile.txt');
  lgh_file := dbms_lob.getlength(src_file);
END;
/
GET_DEDUPLICATE_REGIONS (new in 11g)
Undocumented

Overload 1 		dbms_lob.get_deduplicate_regions(
lob_loc      IN     BLOB,
region_table IN OUT NOCOPY BLOB_DEDUPLICATE_REGION_TAB);
TBD
Overload 2 dbms_lob.get_deduplicate_regions(
lob_loc      IN     CLOB CHARACTER SET ANY_CS,
region_table IN OUT NOCOPY CLOB_DEDUPLICATE_REGION_TAB);
TBD
GETOPTIONS

Obtains settings corresponding to the option_types field for a particular LOB

Overload 1 		dbms_lob.getoptions(
lob_loc      IN BLOB,
option_types IN PLS_INTEGER)
RETURN PLS_INTEGER;
See SECUREFILES demo
Overload 2 dbms_lob.getoptions(
lob_loc      IN CLOB CHARACTER SET ANY_CS,
option_types IN PLS_INTEGER)
RETURN PLS_INTEGER;
TBD
GET_STORAGE_LIMIT
Returns the storage limit for LOBs in your database configuration

Overload 1 		dbms_lob.get_storage_limit(
lob_loc IN CLOB CHARACTER SET ANY_CS) RETURN INTEGER;
conn pm/pm

desc print_media

SELECT dbms_lob.get_storage_limit(ad_sourcetext)
FROM print_media;
Overload 2 | dbms_lob.get_storage_limit(lob_loc IN BLOB) RETURN INTEGER;
conn pm/pm

desc print_media

SELECT dbms_lob.get_storage_limit(ad_photo)
FROM print_media;
INSTR

Returns the matching position of the nth occurrence of the pattern in the LOB

Overload 1 		dbms_lob.instr(
lob_loc IN BLOB,
pattern IN RAW,
offset  IN INTEGER := 1,
nth     IN INTEGER := 1) RETURN INTEGER;
TBD

Overload 2 		dbms_lob.instr(
lob_loc IN CLOB CHARACTER SET ANY_CS,
pattern IN VARCHAR2 CHARACTER SET lob_loc%CHARSET,
offset  IN INTEGER := 1,
nth     IN INTEGER := 1) RETURN INTEGER;
conn pm/pm

SELECT dbms_lob.getlength(ad_sourcetext), dbms_lob.instr(ad_sourcetext, 'A')
FROM print_media;

SELECT dbms_lob.getlength(ad_sourcetext), dbms_lob.instr(ad_sourcetext, 'E')
FROM print_media;

Overload 3 		dbms_lob.instr(
file_loc IN BFILE,
pattern  IN RAW,
offset   IN INTEGER := 1,
nth IN   INTEGER := 1) RETURN INTEGER;
TBD
ISOPEN
Checks to see if the LOB was already opened using the input locator

Overload 1 		dbms_lob.isopen(lob_loc IN BLOB) RETURN INTEGER;
TBD
Overload 2 dbms_lob.isopen(lob_loc IN CLOB CHARACTER SET ANY_CS)
RETURN INTEGER;
TBD
Overload 3 | dbms_lob.isopen(file_loc IN BFILE) RETURN INTEGER;
TBD
ISSECUREFILE (new in 11g)
Returns TRUE is a LOB has been stored in an encrypted SECUREFILE

Overload 1 		dbms_lob.issecurefile(lob_loc IN BLOB) RETURN BOOLEAN;
See SECUREFILES demo
Overload 2 dbms_lob.issecurefile(lob_loc IN CLOB CHARACTER SET ANY_CS)
RETURN BOOLEAN;
TBD
ISTEMPORARY
Checks if the locator is pointing to a temporary LOB

Overload 1 		dbms_lob.istemporary(lob_loc IN BLOB) RETURN INTEGER;
TBD
Overload 2 dbms_lob.istemporary(lob_loc IN CLOB CHARACTER SET ANY_CS)
RETURN INTEGER;
TBD
LOADBLOBFROMFILE

Loads BFILE data into an internal BLOB 		dbm_lob.loadblobfromfile(
dest_lob    IN OUT NOCOPY BLOB,
src_bfile   IN     BFILE,
amount      IN     INTEGER,
dest_offset IN OUT INTEGER,
src_offset  IN OUT INTEGER);
TBD
LOADCLOBFROMFILE

Loads BFILE data into an internal CLOB 		dbm_lob.loadclobfromfile(
dest_lob     IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src_bfile    IN     BFILE,
amount       IN     INTEGER,
dest_offset  IN OUT INTEGER,
src_offset   IN OUT INTEGER,
bfile_csid   IN     NUMBER,
lang_context IN OUT INTEGER,
warning         OUT INTEGER);
TBD
LOADFROMFILE
Loads BFILE data into an internal LOB

Overload 1 		dbms_lob.loadfromfile(
dest_lob    IN OUT NOCOPY BLOB,
src_lob     IN     BFILE,
amount      IN     INTEGER,
dest_offset IN     INTEGER := 1,
src_offset  IN     INTEGER := 1);
exec dbms_lob.loadfromfile(dst_file, src_file, lgh_file);
Overload 2 dbms_lob.loadfromfile(
dest_lob    IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src_lob     IN     BFILE,
amount      IN     INTEGER,
dest_offset IN     INTEGER := 1,
src_offset  IN     INTEGER := 1);
TBD
OPEN
Opens a LOB (internal, external, or temporary) in the indicated mode

Overload 1 		dbms_lob.open(
lob_loc   IN OUT NOCOPY BLOB,
open_mode IN     BINARY_INTEGER);
TBD
Overload 2 dbms_lob.open(
lob_loc   IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
open_mode IN     BINARY_INTEGER);
See CREATETEMPORARY demo
Overload 3 dbms_lob.open(
file_loc  IN OUT NOCOPY BFILE,
open_mode IN     BINARY_INTEGER := file_readonly);
TBD
READ
Reads data from the LOB starting at the specified offset

Overload 1 		dbms_lob.read(
lob_loc IN     BLOB,
amount  IN OUT NOCOPY INTEGER,
offset  IN     INTEGER,
buffer     OUT RAW);
TBD
Overload 2 dbms_lob.read(
lob_loc IN     CLOB CHARACTER SET ANY_CS,
amount  IN OUT NOCOPY INTEGER,
offset  IN     INTEGER,
buffer     OUT VARCHAR2 CHARACTER SET lob_loc%CHARSET);
TBD
Overload 3 dbms_lob.read(
file_loc IN BFILE,
amount   IN OUT NOCOPY INTEGER,
offset   IN     INTEGER,
buffer      OUT RAW);
TBD
SETOPTIONS

Enables CSCE features on a per-LOB basis, overriding the default LOB column settings

Overload 1 		dbms_lob.setoptions(
lob_loc      IN OUT NOCOPY BLOB,
option_types IN     PLS_INTEGER,
options      IN     PLS_INTEGER);

Option Types
opt_compress | 1
opt_encrypt | 2
opt_deduplicate | 4

Options
compress_off | 0
compress_on | 1
encrypt_off | 0
encrypt on | 2
deduplicate_off | 0
deduplicate_on | 4
TBD
Overload 2 dbms_lob.setoptions(
lob_loc      IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
option_types IN     PLS_INTEGER,
options      IN     PLS_INTEGER);
TBD
SUBSTR
Returns part of the LOB value starting at the specified offset

Overload 1 		dbms_lob.substr(
lob_loc IN BLOB,
amount  IN INTEGER := 32767,
offset  IN INTEGER := 1)
RETURN RAW;
TBD
Overload 2 dbms_lob.substr(
lob_loc IN CLOB CHARACTER SET ANY_CS,
amount  IN INTEGER := 32767,
offset  IN INTEGER := 1)
RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;
TBD
Overload 3 dbms_lob.substr(
file_loc IN BFILE,
amount   IN INTEGER := 32767,
offset   IN INTEGER := 1)
RETURN RAW;
TBD
TRIM
Trims the LOB value to the specified shorter length

Overload 1 		dbms_lob.trim(lob_loc IN OUT NOCOPY BLOB, newlen IN INTEGER);
TBD
Overload 2 dbms_lob.trim(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
newlen  IN     INTEGER);
TBD
WRITE
Writes data to the LOB from a specified offset

Overload 1 		dbm_lob.write(
lob_loc IN OUT NOCOPY BLOB,
amount  IN     INTEGER,
offset  IN     INTEGER,
buffer  IN     RAW);
TBD
Overload 2 dbm_lob.write(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount  IN     INTEGER,
offset  IN     INTEGER,
buffer  IN     VARCHAR2 CHARACTER SET lob_loc%CHARSET);
TBD
WRITEAPPEND
Writes a buffer to the end of a LOB

Overload 1 		dbm_lob.writeappend(
lob_loc IN OUT NOCOPY BLOB,
amount  IN     INTEGER,
buffer  IN     RAW);
TBD

Overload 2 		dbm_lob.writeappend(
lob_loc IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
amount  IN     INTEGER,
buffer  IN     VARCHAR2 CHARACTER SET lob_loc%CHARSET);
CREATE TABLE book (
bookid NUMBER(5),
title VARCHAR2(50),
description VARCHAR2(100));

INSERT INTO book
VALUES
(1, '11g Inovations', 'New Features in Oracle 11g');

CREATE TABLE author (
authorid NUMBER(5),
author_name VARCHAR2(60));

INSERT INTO author
VALUES
(1, 'Daniel Morgan');

CREATE TABLE book_author_ie (
bookid NUMBER(5),
authorid NUMBER(5));

INSERT INTO book_author_ie
SELECT bookid, authorid
FROM book, author;

CREATE OR REPLACE PROCEDURE xml_gen(cvar IN OUT NOCOPY CLOB) AS
 CURSOR c IS
 SELECT b.title, b.description, a.author_name
 FROM book b, author a, book_author_ie ie
 WHERE b.bookid = ie.bookid
 AND a.authorid = ie.authorid;
BEGIN
  FOR r IN c LOOP
    dbms_lob.writeappend(cvar, 19, '<root><book><title>');
    dbms_lob.writeappend(cvar, length(r.title), r.title);
    dbms_lob.writeappend(cvar, 14, '</title><desc>');
    dbms_lob.writeappend(cvar, length(r.description), r.description);
    dbms_lob.writeappend(cvar, 27, '</desc></book><author_name>');
    dbms_lob.writeappend(cvar, length(r.author_name), r.author_name);
    dbms_lob.writeappend(cvar, 21, '</author_name></root>');
  END LOOP;
END xml_gen;
/

set serveroutput on

DECLARE
 cvar CLOB := ' ';
BEGIN
  xml_gen(cvar);
  dbms_output.put_line(cvar);
END;
/
DBMS_LOB Demos

Blob Load Demo 		/*
define the directory inside Oracle when logged on as SYS
create or replace directory ctemp as 'c:\temp\';

grant read on the directory to the Staging schema
grant read on directory ctemp to staging;
*/

-- the storage table for the image file
CREATE TABLE pdm (
dname  VARCHAR2(30),  -- directory name
sname  VARCHAR2(30),  -- subdirectory name
fname  VARCHAR2(30),  -- file name
iblob  BLOB);         -- image file
-- create the procedure to load the file
CREATE OR REPLACE PROCEDURE load_file (
 pdname VARCHAR2,
 psname VARCHAR2,
 pfname VARCHAR2) IS

 src_file BFILE;
 dst_file BLOB;
 lgh_file BINARY_INTEGER;
BEGIN
  src_file := bfilename('CTEMP', pfname);

  -- insert a NULL record to lock
  INSERT INTO pdm
  (dname, sname, fname, iblob)
  VALUES
  (pdname, psname, pfname, EMPTY_BLOB())
  RETURNING iblob INTO dst_file;

  -- lock record
  SELECT iblob
  INTO dst_file
  FROM pdm
  WHERE dname = pdname
  AND sname = psname
  AND fname = pfname
  FOR UPDATE;

  -- open the file
  dbms_lob.fileopen(src_file, dbms_lob.file_readonly);

  -- determine length
  lgh_file := dbms_lob.getlength(src_file);

  -- read the file
  dbms_lob.loadfromfile(dst_file, src_file, lgh_file);

  -- update the blob field
  UPDATE pdm
  SET iblob = dst_file
  WHERE dname = pdname
  AND sname = psname
  AND fname = pfname;

  -- close file
  dbms_lob.fileclose(src_file);
END load_file;
/

Save BLOB to File Demo 		How to save a BLOB to a file on disk in PL/SQL
From: Thomas Kyte <tkyte@oracle.com>

Use DBMS_LOB to read from the BLOB

You will need to create an external procedure to take binary data and write it to the operating system, the external procedure can be written in C. If it was CLOB data, you can use UTL_FILE to write it to the OS but UTL_FILE does not support the binary in a BLOB.

There are articles on MetaLink explaining how to do and it has a C program ready for compiling and the External Procedure stuff, i'd advise a visit.

Especially, look for Note:70110.1, Subject: WRITING BLOB/CLOB/BFILE CONTENTS TO A FILE USING EXTERNAL PROCEDURES

Here is the Oracle code cut and pasted from it. The outputstring procedure is the oracle procedure interface to the External procedure.
-------------------------------------

DECLARE
 i1    BLOB;
 len   NUMBER;
 my_vr RAW(10000);
 i2    NUMBER;
 i3    NUMBER := 10000;
BEGIN
  -- get the blob locator
  SELECT c2
  INTO i1
  FROM lob_tab
  WHERE c1 = 2;

  -- find the length of the blob column
  len := dbms_lob.getlength(i1);
  dbms_output.put_line('Column Length: ' || TO_CHAR(len));

  -- Read 10000 bytes at a time
  i2 := 1;
  IF len < 10000 THEN
    -- If the col length is < 10000
    dbms_lob.read(i1,len,i2,my_vr);

    outputstring('p:\bfiles\ravi.bmp',
    rawtohex(my_vr),'wb',2*len);

    -- You have to convert the data to rawtohex format.
    -- Directly sending the buffer
    -- data will not work
    -- That is the reason why we are sending the length as
    -- the double the size of the data read

    dbms_output.put_line('Read ' || to_char(len) || 'Bytes');
  ELSE
    -- If the col length is > 10000
    dbms_lob.read(i1,i3,i2,my_vr);

    outputstring('p:\bfiles\ravi.bmp',
    rawtohex(my_vr),'wb',2*i3);

    dbms_output.put_line('Read ' || TO_CHAR(i3) || ' Bytes ');
  END IF;

  i2 := i2 + 10000;

  WHILE (i2 < len )
  LOOP
    -- loop till entire data is fetched
    dbms_lob.read(i1,i3,i2,my_vr);

    dbms_output.put_line('Read ' || TO_CHAR(i3+i2-1) ||
    ' Bytes ');

    outputstring('p:\bfiles\ravi.bmp',
    rawtohex(my_vr),'ab',2*i3);

    i2 := i2 + 10000 ;
  END LOOP;
END;
/

Load from file demo 		CREATE OR REPLACE PROCEDURE read_file IS
 src_file BFILE := bfilename('DOCUMENT_DIR', 'image.gif');
 dst_file BLOB;
 lgh_file BINARY_INTEGER;
BEGIN
  -- lock record
  SELECT bin_data
  INTO dst_file
  FROM db_image
  FOR update;

  -- open the file
  dbms_lob.fileopen(src_file, dbms_lob.file_readonly);

  -- determine length
  lgh_file := dbms_lob.getlength(src_file);

  -- read the file
  dbms_lob.loadfromfile(dst_file, src_file, lgh_file);

  -- update the blob field
  UPDATE db_image
  SET bin_data = dst_file;
  COMMIT;

  -- close file
  dbms_lob.fileclose(src_file);

EXCEPTION
  WHEN access_error THEN

  WHEN invalid_argval THEN

  WHEN invalid_directory THEN

  WHEN no_data_found THEN

  WHEN noexist_directory THEN

  WHEN nopriv_directory THEN

  WHEN open_toomany THEN

  WHEN operation_failed THEN

  WHEN unopened_file THEN

  WHEN others THEN

END read_file;
/

LOB Demo by Alberto Dell'Era 		>> Actually, I have already done my own tests and it doesn't.
>> I can only retrieve 4000 as you already mentioned as
>> opposed to the 64000 we're used to, but I think that this
>> is a good trade off considering that we were doing almost
>> 5000 queries at a time.

Perhaps you could consider tuning the temp tablespace extent size to retain the ability to fetch 64000 bytes. Consider this test case (9.2.0.5, 8k block size):

CREATE TABLE don (x clob);

DECLARE
 l_clob clob;
BEGIN
  FOR i IN 1..10
  LOOP
    INSERT INTO don (x) VALUES (empty_clob())
    RETURNING x INTO l_clob;

    -- create a 400,000 bytes clob
    FOR i IN 1..100
    LOOP
      dbms_lob.append(l_clob, rpad ('*',4000,'*'));
    END LOOP;
  END LOOP;
END;
/

CREATE TEMPORARY TABLESPACE don_1024
TEMPFILE 'c:\temp\don_1024.dbf' SIZE 10M
EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 1024k;

CREATE TEMPORARY TABLESPACE don_512
TEMPFILE 'c:\temp\don_512.dbf' SIZE 10M
EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 512k;

CREATE TEMPORARY TABLESPACE don_64
TEMPFILE 'c:\temp\don_64.dbf' SIZE 10M
EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 64k;

SELECT tablespace_name, initial_extent
FROM dba_tablespaces
WHERE tablespace_name LIKE ('DON%');

TABLESPACE_NAME INITIAL_EXTENT
--------------- --------------
DON_1024               1048576
DON_512                 524288
DON_64                   65536

ALTER USER uwclass TEMPORARY TABLESPACE don_1024;

(You must exit and relog in to use the new temp tablespace)

SELECT SUBSTR (x, 1, 64000) PIECE
FROM don;

SELECT COUNT(*)
FROM gv$temporary_lobs
WHERE sid = (
  SELECT sid FROM gv$mystat WHERE rownum = 1);

COUNT(*)
----------
1

(Note: Even if we fetched 10 rows, we have only 1 temp clob at the end).

SELECT tablespace, segtype, blocks*8*1024 USED_BYTES
FROM gv$tempseg_usage
WHERE username = user;

TABLESPACE SEGTYPE     USED_BYTES
---------- ----------- ----------
DON_1024   LOB_DATA       1048576
DON_1024   LOB_INDEX      1048576

ALTER USER dellera TEMPORARY TABLESPACE don_512;

(logout then in again)

TABLESPACE SEGTYPE     USED_BYTES
---------- ----------- ----------
DON_512    LOB_DATA        524288
DON_512    LOB_INDEX       524288

ALTER USER dellera TEMPORARY TABLESPACE don_64;

(logout then in again)

TABLESPACE SEGTYPE     USED_BYTES
---------- ----------- ----------
DON_64     LOB_DATA        327680
DON_64     LOB_INDEX        65536

 So by reducing the extent size we greatly reduce the space allocated to the temp lob_index. I don't know why the lob_data that should contain 64000 bytes stays to 327,680 for an extent size of 64K. Interestingly, if we select only 1 row:

SELECT SUBSTR(x, 1, 64000) PIECE
FROM don
WHERE rownum = 1;

TABLESPACE SEGTYPE     USED_BYTES
---------- ----------- ----------
DON_64     LOB_DATA        196608
DON_64     LOB_INDEX        65536

 I don't know the reason for this. Perhaps temporary LOBs have a different (bigger) CHUNKSIZE and/or PCTVERSION or perhaps they are updated versus being 'truncated' and then inserted for each row fetched?

Obviously, changing the extent size may adversely affect sort-to-disk and hash-join-to-disk, etc, operations - even if, by using an LMT temp tablespace, the impact may (stress on *may*) be immaterial.

Replaces All Code Occurrences Of A String With Another Within A CLOB 		-- 1) clob src - the CLOB source to be replaced.
-- 2) replace str - the string to be replaced.
-- 3) replace with - the replacement string.

FUNCTION replaceClob (
srcClob IN CLOB,
replaceStr IN VARCHAR2,
replaceWith IN VARCHAR2)
RETURN CLOB IS

vBuffer    VARCHAR2 (32767);
l_amount   BINARY_INTEGER := 32767;
l_pos      PLS_INTEGER := 1;
l_clob_len PLS_INTEGER;
newClob    CLOB := EMPTY_CLOB;

BEGIN
  -- initalize the new clob
  dbms_lob.createtemporary(newClob,TRUE);

  l_clob_len := dbms_lob.getlength(srcClob);

  WHILE l_pos < l_clob_len
  LOOP
    dbms_lob.read(srcClob, l_amount, l_pos, vBuffer);

    IF vBuffer IS NOT NULL THEN
      -- replace the text
      vBuffer := replace(vBuffer, replaceStr, replaceWith);
      -- write it to the new clob
      dbms_lob.writeappend(newClob, LENGTH(vBuffer), vBuffer);
    END IF;
    l_pos := l_pos + l_amount;
  END LOOP;

  RETURN newClob;
EXCEPTION
  WHEN OTHERS THEN
    RAISE;
END;
/
Related Topics
DBMS_SQL
Directories
SecureFiles


Oracle DBMS_METADATA
General Information
Source | {ORACLE_HOME}/rdbms/admin/dbmsmeta.sql
First Available | 9.0.1

Constants
Name | Data Type | Value
MAX_PROCOBJ_RETLEN | BINARY_INTEGER | 32767
NEWBLOCK_APPEND | NUMBER | -2
NEWBLOCK_BEGIN | NUMBER | 1
NEWBLOCK_CONTINUE | NUMBER | 0
SESSION_TRANSFORM | BINARY_INTEGER | -1

Object Type Constants
AQ_QUEUE | REF_CONSTRAINT
AQ_QUEUE_TABLE | REFRESH_GROUP
AQ_TRANSFORM | RESOURCE_COST
ASSOCIATION | RLS_CONTEXT
AUDIT | RLS_GROUP
AUDIT_OBJ | RLS_POLICY
CLUSTER | RMGR_CONSUMER_GROUP
COMMENT | RMGR_INTITIAL_CONSUMER_GROUP
CONSTRAINT | RMGR_PLAN
CONTEXT | RMGR_PLAN_DIRECTIVE
DATABASE_EXPORT | ROLE
DB_LINK | ROLE_GRANT
DEFAULT_ROLE | ROLLBACK_SEGMENT
DIMENSION | SCHEMA_EXPORT
DIRECTORY | SEQUENCE
FGA_POLICY | SYNONYM
FUNCTION | SYSTEM_GRANT
INDEX_STATISTICS | TABLE
INDEX | TABLE_DATA
INDEXTYPE | TABLE_EXPORT
JAVA_SOURCE | TABLE_STATISTICS
JOB | TABLESPACE
LIBRARY | TABLESPACE_QUOTA
MATERIALIZED_VIEW | TRANSPORTABLE_EXPORT
MATERIALIZED_VIEW_LOG | TRIGGER
OBJECT_GRANT | TRUSTED_DB_LINK
OPERATOR | TYPE
PACKAGE | TYPE_BODY
PACKAGE_SPEC | TYPE_SPEC
PACKAGE_BODY | USER
PROCEDURE | VIEW
PROFILE | XMLSCHEMA
PROXY |

Defined Data Types 		TYPE offset IS RECORD (
pos                PLS_INTEGER,
len                PLS_INTEGER,
grantor            VARCHAR2(30),
patchtablemetadata VARCHAR2(1));

TYPE objddl IS TABLE OF offset INDEX BY BINARY_INTEGER;

TYPE multiobjects IS TABLE OF objddl INDEX BY BINARY_INTEGER;

Dependencies

DBMSOBJG_DP | DBMS_REDEFINITION
DBMS_ASSERT | DBMS_SNAP_INTERNAL
DBMS_DATAPUMP | DBMS_SQL
DBMS_FILE_GROUP_EXP | DBMS_SYS_ERROR
DBMS_LOB | ODCI_EXTOPT_LIB
DBMS_LOGREP_EXP | PARTLOB$
DBMS_METADATA_BUILD | PLITBLM
DBMS_METADATA_INT | TABCOMPART$
DBMS_METADATA_UTIL | WWV_FLOW_GENERATE_DDL
DBMS_ODCI | XMLTYPE
DBMS_PLUGTS |

Exceptions
Exception Name | Error Code | Reason
invalid_argval | 31600 | Invalid argument
invalid_operation | 31601 | The function was called after the first call to FETCH_xxx
inconsistent_args | 31602 | The parameter value is inconsistent with another value specified
object_not_found | 31603 | The specified object was not found in the database
invalid_object_param | 31604 | Specified parameter value is not valid for this object type
inconsistent_operation | 31607 | Either FETCH_XML was called when the DDL transform was specified, or FETCH_DDL was called when the DDL transform was omitted
object_not_found2 | 31608 | The specified object was not found in the database
stylesheet_load_error | 31609 | Installation script initmeta.sql failed to load the named file from the file system directory into the database
sql_error | 31642 | Untrapped internal DBMS_METADATA error
dbmsjava_error | 39128 | Unexpected DBMS_JAVA error

Object Types For OPEN (partial listing)
Type Name | Meaning
CONSTRAINT | constraints
DATABASE_EXPORT | all metadata objects in a database
DB_LINK | database links
FGA_POLICY | fine-grained audit policies
INDEX_STATISTICS | precomputed statistics on indexes
REF_CONSTRAINT | referential constraint
RLS_CONTEXT | driving contexts for enforcement of fine-grained access-control policies
RMGR_PLAN | resource plans
SCHEMA_EXPORT | all metadata objects in a schema
TABLE_DATA | metadata describing row data for a table, nested table, or partition
TRANSPORTABLE_EXPORT | metadata for objects in a transportable tablespace set
TYPE | user-defined types
ADD_DOCUMENT (new 11g)
Specifies an (S)XML document (as XMLTYPE) to be compared

Overload 1 		dbms_metadata.add_document(handle IN NUMBER, document IN sys.XMLType);
Undocumented
Overload 2 | dbms_metadata.add_document(handle IN NUMBER, document IN CLOB);
Undocumented
ADD_TRANSFORM
When used to retrieve objects, it specifies a transform that FETCH_xxx applies to the XML representation of the retrieved objects. When used to submit objects, specifies a transform that CONVERT or PUT applies to the XML representation of the submitted objects. dbms_metadata.add_transform(
handle      IN NUMBER,
name        IN VARCHAR2,
encoding    IN VARCHAR2 DEFAULT NULL,
object_type IN VARCHAR2 DEFAULT NULL)
RETURN NUMBER;
See SET_REMAP_PARAM Demo
CHECK_MATCH_TEMPLATE
Check if sub-partitions were created via table's subpartition template clause dbms_metadata.check_match_template(
pobjno IN NUMBER,
spcnt  IN NUMBER)
RETURN NUMBER;
Undocumented
CHECK_MATCH_TEMPLATE_LOB
Check if sub-partitions lob were created via table's subpartition template clause dbms_metadata.check_match_template_lob(
pobjno IN NUMBER,
spcnt  IN NUMBER)
RETURN NUMBER;
Undocumented
CHECK_MATCH_TEMPLATE_PAR
Check if sub-partitions were created via table's subpartition template clause dbms_metadata.check_match_template_par(
pobjno IN NUMBER,
spcnt  IN NUMBER)
RETURN NUMBER;
Undocumented
CHECK_TYPE

For transportable import, check a type's definition and typeid 		dbms_metadata.check_type(
schema    IN VARCHAR2,
type_name IN VARCHAR2,
version   IN VARCHAR2,
hashcode  IN VARCHAR2,
typeid    IN VARCHAR2);
Undocumented
CLOSE

Invalidates the handle returned by OPEN or OPENW and cleans up the associated state 		dbms_metadata.close(handle IN NUMBER);
DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO h
  FROM dual;

  dbms_metadata.close(h);
END;
/
COMPARE_ALTER ( new 11g)

This function compares the metadata for two objects and returns a set of ALTER statements for making object 1 like object2. 		dbms_metadata.compare_alter (
object_type   IN VARCHAR2,
name1         IN VARCHAR2,
name2         IN VARCHAR2,
schema1       IN VARCHAR2 DEFAULT NULL,
schema2       IN VARCHAR2 DEFAULT NULL,
network_link1 IN VARCHAR2 DEFAULT NULL,
network_link2 IN VARCHAR2 DEFAULT NULL)
RETURN CLOB;
conn uwclass/uwclass

set serveroutput on

DECLARE
 c CLOB;
BEGIN
  SELECT dbms_metadata.compare_alter('TABLE', 'SERVERS', 'SERV_INST', USER, USER)
  INTO c
  FROM dual;

  dbms_output.put_line(c);
END;
/
COMPARE_ALTER_XML (new 11g)

Compares the metadata for two objects and returns an ALTER_XML document 		dbms_metadata.compare_alter_xml (
object_type   IN VARCHAR2,
name1         IN VARCHAR2,
name2         IN VARCHAR2,
schema1       IN VARCHAR2 DEFAULT NULL,
schema2       IN VARCHAR2 DEFAULT NULL,
network_link1 IN VARCHAR2 DEFAULT NULL,
network_link2 IN VARCHAR2 DEFAULT NULL)
RETURN CLOB;
conn / as sysdba

set serveroutput on

DECLARE
 c CLOB;
BEGIN
  SELECT dbms_metadata.compare_alter_xml('TABLE', 'EMP', 'EMPLOYEES', 'SCOTT', 'HR')
  INTO c
  FROM dual;

  dbms_output.put_line(c);
END;
/
COMPARE_SXML ( new 11g)

The functions compares the metadata for two objects and returns
an sxml difference document 		dbms_metadata.compare_sxml (
object_type   IN VARCHAR2,
name1         IN VARCHAR2,
name2         IN VARCHAR2,
schema1       IN VARCHAR2 DEFAULT NULL,
schema2       IN VARCHAR2 DEFAULT NULL,
network_link1 IN VARCHAR2 DEFAULT NULL,
network_link2 IN VARCHAR2 DEFAULT NULL)
RETURN CLOB;
conn / as sysdba

set serveroutput on

DECLARE
 c CLOB;
BEGIN
  SELECT dbms_metadata.compare_sxml('TABLE', 'EMP', 'EMPLOYEES', 'SCOTT', 'HR')
  INTO c
  FROM dual;

  dbms_output.put_line(c);
END;
/
CONVERT (Function: Overload 3 new to 11g)
Transforms an input XML document into creation DDL

Overload 1 		dbms_metadata.convert(handle IN NUMBER, document IN sys.XMLType)
RETURN sys.ku$_multi_ddls;
TBD
Overload 2 dbms_metadata.convert(handle IN NUMBER, document IN CLOB)
RETURN sys.ku$_multi_ddls;
TBD
This is an alternate higher-performing but less flexible form of CONVERT that returns only a single (but multi-object) CLOB with a collection providing offsets into this CLOB to locate each individual DDL. Parse items per DDL are NOT returned with this version.

Overload 3 		DBMS_METADATA.CONVERT (
handle   IN  NUMBER,
document IN  CLOB,
offsets  OUT NOCOPY multiobjects)
RETURN CLOB;
TBD
Transforms an input XML document into creation DDL

Overload 4 		DBMS_METADATA.CONVERT (
handle   IN     NUMBER,
document IN     sys.XMLType,
result   IN OUT NOCOPY CLOB);
TBD
Overload 5 DBMS_METADATA.CONVERT (
handle   IN     NUMBER,
document IN     CLOB,
result   IN OUT NOCOPY CLOB);
TBD
CONVERT_TO_CANONICAL (new 11g)
Convert string to canonical form
vv.vv.vv.vv.vv, e.g., '08.01.03.00.00' 		dbms_metadata.convert_to_canonical(version IN VARCHAR2) RETURN VARCHAR2
SELECT dbms_metadata.convert_to_canonical('11.1.0.6.0')
FROM dual;
FETCH_CLOB (overload 3 new to 11g)
Returns the object, transformed or not, as a CLOB

Overload 1 		dbms_metadata.fetch_clob(
handle       IN NUMBER,
cache_lob    IN BOOLEAN DEFAULT TRUE,
lob_duration IN PLS_INTEGER DEFAULT DBMS_LOB.SESSION)
RETURN CLOB;
TBD
Returns the object, transformed or not, as a CLOB

Overload 2 		dbms_metadata.fetch_clob(
handle IN     NUMBER,
xmldoc IN OUT NOCOPY CLOB);
TBD
Return metadata for object (transformed or not) as a CLOB

Overload 3 		dbms_metadata.fetch_clob(
handle IN     NUMBER,
xmldoc IN OUT NOCOPY CLOB,
diffs     OUT BOOLEAN);
TBD
FETCH_DDL
Fetch selected DB objects as DDL | dbms_metadata.fetch_ddl(handle IN NUMBER) RETURN sys.ku$_ddls;
TBD
FETCH_DDL_TEXT
Fetch selected DB objects as DDL in a VARCHAR2 dbms_metadata.fetch_ddl_text(handle  IN  NUMBER, partial OUT NUMBER)
RETURN VARCHAR2;
TBD
FETCH_OBJNUMS
Table function to return object numbers. Used to speed up heterogeneous fetch dbms_metadata.fetch_objnums(handle IN NUMBER)
RETURN sys.ku$_ObjNumSet pipelined;
TBD
FETCH_SORTED_OBJNUMS
Table function to return nested table of
obj#-order pairs 		dbms_metadata.fetch_sorted_objnums(handle IN NUMBER)
RETURN sys.ku$_ObjNumPairList;
TBD
FETCH_XML
Fetch selected DB objects as XML docs | dbms_metadata.fetch_xml(handle IN NUMBER) RETURN sys.XMLType;
TBD
FETCH_XML_CLOB (overload 2 new 11g)
Returns the XML metadata for the objects as a CLOB in an IN OUT NOCOPY parameter

Overload 1 		dbms_metadata.fetch_xml_clob(
handle           IN     NUMBER,
doc              IN OUT NOCOPY CLOB,
parsed_items        OUT sys.ku$_parsed_items,
object_type_path    OUT VARCHAR2);
TBD

Returns the XML metadata for the objects as a CLOB in an IN OUT NOCOPY parameter

Overload 2 		dbms_metadata.fetch_xml_clob(
handle           IN     NUMBER,
doc              IN OUT NOCOPY CLOB,
parsed_items     IN OUT NOCOPY sys.ku$_parsed_items,
object_type_path    OUT VARCHAR2,
seqno               OUT NUMBER,
procobj_errors      OUT sys.ku$_vcnt);
TBD
FREE_CONTEXT_ENTRY
To be called *ONLY* by the definer's rights pkg. (dbms_metadata_int) error handling. | dbms_metadata.free_context_entry(ind IN NUMBER);
TBD
GET_ACTION_INSTANCE

Get the export string from call instance_info_exp and instance_extended_info_exp function of package in exppkgact$ 		dbms_metadata.get_action_instance(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2,
name       IN VARCHAR2,
schema     IN VARCHAR2,
namespace  IN NUMBER,
objtype    IN NUMBER,
prepost    IN NUMBER,
isdba      IN NUMBER)
RETURN sys.ku$_procobj_lines;
TBD
GET_ACTION_SCHEMA

Get the export string from call schema_info_exp function of package in exppkgact$ 		dbms_metadata.get_action_schema(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2,
schema     IN VARCHAR2,
prepost    IN NUMBER,
isdba      IN NUMBER)
RETURN sys.ku$_procobj_lines;
TBD
GET_ACTION_SYS

Get the export string from call system_info_exp 		dbms_metadata.get_action_sys(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2,
prepost    IN NUMBER)
RETURN sys.ku$_procobj_lines;
TBD
GET_CANONICAL_VSN
Convert user's VERSION param to canonical form. (APIs unique to the submit interface) | dbms_metadata.get_canonical_vsn(version IN VARCHAR2) RETURN VARCHAR2;
SELECT version, dbms_metadata.get_canonical_vsn(version)
FROM gv$instance;
GET_DDL

Fetch DDL for objects 		dbms_metadata.get_ddl(
object_type IN VARCHAR2,
name        IN VARCHAR2,
schema      IN VARCHAR2 DEFAULT NULL,
version     IN VARCHAR2 DEFAULT 'COMPATIBLE',
model       IN VARCHAR2 DEFAULT 'ORACLE',
transform   IN VARCHAR2 DEFAULT 'DDL')
RETURN CLOB;
Table
CREATE TABLE test
PCTFREE 0
TABLESPACE uwdata AS
SELECT table_name, tablespace_name
FROM user_tables;

SET LONG 10000

SELECT dbms_metadata.get_ddl('TABLE', 'TEST')
FROM dual;

View
CREATE OR REPLACE VIEW my_tables AS
select table_name, tablespace_name
FROM user_tables;

SELECT dbms_metadata.get_ddl('VIEW', 'MY_TABLES')
FROM dual;

Function
CREATE OR REPLACE FUNCTION whoami RETURN VARCHAR2 IS

BEGIN
   RETURN user;
END whoami;
/

SELECT dbms_metadata.get_ddl('FUNCTION', 'WHOAMI')
FROM dual;

Tablespace
SELECT dbms_metadata.get_ddl('TABLESPACE', 'UWDATA')
FROM dual;
GET_DEPENDENT_DDL

Fetch DDL for dependent objects (audits, object grants) 		dbms_metadata.get_dependent_ddl(
object_type        IN VARCHAR2,
base_object_name   IN VARCHAR2,
base_object_schema IN VARCHAR2 DEFAULT NULL,
version            IN VARCHAR2 DEFAULT 'COMPATIBLE',
model              IN VARCHAR2 DEFAULT 'ORACLE',
transform          IN VARCHAR2 DEFAULT 'DDL',
object_count       IN NUMBER   DEFAULT 10000)
RETURN CLOB;
GRANT select ON servers TO hr;
GRANT select ON servers TO scott;

set long 100000

SELECT dbms_metadata.get_dependent_ddl('OBJECT_GRANT','SERVERS')
FROM dual;
GET_DEPENDENT_SXML (new 11g)

Return the metadata for objects dependent on a base object as XML 		dbms_metadata.get_dependent_sxml(
object_type        IN VARCHAR2,
base_object_name   IN VARCHAR2,
base_object_schema IN VARCHAR2 DEFAULT NULL,
version            IN VARCHAR2 DEFAULT 'COMPATIBLE',
model              IN VARCHAR2 DEFAULT 'ORACLE',
transform          IN VARCHAR2 DEFAULT 'SXML',
object_count       IN NUMBER DEFAULT 10000)
RETURN CLOB;
TBD
GET_DEPENDENT_XML

Fetch XML for dependent objects (audits, object grants) 		dbms_metadata.get_dependent_xml(
object_type        IN VARCHAR2,
base_object_name   IN VARCHAR2,
base_object_schema IN VARCHAR2 DEFAULT NULL,
version            IN VARCHAR2 DEFAULT 'COMPATIBLE',
model              IN VARCHAR2 DEFAULT 'ORACLE',
transform          IN VARCHAR2 DEFAULT NULL,
object_count       IN NUMBER DEFAULT 10000)
RETURN CLOB;
GRANT all ON servers TO system;

set long 1000000

SELECT dbms_metadata.get_dependent_xml('TABLE', 'UWCLASS.SERVERS')
FROM dual;
GET_DOMIDX_METADATA

Get PLSQL code from the ODCIIndexGetMetadata
method of a domain index's implementation type 		dbms_metadata.get_domidx_metadata(
index_name   IN VARCHAR2,
index_schema IN VARCHAR2,
type_name    IN VARCHAR2,
type_schema  IN VARCHAR2,
flags        IN NUMBER)
RETURN sys.ku$_procobj_lines;
TBD
GET_DPSTRM_MD

Get stream metadata for table (for use by DataPump data layer only this is an internal API) 		dbms_metadata.get_dpstrm_md (
schema           IN     VARCHAR2,
name             IN     VARCHAR2,
mdversion        IN     VARCHAR2 DEFAULT 'COMPATIBLE',
dpapiversion     IN     NUMBER DEFAULT 3,
doc              IN OUT NOCOPY CLOB,
network_link     IN     VARCHAR2 DEFAULT NULL,
force_lob_be     IN     BOOLEAN DEFAULT FALSE,
force_no_encrypt IN     BOOLEAN DEFAULT FALSE);
TBD
GET_EDITION (new 11g)
Returns the edition of interest for the current MDAPI function. (this is either specified as the 'edition' filter, or the session current edition. | dbms_metadata.get_edition RETURN VARCHAR2;
SELECT dbms_metadata.get_edition FROM dual;
GET_EDITION_ID (new 11g)
Returns the edition ID of interest for the current MDAPI context. | dbms_metadata.get_edition_id RETURN NUMBER;
TBD
GET_GRANTED_DDL

Fetch granted objects (system grants, role grants) DDL 		dbms_metadata.get_granted_ddl(
object_type  IN VARCHAR2,
grantee      IN VARCHAR2 DEFAULT NULL,
version      IN VARCHAR2 DEFAULT 'COMPATIBLE',
model        IN VARCHAR2 DEFAULT 'ORACLE',
transform    IN VARCHAR2 DEFAULT 'DDL',
object_count IN NUMBER   DEFAULT 10000)
RETURN CLOB;
SELECT dbms_metadata.get_granted_ddl('SYSTEM_GRANT', 'UWCLASS')
FROM dual;
GET_GRANTED_XML

Fetch granted objects (system grants, role grants) in XML format 		dbms_metadata.get_granted_xml(
object_type  IN VARCHAR2,
grantee      IN VARCHAR2 DEFAULT NULL,
version      IN VARCHAR2 DEFAULT 'COMPATIBLE',
model        IN VARCHAR2 DEFAULT 'ORACLE',
transform    IN VARCHAR2 DEFAULT NULL,
object_count IN NUMBER   DEFAULT 10000)
RETURN CLOB;
SELECT dbms_metadata.get_granted_xml('SYSTEM_GRANT', 'UWCLASS')
FROM dual;
GET_JAVA_METADATA

Return java info from DBMS_JAVA.EXPORT 		dbms_metadata.get_java_metadata(
java_name   IN VARCHAR2,
java_schema IN VARCHAR2,
type_num    IN NUMBER)
RETURN sys.ku$_java_t;
TBD
GET_PLUGTS_BLK
Get the export string from dbms_plugts dbms_metadata.get_plugts_blk(blockid IN NUMBER)
RETURN sys.ku$_procobj_lines;
TBD
GET_PREPOST_TABLE_ACT
Get the export string for pre-table action from call dbms_export_extension.pre_table

1 = pre 		dbms_metadata.get_prepost_table_act(
prepost IN NUMBER,
schema  IN VARCHAR2,
tname   IN VARCHAR2)
RETURN sys.ku$_taction_list_t;
TBD
Get the export string for post-table action from call dbms_export_extension.post_table

2 = post 		dbms_metadata.get_prepost_table_act(
prepost IN NUMBER,
schema  IN VARCHAR2,
tname   IN VARCHAR2)
RETURN sys.ku$_taction_list_t;
TBD
GET_PROCOBJ

Get the export string from create_exp or audit_exp function of package in exppkobj$ 		dbms_metadata.get_procobj(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2,
objid      IN NUMBER,
isdba      IN PLS_INTEGER)
RETURN sys.ku$_procobj_lines;
TBD
GET_PROCOBJ_GRANT

Get the export string from call grant_exp function of package in exppkobj$ 		dbms_metadata.get_procobj_grant(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2,
objid      IN NUMBER,
isdba      IN PLS_INTEGER)
RETURN sys.ku$_procobj_lines;
TBD
GET_QUERY

Returns the text of the queries that are used by FETCH_xxx. This function assists in debugging 		dbms_metadata.get_query(handle IN NUMBER) RETURN VARCHAR2;
set long 1000000
set serveroutput on
set pagesize 0
set linesize 1000
set trim on
set trimspool on

spool c:\temp\demo.txt

DECLARE
 n NUMBER;
 s VARCHAR2(32767);
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO n
  FROM dual;

  SELECT dbms_metadata.get_query(n)
  INTO s
  FROM dual;

  dbms_output.put_line(s);

  dbms_metadata.close(n);
END;
/

spool off

-- replace :SCHEMA1 with 'UWCLASS'

SELECT /*+rule*/ SYS_XMLGEN(VALUE(KU$), XMLFORMAT.createFormat2('TABLE_T', '7')), 0
FROM SYS.KU$_IOTABLE_VIEW KU$
WHERE NOT (BITAND (KU$.PROPERTY,8192)=8192)
AND NOT BITAND(KU$.SCHEMA_OBJ.FLAGS,128)!=0
AND KU$.SCHEMA_OBJ.OWNER_NAME='UWCLASS';

SELECT /*+rule*/ SYS_XMLGEN(VALUE(KU$), XMLFORMAT.createFormat2('TABLE_T', '7')), 0
FROM SYS.KU$_PFHTABLE_VIEW KU$
WHERE NOT (BITAND (KU$.PROPERTY,8192)=8192)
AND NOT BITAND(KU$.SCHEMA_OBJ.FLAGS,128)!=0
AND KU$.SCHEMA_OBJ.OWNER_NAME='UWCLASS';

SELECT /*+rule*/ SYS_XMLGEN(VALUE(KU$), XMLFORMAT.createFormat2('TABLE_T', '7')), 0
FROM SYS.KU$_PHTABLE_VIEW KU$
WHERE NOT (BITAND (KU$.PROPERTY,8192)=8192)
AND NOT BITAND(KU$.SCHEMA_OBJ.FLAGS,128)!=0
AND KU$.SCHEMA_OBJ.OWNER_NAME='UWCLASS';

SELECT /*+rule*/ SYS_XMLGEN(VALUE(KU$), XMLFORMAT.createFormat2('TABLE_T', '7')), 0
FROM SYS.KU$_FHTABLE_VIEW KU$
WHERE NOT (BITAND (KU$.PROPERTY,8192)=8192)
AND NOT BITAND(KU$.SCHEMA_OBJ.FLAGS,128)!=0
AND KU$.SCHEMA_OBJ.OWNER_NAME='UWCLASS';

SELECT /*+rule*/
SYS_XMLGEN(VALUE(KU$), XMLFORMAT.createFormat2('TABLE_T', '7')), 0
FROM SYS.KU$_HTABLE_VIEW KU$
WHERE NOT (BITAND (KU$.PROPERTY,8192)=8192)
AND NOT BITAND(KU$.SCHEMA_OBJ.FLAGS,128)!=0
AND KU$.SCHEMA_OBJ.OWNER_NAME='UWCLASS';
GET_SXML (new 11g)

Returns the metadata for a single object as SXML. This interface is meant for casual browsing (e.g., from SQLPlus) vs. the programmatic OPEN / FETCH / CLOSE interfaces 		dbms_metadata.get_sxml(
object_type IN VARCHAR2,
name        IN VARCHAR2,
schema      IN VARCHAR2 DEFAULT NULL,
version     IN VARCHAR2 DEFAULT 'COMPATIBLE',
model       IN VARCHAR2 DEFAULT 'ORACLE',
transform   IN VARCHAR2 DEFAULT 'SXML')
RETURN CLOB;
conn / as sysdba

set serveroutput on

DECLARE
 c CLOB;
BEGIN
  SELECT dbms_metadata.get_sxml('TABLE', 'SERVERS', 'UWCLASS')
  INTO c
  FROM dual;

  dbms_output.put_line(c);
END;
/
GET_SYSPRIVS

Get the export string from call grant_sysprivs_exp and audit_sysprivs_exp function of a package in exppkgobj$ 		dbms_metadata.get_sysprivs(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2)
RETURN sys.ku$_procobj_lines;
TBD
GET_SYSPRIVS

Get the export string from call grant_sysprivs_exp and audit_sysprivs_exp function of a package in exppkgobj$ 		dbms_metadata.get_sysprivs(
package    IN VARCHAR2,
pkg_schema IN VARCHAR2,
function   IN VARCHAR2)
RETURN sys.ku$_procobj_lines;
TBD
GET_VERSION (new 11g)
Returns the version of interest for the current MDAPI context. Comes from the version parameter in open | dbms_metadata.get_version RETURN VARCHAR2;
SELECT dbms_metadata.get_version FROM dual;
GET_XML

Fetch XML for objects 		dbms_metadata.get_xml(
object_type IN VARCHAR2,
name        IN VARCHAR2,
schema      IN VARCHAR2 DEFAULT NULL,
version     IN VARCHAR2 DEFAULT 'COMPATIBLE',
model       IN VARCHAR2 DEFAULT 'ORACLE',
transform   IN VARCHAR2 DEFAULT NULL)
RETURN CLOB;
Table
CREATE TABLE test
PCTFREE 0
TABLESPACE uwdata AS
SELECT table_name, tablespace_name
FROM user_tables;

SELECT dbms_metadata.get_xml('TABLE', 'TEST')
FROM dual;

View
CREATE OR REPLACE VIEW my_tables AS
select table_name, tablespace_name
FROM user_tables;

SET LONG 4000

SELECT dbms_metadata.get_xml('VIEW', 'MY_TABLES')
FROM dual;

Function
CREATE OR REPLACE FUNCTION whoami RETURN VARCHAR2 IS
BEGIN
  RETURN user;
END whoami;
/

SELECT dbms_metadata.get_xml('FUNCTION', 'WHOAMI')
FROM dual;
IS_OBJECT_XDB_GENERATED (new 11g)
Check for whether object is generated by an dbms_xmlschema.registerschema call. Used by export for triggers and RLS policies. dbms_metadata.is_object_xdb_generated(
object_name  IN VARCHAR2,
schema       IN VARCHAR2,
base_obj_num IN NUMBER)
Undocumented
NETWORK_CALLOUTS
Execute callouts (used by network mode) | dbms_metadata.network_callouts(handle IN NUMBER);
TBD
NETWORK_FETCH_CLOB

Fetch selected DB objects in a VARCHAR2 (used by network mode) 		dbms_metadata.network_fetch_clob(
handle       IN  NUMBER,
do_xsl_parse IN  NUMBER,
partial      OUT NUMBER,
parse_delim  OUT VARCHAR2,
do_callout   OUT NUMBER,
have_errors  OUT NUMBER)
RETURN VARCHAR2;
TBD
NETWORK_FETCH_ERRORS

Serializes a ku$_vcnt into a VARCHAR2 for network operations. Returns a delimited series of error string 		dbms_metadata.network_fetch_errors(
handle  IN  NUMBER,
cnt     OUT NUMBER,
partial OUT NUMBER,
seqno   OUT NUMBER,
path    OUT VARCHAR2)
RETURN VARCHAR2;
TBD
NETWORK_FETCH_PARSE

Return serialized parse items in a VARCHAR2 used by network mode) 		dbms_metadata.network_fetch_parse(
handle  IN  NUMBER,
cnt     OUT NUMBER,
partial OUT NUMBER,
seqno   OUT NUMBER,
path    OUT VARCHAR2)
RETURN VARCHAR2;
TBD
NETWORK_OPEN

Do OPEN over network, negotiate protocol version 		dbms_metadata.network_open(
object_type      IN  VARCHAR2,
version          IN  VARCHAR2 DEFAULT 'COMPATIBLE',
model            IN  VARCHAR2 DEFAULT 'ORACLE',
client_version   IN  NUMBER,
protocol_version OUT NUMBER)
RETURN NUMBER;
TBD
NET_SET_DEBUG
Set the internal debug switch on remote node | dbms_metadata.net_set_debug(on_off  IN BOOLEAN);
TBD
OKTOEXP_2NDARY_TABLE
Should a secondary object of a domain index be exported? dbms_metadata.oktoexp_2ndary_table(tab_obj_num IN NUMBER)
RETURN PLS_INTEGER;
TBD
OPEN

Specifies the type of object to be retrieved, the version of its metadata, and the object model 		dbms_metadata.open(
object_type  IN VARCHAR2,
version      IN VARCHAR2 DEFAULT 'COMPATIBLE',
model        IN VARCHAR2 DEFAULT 'ORACLE',
network_link IN VARCHAR2 DEFAULT NULL)
RETURN NUMBER;
set serveroutput on

DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO h
  FROM dual;

  dbms_output.put_line(h);

  dbms_metadata.close(h);
END;
/
OPENC (new 11g)
Establishes a 'compare' context and specifies the object type for comparing to (S)XML documents | dbms_metadata.openc(object_type IN VARCHAR2) RETURN NUMBER;
Undocumented
OPENW

Specifies the type of object to be submitted and the object model. The return value is an opaque context handle 		dbms_metadata.openw(
object_type IN VARCHAR2,
version     IN VARCHAR2 DEFAULT 'COMPATIBLE',
model       IN VARCHAR2 DEFAULT 'ORACLE')
RETURN NUMBER;
set serveroutput on

DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.openw('TABLE')
  INTO h
  FROM dual;

  dbms_output.put_line(h);

  dbms_metadata.close(h);
END;
/
PATCH_TYPEID

For transportable import, modify a type's typeid 		dbms_metadata.patch_typeid(
schema   IN VARCHAR2,
name     IN VARCHAR2,
typeid   IN VARCHAR2,
hashcode IN VARCHAR2);
TBD
PUT

Submits an XML document containing object metadata to the database to create the objects

Overload 1 		dbms_metadata.put(
handle   IN     NUMBER,
document IN     sys.XMLType,
flags    IN     NUMBER,
results  IN OUT NOCOPY sys.ku$_SubmitResults)
RETURN BOOLEAN;
TBD

Overload 2 		dbms_metadata.put(
handle   IN     NUMBER,
document IN     CLOB,
flags    IN     NUMBER,
results  IN OUT NOCOPY sys.ku$_SubmitResults)
RETURN BOOLEAN;
TBD
SET_COUNT

The maximum number of objects to be retrieved in a single FETCH_xxx call 		dbms_metadata.set_count(
handle           IN NUMBER,
value            IN NUMBER,
object_type_path IN VARCHAR2 DEFAULT NULL);
DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO h
  FROM dual;

  dbms_metadata.set_count(h, 20, 'TABLE');

  dbms_metadata.close(h);
END;
/
SET_DEBUG
Set the internal debug switch and turn on jdev | dbms_metadata.set_debug(on_off IN BOOLEAN);
TBD
SET_FILTER (overload 2 and 3 new in 11g)

Specifies restrictions on the objects to be retrieved, for example, the object name or schema

Overload 1 		dbms_metadata.set_filter(
handle           IN NUMBER,
name             IN VARCHAR2,
value            IN VARCHAR2,
object_type_path IN VARCHAR2 DEFAULT NULL);
DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO h
  FROM dual;

  dbms_metadata.set_filter(h, 'NAME', '<=''BOWIE_STUFF''');
  dbms_metadata.set_filter(h, 'NAME', '<=''FPN''');

  dbms_metadata.close(h);
END;
/

Overload 2 		dbms_metadata.set_filter(
handle           IN NUMBER,
name             IN VARCHAR2,
value            IN BOOLEAN DEFAULT TRUE,
object_type_path IN VARCHAR2 DEFAULT NULL);
TBD

Overload 3 		dbms_metadata.set_filter(
handle           IN NUMBER,
name             IN VARCHAR2,
value            IN NUMBER,
object_type_path IN VARCHAR2 DEFAULT NULL);
TBD
SET_PARSE_ITEM

Enables output parsing and specifies an object attribute to be parsed and returned 		dbms_metadata.set_parse_item(
handle      IN NUMBER,
name        IN VARCHAR2,
object_type IN VARCHAR2 DEFAULT NULL);

 The following syntax applies when SET_PARSE_ITEM is used for XML submission:

dbms_metadata.set_parse_item(
handle IN NUMBER,
name   IN VARCHAR2);
DECLARE
 h NUMBER;
BEGIN
  SELECT dbms_metadata.open('TABLE')
  INTO h
  FROM dual;

  dbms_metadata.set_parse_item(h, 'T1');

  dbms_metadata.close(h);
END;
/
SET_PARSING (new 11g)
Turn query parsing on/off | dbms_metadata.set_parsing(on_off IN BOOLEAN);
exec dbms_metadata.set_parsing(TRUE);
SET_REMAP_PARAM

Specify parameters to the XSLT stylesheet identified by transform_handle.Use them to modify or customize the output of the transform 		dbms_metadata.set_remap_param(
transform_handle IN NUMBER,
name             IN VARCHAR2,
old_value        IN VARCHAR2,
new_value        IN VARCHAR2,
object_type      IN VARCHAR2 DEFAULT NULL);
set serveroutput on

DECLARE
 h  NUMBER;
 th NUMBER;
BEGIN
  SELECT dbms_metadata.openw('TABLE')
  INTO h
  FROM dual;

  th := dbms_metadata.add_transform(h,'MODIFY');

  -- prepare for a different schema
  dbms_metadata.set_remap_param(th, 'REMAP_SCHEMA', 'UWCLASS', 'IDS');

  dbms_metadata.close(h);
END;
/
SET_TRANSFORM_PARAM

Specify parameters to the XSLT stylesheet identified by transform_handle.Use them to modify or customize the output of the transform

Overload 1 		dbms_metadata.set_transform_param(
transform_handle IN NUMBER,
name             IN VARCHAR2,
value            IN VARCHAR2),
object_type      IN VARCHAR2 DEFAULT NULL);
set long 2000000
set pagesize 0

SELECT dbms_metadata.get_ddl('TABLE', 'T1')
FROM dual;

-- omit the storage clause
exec dbms_metadata.set_transform_param( dbms_metadata.session_transform, 'STORAGE', FALSE);

SELECT dbms_metadata.get_ddl('TABLE', 'T1')
FROM dual;

exec dbms_metadata.set_transform_param( dbms_metadata.session_transform, 'DEFAULT');

Overload 2 		dbms_metadata.set_transform_param(
transform_handle IN NUMBER,
name             IN VARCHAR2,
value            IN BOOLEAN DEFAULT TRUE,
object_type      IN VARCHAR2 DEFAULT NULL);
TBD

Overload 3 		dbms_metadata.set_transform_param(
transform_handle IN NUMBER,
name             IN VARCHAR2,
value            IN NUMBER,),
object_type      IN VARCHAR2 DEFAULT NULL);
TBD
SET_XMLFORMAT

Specify formatting attributes for XML output 		dbms_metadata.set_xmlformat(
handle IN NUMBER,
name   IN VARCHAR2,
value  IN BOOLEAN DEFAULT TRUE);
TBD
Demo (copied from http://www.orafaq.com/node/59)
CREATE TYPE tableddl_ty AS OBJECT (
table_name  VARCHAR2(30),
orig_schema VARCHAR2(30),
orig_ddl    CLOB,
comp_schema VARCHAR2(30),
comp_ddl    CLOB);
/

CREATE TYPE tableddl_ty_tb AS TABLE OF tableddl_ty;
/
CREATE OR REPLACE FUNCTION tableddl_fc (input_values SYS_REFCURSOR)
RETURN tableddl_ty_tb PIPELINED IS

PRAGMA AUTONOMOUS_TRANSACTION;

-- variables to be passed in by sys_refcursor */
table_name  VARCHAR2(30);
orig_schema VARCHAR2(30);
comp_schema VARCHAR2(30);

-- setup output record of TYPE tableddl_ty
out_rec tableddl_ty := tableddl_ty(NULL,NULL,NULL,NULL,NULL);

/* setup handles to be used for setup and fetching metadata information handles are used
to keep track of the different objects (DDL) we will be referencing in the PL/SQL code */
hOpenOrig0  NUMBER;
hOpenOrig   NUMBER;
hOpenComp   NUMBER;
hModifyOrig NUMBER;
hTransDDL   NUMBER;
dmsf        PLS_INTEGER;

/*
CLOBs to hold DDL
Orig_ddl0 will hold the baseline DDL for the object to be compared
Orig_ddl1 will also hold the baseline DDL for the object to be compared against
but will also go through some translations before being compared
against Comp_ddl2
Comp_ddl2 will contain the DDL to be compared against the baseline
*/
Orig_ddl0  CLOB;
Orig_ddl1  CLOB;
Comp_ddl2  CLOB;

ret        NUMBER;
BEGIN
  /* Strip off Attributes not concerned with in DDL. If you are concerned with
     TABLESPACE, STORAGE, or SEGMENT information just comment out these few lines. */
  dmsf := dbms_metadata.session_transform
  dbms_metadata.set_transform_param(dmsf, 'TABLESPACE', FALSE);
  dbms_metadata.set_transform_param(dmsf, 'STORAGE', FALSE);
  dbms_metadata.set_transform_param(dmsf, 'SEGMENT_ATTRIBUTES', FALSE);

  -- Loop through each of the rows passed in by the reference cursor
  LOOP
    /* Fetch the input cursor into PL/SQL variables */
    FETCH input_values INTO table_name, orig_schema, comp_schema;
    EXIT WHEN input_values%NOTFOUND;

    /* Here is the first use of our handles for pointing to the original table DDL
       It names the object_type (TABLE), provides the name of the object (our PL/SQL
       variable table_name), and states the schema it is from */
    hOpenOrig0 := dbms_metadata.open('TABLE');
    dbms_metadata.set_filter(hOpenOrig0,'NAME',table_name);
    dbms_metadata.set_filter(hOpenOrig0,'SCHEMA',orig_schema);

    /* Setup handle again for the original table DDL that will undergo transformation
       We setup two handles for the original object DDL because we want to be able to
       Manipulate one set for comparison but output the original DDL to the user */
    hOpenOrig := dbms_metadata.open('TABLE');
    dbms_metadata.set_filter(hOpenOrig,'NAME',table_name);
    dbms_metadata.set_filter(hOpenOrig,'SCHEMA',orig_schema);

    -- Setup handle for table to compare original against
    hOpenComp := dbms_metadata.open('TABLE');
    dbms_metadata.set_filter(hOpenComp,'NAME',table_name);
    dbms_metadata.set_filter(hOpenComp,'SCHEMA',comp_schema);

    /* Modify the transformation of "orig_schema" to take on ownership of "comp_schema"
       If we didn't do this, when we compared the original to the comp objects there
       would always be a difference because the schema_owner is in the DDL generated */
    hModifyOrig := dbms_metadata.add_transform(hOpenOrig,'MODIFY');
    dbms_metadata.set_remap_param(hModifyOrig,'REMAP_SCHEMA',orig_schema,comp_schema);

    -- This states to created DDL instead of XML to be compared
    hTransDDL := dbms_metadata.add_transform(hOpenOrig0,'DDL');
    hTransDDL := dbms_metadata.add_transform(hOpenOrig ,'DDL');
    hTransDDL := dbms_metadata.add_transform(hOpenComp ,'DDL');

    -- Get the DDD and store into the CLOB PL/SQL variables
    Orig_ddl0 := dbms_metadata.fetch_clob(hOpenOrig0);
    Orig_ddl1 := dbms_metadata.fetch_clob(hOpenOrig);

    /* Here we are providing for those instances where the baseline object does not
       exist in the Comp_schema. */
    BEGIN
      Comp_ddl2 := dbms_metadata.fetch_clob(hOpenComp);
    EXCEPTION
      WHEN OTHERS THEN
        comp_ddl2 := 'DOES NOT EXIST';
    END;

    -- Now simply compare the two DDL statements and output row if not equal
    ret := dbms_lob.compare(Orig_ddl1, Comp_ddl2);
    IF ret != 0 THEN
      out_rec.table_name := table_name;
      out_rec.orig_schema := orig_schema;
      out_rec.orig_ddl := Orig_ddl0;
      out_rec.comp_schema := comp_schema;
      out_rec.comp_ddl := Comp_ddl2;
      PIPE ROW(out_rec);
    END IF;

    -- Cleanup and release the handles
    dbms_metadata.close(hOpenOrig0);
    dbms_metadata.close(hOpenOrig);
    dbms_metadata.close(hOpenComp);
  END LOOP;
  RETURN;
END TABLEDDL_FC;
/

SELECT *
FROM TABLE(tableddl_fc(CURSOR(SELECT table_name, owner, 'UWCLASS'
FROM dba_tables where owner = 'ABC')));
Related Topics
DBMS_PREPROCESSOR


Oracle DBMS_ODCI
General
Note: DBMS_ODCI provides an estimate of of CPU instructions (in thousands) per unit of time in seconds
Source | {ORACLE_HOME}/rdbms/admin/catodci.sql
First Available | 9.0.1
Dependencies
DBMS_ASSERT | IND$ | PLITBLM
DBMS_I_INDEX_UTL | OBJ$ | SECOBJ$
DBMS_METADATA | ODCIINDEXINFO | SEM_INDEXTYPE_IM
DBMS_SQL | ODCISECOBJ | USER$
DBMS_SYS_SQL | ODCISECOBJTABLE |
CLEANUP (new in 11g)
Undocumented dbms_odci.estimate_cleanup(
ia          IN SYS.ODCIIndexInfo,
gtn_context IN NUMBER);
TBD
ESTIMATE_CPU_UNITS
Estimate instructions per second | dbms_odci.estimate_cpu_units(elapsed_time IN NUMBER) RETURN NUMBER;
SELECT dbms_odci.estimate_cpu_units(1) * 1000
FROM dual;
GETMETADATA (new in 11g)
Undocumented dbms_odci.getmetadata(
ia          IN  SYS.ODCIIndexInfo,
exp_version IN  VARCHAR2,
idx_version IN  NUMBER DEFAULT 1,
stmt_string OUT VARCHAR2,
new_block   OUT NUMBER);
TBD
GETTABLENAMES (new in 11g)
Undocumented dbms_odci.gettablenames(
ia          IN  SYS.ODCIIndexInfo,
read_only   IN  NUMBER,
exp_version IN  VARCHAR2,
idx_version IN  NUMBER,
stmt_string OUT VARCHAR2,
gtn_context OUT NUMBER,
status      OUT NUMBER);
TBD
RESTOREREFCURSOR
Undocumented PROCEDURE RestoreRefCursor(rc OUT SYS_REFCURSOR, curnum IN NUMBER)
IS LANGUAGE C
LIBRARY odci_extopt_lib
NAME "RestoreRefCursor"
WITH CONTEXT
PARAMETERS (CONTEXT, rc, curnum OCINumber, curnum INDICATOR);
TBD
SAVEREFCURSOR
Undocumented dbms_odci.SaveRefCursor(rc IN SYS_REFCURSOR, curnum OUT NUMBER)
IS LANGUAGE C
LIBRARY odci_extopt_lib
NAME "SaveRefCursor"
WITH CONTEXT
PARAMETERS (CONTEXT, rc, curnum OCINumber, curnum INDICATOR);
TBD
UPGRADE_SECOBJ
Undocumented | dbms_odci.upgrade_secobj(objlist IN ODCISecObjTable);
TBD


Oracle DBMS_PCLXUTIL
General Information
Note: DBMS_PCLXUTIL uses the DBMS_JOB package to provide a greater degree of parallelism for creating a local index for a partitioned table. This is achieved by asynchronous inter-partition parallelism using the background processes (with DBMS_JOB), in combination with intra-partition parallelism using the parallel query slave processes. DBMS_PCLXUTIL works with both range and range-hash composite partitioning.
Source | {ORACLE_HOME}/rdbms/admin/dbmspclx.sql
Defined Data Type | TYPE JobList IS TABLE OF NUMBER;
Dependencies
DBA_IND_PARTITIONS | DBMS_JOB
DBA_IND_SUBPARTITIONS | DBMS_LOCK
DBA_JOBS | DBMS_OUTPUT
DBA_TABLES | DUAL
DBA_TAB_PARTITIONS | GV$PARAMETER
DBMS_ASSERT | PLITBLM
Object Privileges | Execute is granted to PUBLIC
BUILD_PART_INDEX

Build local partition index 		dbms_pclxutil.build_part_index (
jobs_per_batch IN NUMBER DEFAULT 1,
procs_per_job  IN NUMBER DEFAULT 1,
tab_name       IN VARCHAR2 DEFAULT NULL,
idx_name       IN VARCHAR2 DEFAULT NULL,
force_opt      IN BOOLEAN DEFAULT FALSE);

jobs_per_batch = number of partitions
procs_per_batch = degree <= max_slaves
force_opt = If true forces rebuild of all indexes. If false rebuild only of index marked UNUSABLE.
-- create tablespace DDL on Partitions page
CREATE TABLE prof_hist (
prof_history_id  NUMBER(10),
person_id        NUMBER(10) NOT NULL,
organization_id  NUMBER(10) NOT NULL,
record_date      DATE NOT NULL,
prof_hist_comments VARCHAR2(2000))
PARTITION BY HASH (prof_history_id)
PARTITIONS 3
STORE IN (part1, part2, part3);

SELECT table_name, partition_name
FROM user_tab_partitions;

CREATE INDEX ix_prof_hist
ON prof_hist(prof_history_id)
LOCAL
UNUSABLE;

/* Causes the dictionary entries to be created without "building" the index itself, the time consuming part of creating an index. */

desc user_ind_partitions

SELECT index_name, partition_name, status
FROM user_ind_partitions;

/* Causes a concurrent build of local indexes with the specified degree of parallelism. */
exec dbms_pclxutil.build_part_index(3, 1, 'PROF_HIST', 'IX_PROF_HIST', TRUE);

SELECT index_name, partition_name, status
FROM user_ind_partitions;
Related Topics
DBMS_I_INDEX_UTL
DBMS_INDEX_UTL
Partitioning


Oracle DBMS_PREPROCESSOR
General Information
Source | {ORACLE_HOME}/rdbms/admin/dbmspp.sql
Defined Data Type TYPE source_lines_t IS TABLE OF VARCHAR2(32767)
INDEX BY BINARY_INTEGER;
Dependencies
ALL_SOURCE | DBMS_SYS_ERROR | PLITBLM
DBMS_OUTPUT | DUAL |
Exceptions
Error Code | Reason
ORA-00931 | Missing identifier. The object_name should not be NULL
ORA-24234 | Insufficient privileges or object does not exist
ORA-24235 | Bad value for object type. Should be one of PACKAGE, PACKAGE BODY, PROCEDURE, FUNCTION, TYPE, TYPE, BODY or TRIGGER.
ORA-24236 | The source text is empty
ORA-24241 | Wrapped input
ORA-06502 | Numeric or value error
Security Model | Execute is granted to PUBLIC during installation
GET_POST_PROCESSED_SOURCE

Returns post-processed source text

Overload 1 		dbms_preprocessor.get_post_processed_source (
object_type IN VARCHAR2,
schema_name IN VARCHAR2,
object_name IN VARCHAR2)
RETURN source_lines_t;
CREATE OR REPLACE FUNCTION test_func RETURN NUMBER IS
 i user_tables.blocks%TYPE := 1;
BEGIN
  -- my demo comment in the code
  i := i + 1;
  RETURN i;
END test_func;
/

set serveroutput on

DECLARE
 retval_t  dbms_preprocessor.source_lines_t;
BEGIN
  retval_t := dbms_preprocessor.get_post_processed_source(
  'FUNCTION', 'UWCLASS', 'TEST_FUNC');

  FOR i IN 1..retval_t.LAST
  LOOP
    dbms_output.put_line(retval_t(i));
  END LOOP;
END;
/

Overload 2 		dbms_preprocessor(source IN VARCHAR2) RETURN source_lines_t;
set serveroutput on

DECLARE
 instring  VARCHAR2(32767);
 retval_t  dbms_preprocessor.source_lines_t;
BEGIN
  instring := 'BEGIN ' ||
              '  FOR i IN 1 .. 100 LOOP ' ||
              '    NULL; ' ||
              '  END LOOP; ' ||
              'END;';

  retval_t := dbms_preprocessor.get_post_processed_source(instring);

  FOR i IN 1..retval_t.LAST
  LOOP
    dbms_output.put_line(retval_t(i));
  END LOOP;
END;
/

Overload 3 		dbms_preprocessor(source_lines_t IN VARCHAR2) RETURN source_lines_t;
set serveroutput on

DECLARE
 inval_t  dbms_preprocessor.source_lines_t;
 retval_t dbms_preprocessor.source_lines_t;
BEGIN
  inval_t(1) := 'BEGIN ';
  inval_t(2) := '  FOR i IN 1 .. 100 LOOP ';
  inval_t(3) := '    NULL; ';
  inval_t(4) := '  END LOOP; ';
  inval_t(5) := 'END;';

  retval_t := dbms_preprocessor.get_post_processed_source(inval_t);

  FOR i IN 1..retval_t.LAST
  LOOP
    dbms_output.put_line(retval_t(i));
  END LOOP;
END;
/
PRINT_POST_PROCESSED_SOURCE Procedures

Given a stored PL/SQL unit, print its post-processed source text

Overload 1 		dbms_preprocessor.print_post_processed_source(
object_type IN VARCHAR2,
schema_name IN VARCHAR2,
object_name IN VARCHAR2);
set serveroutput on

BEGIN
  dbms_preprocessor.print_post_processed_source('FUNCTION', 'UWCLASS',
  'TEST_FUNC');
END;
/

Overload 2 		dbms_preprocessor.print_post_processed_source(source VARCHAR2);
set serveroutput on

DECLARE
 str VARCHAR2(32767) := 'BEGIN NULL; END;';
BEGIN
  dbms_preprocessor.print_post_processed_source(str);
END;
/

Overload 3 		dbms_preprocessor.print_post_processed_source(source source_lines_t);
set serveroutput on

DECLARE
 inval_t dbms_preprocessor.source_lines_t;
BEGIN
  inval_t(1) := 'BEGIN ';
  inval_t(2) := 'FOR i IN 1 .. 100 LOOP ';
  inval_t(3) := 'NULL; ';
  inval_t(4) := 'END LOOP; ';
  inval_t(5) := 'END;';

  dbms_preprocessor.print_post_processed_source(inval_t);
END;
/
Related Topics
DBMS_METADATA


Oracle DBMS_RANDOM
General
Note: Deprecated. Use the methods in the DBMS_CRYPTO built-in package.
Source | {ORACLE_HOME}/rdbms/admin/dbmsrand.sql
First Available | 8.0
Dependencies
DBMS_COMPARISON | ODM_MODEL_UTIL
DBMS_JDM_INTERNAL | SDO_NETWORK_MANAGER_I
DBMS_PREDICTIVE_ANALYTICS | SDO_ROUTER_PARTITION
DBMS_WORKLOAD_CAPTURE | UTL_RECOMP
DBMS_WORKLOAD_REPLAY | WWV_FLOW_SAMPLE_APP
DMP_SYS |
INITIALIZE
Initialize package with a seed value | dbms_random.initialize (seed IN BINARY_INTEGER);
exec dbms_random.initialize(17809465);
NORMAL

Returns random numbers in a standard normal distribution 		dbms_random.normal RETURN NUMBER;
SELECT dbms_random.normal
FROM dual;

/

/

SELECT ABS(dbms_random.normal)
FROM dual;

/

/
RANDOM

Generate Random Numeric Values 		dbms_random.random RETURN BINARY_INTEGER;
conn / as sysdba

set serveroutput on

DECLARE
 x  PLS_INTEGER;
 rn NUMBER(20);
BEGIN
  SELECT hsecs
  INTO rn
  FROM gv$timer;

  dbms_random.initialize(rn);
  FOR i IN 1..20
  LOOP
    x := dbms_random.random;
    dbms_output.put_line(x);
    rn := x;
  END LOOP;
  dbms_random.terminate;
END;
/
Force Output To Positive Only Values
SELECT (1+ABS(MOD(dbms_random.random,100000)))
FROM dual;
SEED
Reset the seed value

Overload 1 		dbms_random.seed(val IN BINARY_INTEGER);
exec dbms_random.seed(681457802);
Overload 2 | dbms_random.seed(val IN VARCHAR2);
exec dbms_random.seed('o42i4p');
STRING

Create Random Strings 		dbms_random.string(opt IN CHAR, len IN NUMBER)
RETURN VARCHAR2;

opt seed values:
'a','A'  alpha characters only (mixed case)
'l','L'  lower case alpha characters only
'p','P'  any printable characters
'u','U'  upper case alpha characters only
'x','X'  any alpha-numeric characters (upper)
CREATE TABLE random_strings AS
SELECT rownum RNUM,
dbms_random.string('A', 12) RNDMSTR
FROM all_objects
WHERE rownum <= 200;

col rndmstr format a20

SELECT * FROM random_strings;
-- create test data
CREATE TABLE test (
col1 VARCHAR2(20),
col2 VARCHAR2(20));

DECLARE
 x VARCHAR2(20);
 y VARCHAR2(20);
BEGIN
  FOR i IN 1..100
  LOOP
    x := dbms_random.string('A', 20);
    y := dbms_random.string('A', 20);

    INSERT INTO test
    (col1, col2)
    VALUES
    (x,y);
  END LOOP;
  COMMIT;
END;
/

SELECT * FROM test;
TERMINATE
Terminate use of the Package | dbms_random.terminate;
dbms_random.terminate;
VALUE
Gets a random number, greater than or equal to 0 and less than 1, with decimal 38 digits

Overload 1 		dbms_random.value RETURN NUMBER;
SELECT dbms_random.value
FROM dual;

/

/
Alternatively, you can get a random Oracle number x, where x is greater than or equal to low and less than high

Overload 2 		dbms_random.value(
low  NUMBER,
high NUMBER) RETURN NUMBER
SELECT dbms_random.value(2, 3)
FROM dual;

/

/
Select a random record SELECT srvr_id
FROM (
  SELECT srvr_id
  FROM servers
  ORDER BY dbms_random.value)
WHERE rownum = 1;

/

/
Creating Random Numbers Without DBMS_RANDOM Demo
Demo Procedure IF seed=0 THEN
  seed := EXP(TO_NUMBER(TO_CHAR(SYSDATE,'ss'))/59);
END IF;
seed := 1/(seed - TRUNC(seed));
seed := seed - TRUNC(seed);
Related Topics
DBMS_CRYPTO


Oracle DBMS_REPUTIL Replication Utility

Oracle DBMS_REPUTIL
General Information
Note: This package is deprecated but contains some interesting functionality ... shown below. No attempt has been made on this page to document all of the contents of this package. Just pieces that look particular interesting.
Source | {ORACLE_HOME}/rdbms/admin/dbmsgen.sql
First Availability | 11.1
Security Model | Execute is granted to PUBLIC
GET_CONSTRAINT_NAME

Extracts a constraint name from an error message 		dbms_reputil.get_constraint_name();
INSERT INTO servers (srvr_id) VALUES (1);

SELECT dbms_reputil.get_constraint_name('ORA-00001: unique constraint (UWCLASS.PK_SERVERS) violated')
FROM dual;
GLOBAL_NAME

Returns the database global name 		dbms_reputil.global_name RETURN VARCHAR2
SELECT dbms_reputil.global_name
FROM dual;
RAW_TO_VARCHAR2

Returns a RAW 		dbms_reputil.raw_to_varchar2(
r      IN  RAW,
offset IN  BINARY_INTEGER,
v      OUT VARCHAR2);
set serveroutput on

DECLARE
 outval VARCHAR2(20);
BEGIN
  dbms_reputil.raw_to_varchar2('0011', 1, outval);
  dbms_output.put_line(outval);
END;
/
SET_GLOBAL_NAME
In internal packages, Oracle doesn't want to call PL/SQL to set from_remote, hence, convert from_remote to a function clients are not supposed to assign values to this variable.If they do, use set_from_remote(flag) instead. Running this demo is dangerous. It is here for education purposes only. | dbms_reputil.set_global_name(gdbname IN VARCHAR2);
exec dbms_reputil.set_global_name('TEST');
Related Topics
DBMS_UTILITY


Oracle DBMS_RLS Fine Grained Access Control Virtual Private Database

Oracle DBMS_RLS (FGAC)
Fine Grained Access Control
Virtual Private Database
Version 10.2
General
Note: The functionality supporting FGA is based on dynamic predicates acquired at statement parse time, when the base table or view is referenced in a DML statement.
Source | {ORACLE_HOME}/rdbms/admin/dbmsrlsa.sql
First Available | 8.1.5
Constants
Name | Data Type | Value
STATIC | BINARY_INTEGER | 1
SHARED_STATIC | BINARY_INTEGER | 2
CONTEXT_SENSITIVE | BINARY_INTEGER | 3
SHARED_CONTEXT_SENSITIVE | BINARY_INTEGER | 4
DYNAMIC | BINARY_INTEGER | 5
ALL_ROWS | BINARY_INTEGER | 1
Default Policy Group | SYS_DEFAULT
Dependencies
all_contexts | dba_policy_groups
all_policies | dba_policy_groups
all_policy_contexts | dbms_rls_lib
context$ | rls$
dba_contexts | user_contexts
dba_policies | user_policies
dba_policy_contexts | user_policy_contexts
Related System Privileges create any context
create policy group
drop any context
exempt access policy (not subject to SYS_DEFAULT policies)

Must grant execute on dbms_rls for use
GRANT create any context TO uwclass;
GRANT create any policy TO uwclass;
GRANT drop any context TO uwclass;
GRANT execute ON dbms_rls TO uwclass;
ADD_GROUPED_POLICY
Add a row level security policy to a policy group for a table or view dbms_rls.add_grouped_policy(
object_schema         IN VARCHAR2 := NULL,
object_name           IN VARCHAR2,
policy_group          IN VARCHAR2 := 'SYS_DEFAULT',
policy_name           IN VARCHAR2,
function_schema       IN VARCHAR2 := NULL,
policy_function       IN VARCHAR2,
statement_types       IN VARCHAR2 := NULL,
update_check          IN BOOLEAN  := FALSE,
enable                IN BOOLEAN  := TRUE,
static_policy         IN BOOLEAN  := FALSE,
policy_type           IN BINARY_INTEGER := NULL,
long_predicate        IN BOOLEAN  := FALSE,
sec_relevant_cols     IN VARCHAR2 := NULL,
sec_relevant_cols_opt IN BINARY_INTEGER := NULL);
TBD
ADD_POLICY
Add a row level security policy to a table or view dbms_rls.add_policy(
object_schema         IN VARCHAR2 := NULL,
object_name           IN VARCHAR2,
policy_name           IN VARCHAR2,
function_schema       IN VARCHAR2 := NULL,
policy_function       IN VARCHAR2,
statement_types       IN VARCHAR2 := NULL,
update_check          IN BOOLEAN  := FALSE,
enable                IN BOOLEAN  := TRUE,
static_policy         IN BOOLEAN  := FALSE,
policy_type           IN BINARY_INTEGER := NULL,
=long_predicate        IN BOOLEAN  := FALSE,
sec_relevant_cols     IN VARCHAR2 := NULL,
sec_relevant_cols_opt IN BINARY_INTEGER := NULL);
See FGAC Demo
ADD_POLICY_CONTEXT
Add a driving context to a table or view dbms_rls.add_policy_context(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
namespace     IN VARCHAR2,
attribute     IN VARCHAR2);
TBD
CREATE_POLICY_GROUP
Create a policy group for a table or view dbms_rls.create_policy_group(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
policy_group  IN VARCHAR2);
TBD
DELETE_POLICY_GROUP
Delete a policy group for a table or view dbms_rls.delete_policy_group(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
policy_group  IN VARCHAR2);
TBD
DISABLE_GROUPED_POLICY
Enable or disable a policy for a table or view dbms_rls.disable_grouped_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
group_name    IN VARCHAR2,
policy_name   IN VARCHAR2);
TBD
DROP_GROUPED_POLICY
Drop a row level security policy from a policy group of a table or view dbms_rls.drop_grouped_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
policy_group  IN VARCHAR2 := 'SYS_DEFAULT',
policy_name   IN VARCHAR2);
TBD
DROP_POLICY
Drop a row level security policy from a table or view dbms_rls.drop_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
policy_name   IN VARCHAR2);
See FGAC Demo
DROP_POLICY_CONTEXT
Drop a driving context from a table or view dbms_rls.drop_policy_context(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
namespace     IN VARCHAR2,
attribute     IN VARCHAR2);
TBD
ENABLE_GROUPED_POLICY
Enable or disable a policy for a table or view dbms_rls.enable_grouped_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
group_name    IN VARCHAR2,
policy_name   IN VARCHAR2,
enable        IN BOOLEAN  := TRUE);
TBD
ENABLE_POLICY
Enable or disable a security policy for a table or view dbms_rls.enable_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2,
policy_name   IN VARCHAR2,
enable        IN BOOLEAN  := TRUE);
TBD
REFRESH_GROUPED_POLICY
Invalidate all cursors associated with the policy if no argument provides, all cursors with policies involved will be invalidated dbms_rls.refresh_grouped_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2 := NULL,
group_name    IN VARCHAR2 := NULL,
policy_name   IN VARCHAR2 := NULL);
TBD
REFRESH_POLICY
Invalidate all cursors associated with the policy. If no argument provides, all cursors with policies involved will be invalidated dbms_rls.refresh_policy(
object_schema IN VARCHAR2 := NULL,
object_name   IN VARCHAR2 := NULL,
policy_name   IN VARCHAR2 := NULL);
TBD
Related Topics
Fine Grained Access Control Demo
Object Privileges
Roles
System Privileges


Oracle DBMS_SESSION Roles Database Links Session

Oracle DBMS_SESSION
General
Purpose | Try dbms_session.reset_package. This call will reset all packages variables to their defaults (and will close and flush all cached cursors and free other resources, too, but it will not reset system contexts and it will not cause package initialization part to be re-executed when package is next accessed). Note that no explicit default for a package variable defaults it to NULL.
Source | {ORACLE_HOME}/rdbms/admin/dbmssess.sql
First Available | 7.3.4
Constants used by Modify Package State
Name | Data Type | Value
FREE_ALL_RESOURCES | PLS_INTEGER | 1
REINITIALIZE | PLS_INTEGER | 2
Defined Data Types TYPE AppCtxRecTyp IS RECORD (
namespace VARCHAR2(30),
attribute VARCHAR2(30),
value     VARCHAR2(4000));
/

TYPE AppCtxTabTyp IS TABLE OF AppCtxRecTyp INDEX BY BINARY_INTEGER;
/
Dependencies
CURRENTSESSIONTOKENMAP$ | ODM_MODEL_UTIL
DBMS_ALERT | PBSDE
DBMS_DEBUG | ROWTOKENMAP$
DBMS_REGISTRY_SYS | SDO_SEM_CTX
DBMS_SNAPSHOT | SDO_WFS_LOCK
DBMS_SQLDIAG_INTERNAL | SESSION_CONTEXT
DBMS_STATS_INTERNAL | STORAGE_UI_UTIL_PKG
DBMS_SUMREF_UTIL | TOKENSESSIONMAP$
DRIACC | WM_DDL_UTIL
DRIXMD | WWV_FLOW
KUPD$DATA | WWV_FLOW_DATALOAD_XML
KUPW$WORKER | WWV_FLOW_LANG
LTADM | WWV_FLOW_SC_TRANSACTIONS
LT_CTX_PKG | WWV_FLOW_UTILITIES
MGMT_USER |
Exceptions
Error Code | Reason
ORA-01919 | Role "rolename" does not exist
ORA-01979 | Missing or invalid password for role "rolename"
ORA-01924 | Role "rolename" not granted or does not exist
Security Model | Execute is granted to PUBLIC
CLEAR_ALL_CONTEXT
Removes all contexts | dbms_session.clear_all_context(namespace IN VARCHAR2);
exec dbms_session.clear_all_context('SC_TEST');
CLEAR_CONTEXT

Removes a context 		dbms_session.clear_context(
namespace         IN VARCHAR2,
client_identifier IN VARCHAR2 DEFAULT NULL,
attribute         IN VARCHAR2 DEFAULT NULL);
see SET_CONTEXT demo
CLEAR_IDENTIFIER
Removes the set_client_id in the session | dbms_session.clear_identifier;
exec dbms_session.clear_identifier;
CLOSE_DATABASE_LINK
Closes an open database link dbms_session.close_database_link(dblink IN VARCHAR2);

equivalent to: ALTER SESSION CLOSE DATABASE LINK <name>;
exec dbms_session.close_database_link('TEST_LINK');
FREE_UNUSED_USER_MEMORY

Reclaims unused memory after performing operations requiring large amounts of memory (more than 100K) 		dbms_session.free_unused_user_memory;
CREATE OR REPLACE PACKAGE foobar AS

TYPE number_idx_tbl IS TABLE OF NUMBER
INDEX BY binary_integer;

store1_table number_idx_tbl; -- PL/SQL indexed table
store2_table number_idx_tbl; -- PL/SQL indexed table
store3_table number_idx_tbl; -- PL/SQL indexed table

END foobar;
/

DECLARE
 empty_table foobar.number_idx_tbl;   -- uninitialized
BEGIN
  FOR i in 1..1000000
  LOOP
    foobar.store1_table(i) := i;      -- load data
  END LOOP;

  foobar.store1_table := empty_table; -- empty indexed table

  dbms_session.free_unused_user_memory;

  foobar.store1_table(1) := 100;      -- index tables declared
  foobar.store1_table(2) := 200;      -- but truncated
END;
/
IS_ROLE_ENABLED
Determines if the named role is enabled for this session | dbms_session.is_role_enabled(rolename IN VARCHAR2) RETURN BOOLEAN;
See set_role demo
IS_SESSION_ALIVE

Determines if the specified session is active 		dbms_session.is_session_alive(uniqueid IN VARCHAR2) RETURN BOOLEAN;
-- as uwclass
SELECT dbms_session.unique_session_id
FROM dual;

set serveroutput on

-- as SYS
DECLARE
 x BOOLEAN;
BEGIN
  IF dbms_session.is_session_alive('008D04030001') THEN
    dbms_output.put_line('TRUE');
  ELSE
    dbms_output.put_line('FALSE');
  END IF;
END;
/
LIST_CONTEXT
Returns a list of active namespaces and contexts for the current session | dbms_session.list_context(list OUT AppCtxTabTyp, lsize OUT NUMBER);
See set_context demo
MODIFY_PACKAGE_STATE
Performs actions on the session state of PL/SQL program units that are active in the session
Compiles on the client dbms_session.modify_package_state(action_flags IN PLS_INTEGER);

-- See action_flag constants above
dbms_session.modify_package_state(2);
Free memory resources | exec dbms_session.modify_package_state(dbms_session.free_all_resources);
RESET_PACKAGE
Deinstantiates all packages in this session | dbms_session.reset_package;
exec dbms_session.reset_package;
SESSION_TRACE_DISABLE
Disable SQL trace for the session | dbms_session.session_trace_disable;
exec dbms_session.session_trace_disable;
SESSION_TRACE_ENABLE (new 11g plan_stat parameter)

Enables SQL trace for the session 		dbms_session.session_trace_enable(
waits     IN BOOLEAN  DEFAULT TRUE,
binds     IN BOOLEAN  DEFAULT FALSE,
plan_stat IN VARCHAR2 DEFAULT NULL);

PLAN_STAT | Description
ALL_EXECUTIONS | Always dump row source statistics
FIRST_EXECUTION | Dump row source statistics on first execution
NEVER | Never dump row source statistics
exec dbms_session.session_trace_enable;
SET_CLOSED_CACHED_OPEN_CURSORS
Turns close_cached_open_cursors on or off dbms_session.set_close_cached_open_cursors(close_cursors IN BOOLEAN);

-- Equivalent to: ALTER SESSION SET CLOSE_CACHED_OPEN_CURSORS
exec dbms_session.set_close_cached_open_cursors(TRUE);
SET_CONTEXT

Sets a context within a session 		dbms_session.set_context(
namespace IN VARCHAR2,
attribute IN VARCHAR2,
value     IN VARCHAR2,
username  IN VARCHAR2 DEFAULT NULL,
client_id IN VARCHAR2 DEFAULT NULL);
conn / as sysdba

GRANT create any context TO uwclass;

conn uwclass/uwclass

CREATE OR REPLACE CONTEXT sc_test USING set_contxt;

CREATE OR REPLACE PROCEDURE set_contxt IS
 lcontext dbms_session.appctxtabtyp;
 lsize    NUMBER;
BEGIN
  FOR i IN 1..5 LOOP
    dbms_session.set_context('SC_TEST', 'ATTR' || i, i * 100);
  END LOOP;

  FOR j IN (SELECT * FROM session_context ORDER BY 2) LOOP
    dbms_output.put_line(j.attribute || ',' || j.value);
  END LOOP;

  dbms_output.put_line('*****');
  dbms_session.list_context (lcontext, lsize);
  FOR k IN 1 .. (lcontext.COUNT)
  LOOP
    dbms_output.put_line('Namespace: ' || lcontext(k).namespace || ' Attribute: ' || lcontext(k).attribute || ' Value: ' ||
lcontext(k).value);
  END LOOP;
  dbms_output.put_line('*****');

  dbms_output.put_line('List Size: ' || lsize);

  dbms_session.clear_context('SC_TEST', NULL, 'ATTR2');
  dbms_output.put_line( '*** ATTR2 has now been cleared ***' );

  FOR l IN (SELECT * FROM session_context ORDER BY 2) LOOP
    dbms_output.put_line(l.attribute || ',' || l.value);
  END LOOP;
END set_contxt;
/

set serveroutput on

exec set_contxt
SET_EDITION (new 11g)
Requests a switch to the specified edition. The switch takes effect at the end of the current client call | dbms_session.set_edition(edition IN VARCHAR2);
SELECT *
FROM dba_editions;

exec dbms_session.set_edition('ORA$BASE');
SET_IDENTIFIER

Sets the client ID in the session 		dbms_session.set_identifier(client_id IN VARCHAR2);
/*
internal services
SYS$BACKGROUND is used by background processes only
SYS$USERS is the default for user sessions not associated with other services
*/

set linesize 160
col client_identifier format a25
col client_id format a20
col event format a25
col service_name format a25
col module format a25

SELECT sid, client_identifier, service_name, module
FROM gv_$session;

CREATE OR REPLACE TRIGGER logon_trigger
AFTER LOGON
ON DATABASE

DECLARE
 uid  VARCHAR2(64);
BEGIN
  SELECT ora_login_user ||':'||SYS_CONTEXT('USERENV','OS_USER')
  INTO uid
  FROM dual;

  dbms_session.set_identifier(uid);
END logon_trigger;
/

SELECT sid, client_identifier, service_name, module, action
FROM gv_$session;

-- session 2
log on

exec dbms_application_info.set_module('Battelle', 'Lecture');

-- session 1
SELECT sid, client_identifier, service_name, module, action
FROM gv_$session;

-- ASH
SELECT session_id, client_id, event,
SUM(wait_time + time_waited) ttl_wait_time
FROM gv_$active_session_history
WHERE sample_time BETWEEN SYSDATE - 30/1440 AND SYSDATE
GROUP BY session_id, client_id, event
ORDER BY 2;
SET_NLS
Sets national language support (NLS) dbms_session.set_nls(param IN VARCHAR2, value IN VARCHAR2);

Equivalent to: ALTER SESSION SET <nls_parameter> = <value>;
exec dbms_session.set_nls('nls_date_format','''DD-MON-YY''');
SET_ROLE

Enables and disables roles 		dbms_session.set_role(role_cmd IN VARCHAR2);
set serveroutput on

BEGIN
  IF dbms_session.is_role_enabled('CONNECT') THEN
    dbms_output.put_line('CONNECT is granted');
  ELSE
    dbms_output.put_line('CONNECT is not granted');
  END IF;
END;
/

exec dbms_session.set_role('NONE');

BEGIN
  IF dbms_session.is_role_enabled('CONNECT') THEN
    dbms_output.put_line('CONNECT is granted');
  ELSE
    dbms_output.put_line('CONNECT is not granted');
  END IF;
END;
/

CREATE TABLE set_role_tab (
testcol VARCHAR2(20));

desc user_role_privs

SELECT granted_role
FROM user_role_privs;

exec dbms_session.set_role('CONNECT');

BEGIN
  IF dbms_session.is_role_enabled('CONNECT') THEN
    dbms_output.put_line('CONNECT is granted');
  ELSE
    dbms_output.put_line('CONNECT is not granted');
  END IF;
END;
/

CREATE TABLE set_role_tab (
testcol VARCHAR2(20));
SET_SQL_TRACE
Turns tracing on or off dbms_session.set_sql_trace(sql_trace IN BOOLEAN);

Equivalent to: ALTER SESSION SET SQL_TRACE <ON | OFF>;
exec dbms_session.set_sql_trace(TRUE);
SWITCH_CURRENT_CONSUMER_GROUP

Changes the current resource consumer group of a user's current session 		dbms_session.switch_current_consumer_group(
new_consumer_group     IN  VARCHAR2,
old_consumer_group     OUT VARCHAR2,
initial_group_on_error IN  BOOLEAN);
CREATE OR REPLACE PROCEDURE high_priority_task IS

old_group  VARCHAR2(30);
prev_group VARCHAR2(30);
curr_user  VARCHAR2(30);

BEGIN
  -- switch invoker to privileged consumer group.
  -- If we fail to do so, an
  -- error will be thrown, but the consumer group will not change
  -- because 'initial_group_on_error' is set to FALSE
  dbms_session.switch_current_consumer_group('tkrogrp1',
  old_group, FALSE);

  -- set up exception handler (in the event of an error,
  -- we do not want to return to caller while leaving the session
  -- still in the privileged group)

  BEGIN
    NULL;  -- perform some actions
  EXCEPTION
    WHEN OTHERS THEN
    -- It is possible that the procedure owner does not have
    -- privileges on old_group. 'initial_group_on_error' is
    -- set to TRUE to make sure that the user is moved out
    -- of the privileged group in such a situation

  dbms_session.switch_current_consumer_group(old_group,
  prev_group, TRUE);
      RAISE;
  END;

  -- we've succeeded. Now switch to old_group, or if can
  -- not do so, switch to caller's initial consumer group

  dbms_session.switch_current_consumer_group(old_group,
  prev_group, TRUE);

END high_priority_task;
/
UNIQUE_SESSION_ID
Returns an identifier that is unique for all sessions currently connected to this database | dbms_session.unique_session_id RETURN VARCHAR2;
See is_session_alive demo
Related Topics
Database Links
Packages
Roles
SYS_CONTEXT


Oracle DBMS_SQL Dynamic SQL

Oracle DBMS_SQL
Version 10.2
General
Note: DMBS_SQL is the traditional form of dynamic SQL in Oracle.

For most purposes native dynamic sql (NDS) will suffice but there are some things the DBMS_SQL package does that can not be done any other way. This page emphasizes those areas where there is no substitute.
Source | {ORACLE_HOME}/rdbms/admin/dbmssql.sql
First Available | 7.3.4
Constants
Name | Data Type | Value
v6 | INTEGER | 0
native | INTEGER | 1
v7 | INTEGER | 2

Defined Data Types 		General Types
TYPE desc_rec IS RECORD (
col_type binary_integer := 0,
col_max_len binary_integer := 0,
col_name varchar2(32) := '',
col_name_len binary_integer := 0,
col_schema_name varchar2(32) := '',
col_schema_name_len binary_integer := 0,
col_precision binary_integer := 0,
col_scale binary_integer := 0,
col_charsetid binary_integer := 0,
col_charsetform binary_integer := 0,
col_null_ok boolean := TRUE);

TYPE desc_rec2 IS RECORD (
col_type binary_integer := 0,
col_max_len binary_integer := 0,
col_name varchar2(32767) := '',
col_name_len binary_integer := 0,
col_schema_name varchar2(32) := '',
col_schema_name_len binary_integer := 0,
col_precision binary_integer := 0,
col_scale binary_integer := 0,
col_charsetid binary_integer := 0,
col_charsetform binary_integer := 0,
col_null_ok boolean := TRUE);

TYPE desc_tab IS TABLE OF desc_rec
INDEX BY binary_integer;

TYPE desc_tab2 IS TABLE OF desc_rec2
INDEX BY binary_integer;

TYPE varchar2a IS TABLE OF VARCHAR2(32767)
INDEX BY binary_integer;

TYPE varchar2s IS TABLE OF VARCHAR2(256)
INDEX BY binary_integer;

Bulk SQL Types
TYPE bfile_table IS TABLE OF bfile
INDEX BY binary_integer;

TYPE binary_double_table IS TABLE OF binary_double
INDEX BY binary_integer;

TYPE binary_float_table IS TABLE OF binary_float
INDEX BY binary_integer;

TYPE blob_table IS TABLE OF blob
INDEX BY binary_integer;

TYPE clob_table IS TABLE OF clob
INDEX BY binary_integer;

TYPE date_table IS TABLE OF date
INDEX BY binary_integer;

TYPE interval_day_to_second_table IS TABLE OF
dsinterval_unconstrained INDEX BY binary_integer;

TYPE interval_year_to_MONTH_Table IS TABLE OF
yminterval_unconstrained
INDEX BY binary_integer;

TYPE number_table IS TABLE OF NUMBER
INDEX BY binary_integer;

TYPE time_table IS TABLE OF time_unconstrained
INDEX BY binary_integer;

TYPE time_with_time_zone_Table IS TABLE OF TIME_TZ_UNCONSTRAINED INDEX BY binary_integer;

TYPE timestamp_table IS TABLE OF timestamp_unconstrained
INDEX BY binary_integer;

TYPE timestamp_with_ltz_table IS TABLE OF
TIMESTAMP_LTZ_UNCONSTRAINED
INDEX BY binary_integer;

TYPE urowid_table IS TABLE OF urowid
INDEX BY binary_integer;

TYPE timestamp_with_time_zone_table IS TABLE OF
TIMESTAMP_TZ_UNCONSTRAINED
INDEX BY binary_integer;

TYPE varchar2_table IS TABLE OF VARCHAR2(2000)
INDEX BY binary_integer;
Dependencies SELECT name
FROM dba_dependencies
WHERE referenced_name = 'DBMS_SQL'
UNION
SELECT referenced_name
FROM dba_dependencies
WHERE name = 'DBMS_SQL';
Exceptions
Error Code | Reason
ORA-06562 | Inconsistent types: Raised by procedure "column_value" or "variable_value" if the type of out argument where to put the requested value is different from the type of the value
Flow --
--                      -----------
--                    | open_cursor |
--                      -----------
--                           |
--                           |
--                           v
--                         -----
--          ------------>| parse |
--          |              -----
--          |                |
--          |                | ---------
--          |                v          |
--          |           --------------  |
--          |-------->| bind_variable | |
--          |     ^     -------------   |
--          |     |           |         |
--          |      -----------|         |
--          |                 |<--------
--          |                 v
--          |               query?---------- yes ---------
--          |                 |                           |
--          |                no                           |
--          |                 |                           |
--          |                 v                           v
--          |              -------                  -------------
--          |----------->| execute |            ->| define_column |
--          |              -------             |    -------------
--          |                 |------------    |          |
--          |                 |            |    ----------|
--          |                 v            |              v
--          |           --------------     |           -------
--          |       ->| variable_value |   |  ------>| execute |
--          |      |    --------------     | |         -------
--          |      |          |            | |            |
--          |       ----------|            | |            |
--          |                 |            | |            v
--          |                 |            | |        ----------
--          |                 |<-----------  |----->| fetch_rows |
--          |                 |              |        ----------
--          |                 |              |            |
--          |                 |              |            v
--          |                 |              |  -----------------
--          |                 |              | | column_value    |
--          |                 |              | | variable_value  |
--          |                 |              |  -----------------
--          |                 |              |            |
--          |                 |<--------------------------
--          |                 |
--           -----------------|
--                            |
--                            v
--                       ------------
--                     | close_cursor |
--                       ------------
--
BIND_ARRAY

Binds a given value to a given collection

Overload 1 		dbms_sql.BIND_ARRAY(
c      IN INTEGER,
name   IN VARCHAR2,
n_tab  IN NUMBER_TABLE);
conn scott/tiger

DECLARE
 stmt          VARCHAR2(200);
 dept_no_array dbms_sql.number_table;
 c             NUMBER;
 dummy         NUMBER;
BEGIN
  dept_no_array(1) := 10; dept_no_array(2) := 20;
  dept_no_array(3) := 30; dept_no_array(4) := 40;
  dept_no_array(5) := 30; dept_no_array(6) := 40;
  stmt := 'delete from emp where deptno = :dept_array';
  c := dbms_sql.open_cursor;
  dbms_sql.parse(c, stmt, dbms_sql.NATIVE);
  dbms_sql.bind_array(c, ':dept_array', dept_no_array, 1, 4);
  dummy := dbms_sql.execute(c);
  dbms_sql.close_cursor(c);

EXCEPTION
  WHEN OTHERS THEN
    IF dbms_sql.is_open(c) THEN
      dbms_sql.close_cursor(c);
    END IF;
    RAISE;
END;
/
Overload 2 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
c_tab  IN VARCHAR2_TABLE);
TBD
Overload 3 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
d_tab  IN DATE_TABLE);
TBD
Overload 4 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
bl_tab IN BLOB_TABLE);
TBD
Overload 5 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
cl_tab IN CLOB_TABLE);
TBD
Overload 6 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
bf_tab IN BFILE_TABLE);
TBD
Overload 7 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
n_tab  IN NUMBER_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 8 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
c_tab  IN VARCHAR2_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 9 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
d_tab  IN DATE_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 10 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
b_tab  IN BLOB_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 11 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
c_tab  IN CLOB_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 12 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
bf_tab IN BFILE_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 13 dbms_sql.bind_array(
c       IN INTEGER,
name    IN VARCHAR2,
ur_tab IN UROWID_TABLE);
TBD
Overload 14 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
ur_tab IN UROWID_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
Overload 15 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
tm_tab IN TIME_TABLE);
TBD
Overload 16 dbms_sql.bind_array (
c       IN INTEGER,
name    IN VARCHAR2,
tm_tab IN TIME_TABLE,
index1 IN INTEGER,
index2 IN INTEGER);
TBD
BIND_VARIABLE

Binds a given value to a given variable 		dbms_sql.bind_variable(
c     IN INTEGER,
name  IN VARCHAR2,
value IN NUMBER);
conn scott/tiger

SELECT COUNT(*) FROM emp;

CREATE OR REPLACE PROCEDURE demo(salary IN NUMBER) AS
 cursor_name    INTEGER;
 rows_processed INTEGER;
BEGIN
  cursor_name := dbms_sql.open_cursor;
  dbms_sql.parse(cursor_name, 'DELETE FROM emp WHERE sal > :x',
dbms_sql.NATIVE);
  dbms_sql.bind_variable(cursor_name, ':x', salary);
  rows_processed := dbms_sql.execute(cursor_name);
  dbms_sql.close_cursor(cursor_name);
EXCEPTION
  WHEN OTHERS THEN
    dbms_sql.close_cursor(cursor_name);
END demo;
/

exec demo(30001)

SELECT COUNT(*) FROM emp;

rollback;
Overload 2 dbms_sql.bind_variable(
c     IN INTEGER,
name  IN VARCHAR2,
value IN VARCHAR2 CHARACTER SET ANY_CS);
TBD
Overload 3 dbms_sql.bind_variable(
c              IN INTEGER,
name           IN VARCHAR2,
value          IN VARCHAR2 CHARACTER SET ANY_CS,
out_value_size IN INTEGER);
TBD
Overload 4 dbms_sql.bind_variable (
c     IN INTEGER,
name  IN VARCHAR2,
value IN DATE);
TBD
Overload 5 dbms_sql.bind_variable(
c     IN INTEGER,
name  IN VARCHAR2,
value IN BLOB);
TBD
Overload 6 dbms_sql.bind_variable(
c     IN INTEGER,
name  IN VARCHAR2,
value IN CLOB CHARACTER SET ANY_CS);
TBD
Overload 7 dbms_sql.bind_variable (
c     IN INTEGER,
name  IN VARCHAR2,
value IN BFILE);
TBD
Overload 8 dbms_sql.bind_variable(
c     IN INTEGER,
name  IN VARCHAR2,
value IN TIME_UNCONSTRAINED);
TBD
BIND_VARIABLE_CHAR
Binds a given value to a given variable

Overload 1 		dbms_sql.bind_variable_char(
c     IN INTEGER,
name  IN VARCHAR2,
value IN CHAR CHARACTER SET ANY_CS);
See bind_variable demo
Overload 2 dbms_sql.bind_variable_char(
c              IN INTEGER,
name           IN VARCHAR2,
value          IN CHAR CHARACTER SET ANY_CS,
out_value_size IN INTEGER);
TBD
BIND_VARIABLE_RAW
Binds a given value to a given variable

Overload 1 		dbms_sql.bind_variable_raw(
c     IN INTEGER,
name  IN VARCHAR2,
value IN RAW);
See bind_variable demo
Overload 2 dbms_sql.bind_variable_raw(
c              IN INTEGER,
name           IN VARCHAR2,
value          IN RAW,
out_value_size IN INTEGER);
TBD
BIND_VARIABLE_ROWID
Binds a given value to a given variable

Overload 1 		dbms_sql.bind_variable_rowid(
c     IN INTEGER,
name  IN VARCHAR2,
value IN ROWID);
See bind_variable demo
Overload 2 dbms_sql.bind_variable_rowid(
c              IN INTEGER,
name           IN VARCHAR2,
value          IN ROWID,
out_value_size IN INTEGER);
TBD
CLOSE_CURSOR
Closes cursor and free memory | dbms_sql.close_cursor(c IN OUT INTEGER);
See is_open demo
COLUMN_VALUE
Returns value of the cursor element for a given position in a cursor

Overload 1 		dbms_sql.column_value
c        IN  INTEGER,
position IN  INTEGER,
value    OUT NUMBER);
See final demo
Overload 2 dbms_sql.column_value(
c         IN  INTEGER,
position  IN  INTEGER,
value     OUT VARCHAR2 CHARACTER SET ANY_CS);
TBD
Overload 3 dbms_sql.column_value(
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT DATE);
TBD
Overload 4 dbms_sql.column_value(
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT BLOB);
TBD
Overload 5 dbms_sql.column_value(
c        IN  INTEGER,
position IN  INTEGER,
value    OUT CLOB CHARACTER SET ANY_CS);
TBD
Overload 6 dbms_sql.column_value (
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT BFILE);
TBD
Overload 7 dbms_sql.column_value(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT NUMBER,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
Overload 8 dbms_sql.column_value(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT VARCHAR2 CHARACTER SET ANY_CS,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
Overload 9 dbms_sql.column_value(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT DATE,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
Overload 10 dbms_sql.column_value(
c        IN INTEGER,
position  IN  INTEGER,
n_tab    IN NUMBER_TABLE);
TBD
Overload 11 dbms_sql.column_value(
c        IN INTEGER,
position  IN  INTEGER,
c_tab    IN VARCHAR2_TABLE);
TBD
Overload 12 dbms_sql.column_value(
c        IN INTEGER,
position  IN INTEGER,
d_tab    IN DATE_TABLE);
TBD
Overload 13 dbms_sql.column_value(
c        IN INTEGER,
position  IN  INTEGER,
bl_tab   IN BLOB_TABLE);
TBD
Overload 14 dbms_sql.column_value(
c        IN INTEGER,
position  IN  INTEGER,
cl_tab   IN CLOB_TABLE);
TBD
Overload 15 dbms_sql.column_value (
c        IN INTEGER,
position  IN  INTEGER,
bf_tab   IN BFILE_TABLE);
TBD
Overload 16 dbms_sql.column_value (
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT UROWID);
TBD
Overload 17 dbms_sql.column_value (
c        IN INTEGER,
position  IN INTEGER,
ur_tab   IN UROWID_TABLE);
TBD
Overload 18 dbms_sql.column_value (
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT TIME_UNCONSTRAINED);
TBD
Overload 19 dbms_sql.column_value(
c        IN INTEGER,
position IN INTEGER,
tm_tab   IN TIME_TABLE);
TBD
COLUMN_VALUE_CHAR
Returns value of the cursor element for a given position in a cursor

Overload 1 		dbms_sql.column_value_char(
c        IN  INTEGER,
position  IN  INTEGER,
value    OUT CHAR CHARACTER SET ANY_CS);
See column_value in final demo
Overload 2 dbms_sql.column_value_char(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT CHAR CHARACTER SET ANY_CS,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
COLUMN_VALUE_LONG
Returns a selected part of a LONG column, that has been defined using DEFINE_COLUMN_LONG dbms_sql.column_value_long(
c            IN  INTEGER,
position     IN  INTEGER,
length       IN  INTEGER,
offset       IN  INTEGER,
value        OUT VARCHAR2,
value_length OUT INTEGER);
See column_value in final demo
COLUMN_VALUE_RAW
Returns value of the cursor element for a given position in a cursor

Overload 1 		dbms_sql.column_value_raw(
c        IN  INTEGER,
position IN  INTEGER,
value    OUT RAW);
See column_value in final demo
Overload 2 dbms_sql.column_value_raw(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT RAW,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
COLUMN_VALUE_ROWID
Undocumented

Overload 1 		dbms_sql.column_value_rowid(
c               IN  INTEGER,
position        IN  INTEGER,
value           OUT ROWID);
See column_value in final demo
Overload 2 dbms_sql.column_value_rowid(
c             IN  INTEGER,
position      IN  INTEGER,
value         OUT ROWID,
column_error  OUT NUMBER,
actual_length OUT INTEGER);
TBD
DEFINE_ARRAY

Defines a collection to be selected from the given cursor, used only with SELECT statements

Overload 1 		dbms_sql.define_array(
c         IN INTEGER,
position  IN INTEGER,
n_tab     IN NUMBER_TABLE,
cnt       IN INTEGER,
lower_bnd IN INTEGER);
DECLARE
 c     NUMBER;
 d     NUMBER;
 n_tab dbms_sql.number_table;
 indx  NUMBER := -10;
BEGIN
  c := dbms_sql.open_cursor;
  dbms_sql.parse(c,'select n from t order by 1',dbms_sql.NATIVE);

  dbms_sql.define_array(c, 1, n_tab, 10, indx);

  d := dbms_sql.execute(c);

  LOOP
    d := dbms_sql.fetch_rows(c);
    dbms_sql.column_value(c, 1, n_tab);
    exit when d != 10;
  END LOOP;

  dbms_sql.close_cursor(c);
EXCEPTIONS
  WHEN OTHERS THEN
    IF dbms_sql.is_open(c) THEN
      dbms_sql.close_cursor(c);
    END IF;
    RAISE;
END;
/
Overload 2 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
c_tab       IN VARCHAR2_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 3 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
d_tab       IN DATE_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 4 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
bl_tab      IN BLOB_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 5 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
cl_tab      IN CLOB_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 6 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
bf_tab      IN BFILE_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 7 dbms_sql.define_array (
c           IN INTEGER,
position    IN INTEGER,
ur_tab      IN UROWID_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
Overload 8 dbms_sql.define_array(
c           IN INTEGER,
position    IN INTEGER,
tm_tab      IN TIME_TABLE,
cnt         IN INTEGER,
lower_bound IN INTEGER);
TBD
DEFINE_COLUMN
Defines a column to be selected from the given cursor, used only with SELECT statements

Overload 1 		dbms_sql.define_column (
c        IN INTEGER,
position IN INTEGER,
column   IN NUMBER)
See final demo
Overload 2 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN VARCHAR2 CHARACTER SET ANY_CS,
column_size IN INTEGER);
TBD
Overload 3 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN DATE);
TBD
Overload 4 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN BLOB);
TBD
Overload 5 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN CLOB);
TBD
Overload 6 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN BFILE);
TBD
Overload 7 dbms_sql.define_column (
c           IN INTEGER,
position    IN INTEGER,
column      IN UROWID);
TBD
Overload 8 dbms_sql.define_column(
c           IN INTEGER,
position    IN INTEGER,
column      IN TIME_UNCONSTRAINED);
TBD
DEFINE_COLUMN_CHAR
Undocumented dbms_sql.define_column_char(
c           IN INTEGER,
position    IN INTEGER,
column      IN CHAR CHARACTER SET ANY_CS,
column_size IN INTEGER);
See define_column in final demo
DEFINE_COLUMN_LONG
Defines a LONG column to be selected from the given cursor, used only with SELECT statements dbms_sql.define_column_long(
c        IN INTEGER,
position IN INTEGER);
See define_column in final demo
DEFINE_COLUMN_RAW
Undocumented dbms_sql.define_column_raw(
c           IN INTEGER,
position    IN INTEGER,
column      IN RAW,
column_size IN INTEGER);
See define_column in final demo
DEFINE_COLUMN_ROWID
Undocumented dbms_sql.define_column_rowid(
c        IN INTEGER,
position IN INTEGER,
column   IN ROWID);
See define_column in final demo
DESCRIBE_COLUMNS

Describes the columns for a cursor opened and parsed through DBMS_SQL 		dbms_sql.describe_columns(
c       IN  INTEGER,
col_cnt OUT INTEGER,
desc_t  OUT DESC_TAB);
DECLARE
 c       NUMBER;
 d       NUMBER;
 col_cnt PLS_INTEGER;
 f       BOOLEAN;
 rec_tab dbms_sql.desc_tab;
 col_num NUMBER;

PROCEDURE print_rec(rec in dbms_sql.desc_rec) IS
BEGIN
  dbms_output.new_line;
  dbms_output.put_line('col_type = ' || rec.col_type);
  dbms_output.put_line('col_maxlen = ' || rec.col_max_len);
  dbms_output.put_line('col_name = ' || rec.col_name);
  dbms_output.put_line('col_name_len = ' || rec.col_name_len);
  dbms_output.put_line('col_schema_name= ' || rec.col_schema_name);
  dbms_output.put_line('col_schema_name_len= ' || rec.col_schema_name_len);
  dbms_output.put_line('col_precision = ' || rec.col_precision);
  dbms_output.put_line('col_scale = ' || rec.col_scale);
  dbms_output.put('col_null_ok = ');

  IF (rec.col_null_ok) THEN
    dbms_output.put_line('True');
  ELSE
    dbms_output.put_line('False');
  END IF;
END;

BEGIN
  c := dbms_sql.open_cursor;
  dbms_sql.parse(c,'select * from scott.bonus',dbms_sql.NATIVE);
  d := dbms_sql.execute(c);
  dbms_sql.describe_columns(c, col_cnt, rec_tab);

/*
Following loop could simply be for j in 1..col_cnt loop.
Here we are simply illustrating some of the PL/SQL table features.
*/
  col_num := rec_tab.first;

  IF (col_num IS NOT NULL) THEN
    LOOP
      print_rec(rec_tab(col_num));
      col_num := rec_tab.next(col_num);
    EXIT WHEN (col_num is null);
    END LOOP;
  END IF;

  dbms_sql.close_cursor(c);
END;
/
DESCRIBE_COLUMNS2
Describes the specified column, an alternative method dbms_sql.describe_columns2(
c         IN  INTEGER,
col_cnt   OUT INTEGER,
desc_tab2 OUT DESC_TAB);
TBD
EXECUTE
Execute dynamic SQL cursor | dbms_sql.execute(c IN INTEGER) RETURN INTEGER;
DECLARE
 sqlstr  VARCHAR2(50);
 tCursor PLS_INTEGER;
 RetVal  NUMBER;
BEGIN
  sqlstr := 'DROP SYNONYM my_synonym';
  tCursor := dbms_sql.open_cursor;
  dbms_sql.parse(tCursor, sqlstr, dbms_sql.NATIVE);
  RetVal := dbms_sql.execute(tCursor);
  dbms_sql.close_cursor(tCursor);
END;
/
EXECUTE_AND_FETCH
Executes a given cursor and fetch rows dbms_sql.execute_and_fetch(
c     IN INTEGER,
exact IN BOOLEAN DEFAULT FALSE)
RETURN INTEGER;
Combine demo w/ last_row_count and last_row_id demos
FETCH_ROWS
Fetches a row from a given cursor | dbms_sql.fetch_rows(c IN INTEGER) RETURN INTEGER;
See final demo
IS_OPEN
Determine whether a cursor is open | dbms_sql.is_open(c IN INTEGER) RETURN BOOLEAN;
set serveroutput on

DECLARE
 tCursor PLS_INTEGER;
BEGIN
  tCursor := dbms_sql.open_cursor;

  IF dbms_sql.is_open(tCursor) THEN
    dbms_output.put_line('1-OPEN');
  ELSE
    dbms_output.put_line('1-CLOSED');
  END IF;

  dbms_sql.close_cursor(tCursor);

  IF dbms_sql.is_open(tCursor) THEN
    dbms_output.put_line('2-OPEN');
  ELSE
    dbms_output.put_line('2-CLOSED');
  END IF;
END;
/
LAST_ERROR_POSITION
Returns byte offset in the SQL statement text where the error occurred | dbms_sql.last_error_position RETURN INTEGER;
TBD
LAST_ROW_COUNT
Returns cumulative count of the number of rows fetched | dbms_sql.last_row_count RETURN INTEGER;
TBD
LAST_ROW_ID
Returns ROWID of last row processed | dbms_sql.last_row_id RETURN ROWID;
TBD
LAST_SQL_FUNCTION_CODE
Returns SQL function code for statement | dbms_sql.last_sql_function_code RETURN INTEGER;
TBD
OPEN_CURSOR
Open dynamic SQL cursor and return cursor ID number of new cursor | dbms_sql.open_cursor RETURN INTEGER;
See is_open demo
PARSE

Parse statement

Overload 1 		dbms_sql.parse(
c             IN INTEGER,
statement     IN VARCHAR2,
language_flag IN INTEGER);
CREATE SYNONYM test_syn FOR dual;

SELECT *
FROM test_syn;

SELECT synonym_name
FROM user_synonyms;

DECLARE
  sqlstr  VARCHAR2(50);
  tCursor PLS_INTEGER;
BEGIN
  sqlstr := 'DROP SYNONYM test_syn';
  tCursor := dbms_sql.open_cursor;
  dbms_sql.parse(tCursor, sqlstr, dbms_sql.NATIVE);
  dbms_sql.close_cursor(tCursor);
END;
/

SELECT synonym_name
FROM user_synonyms;
-- with returning clause

CREATE OR REPLACE PROCEDURE single_row_insert(c1 NUMBER, c2 NUMBER, r OUT NUMBER) IS
 c NUMBER;
 n NUMBER;
BEGIN
  c := dbms_sql.open_cursor;

  dbms_sql.parse(c, 'INSERT INTO tab VALUES (:bnd1, :bnd2) ' ||
  'returning c1*c2 into :bnd3', 2);

  dbms_sql.bind_variable(c, 'bnd1', c1);
  dbms_sql.bind_variable(c, 'bnd2', c2);
  dbms_sql.bind_variable(c, 'bnd3', r);

  n := dbms_sql.execute(c);

  dbms_sql.variable_value(c, 'bnd3', r); -- get value of outbind
  dbms_sql.close_cursor(c);
END single_row_insert;
/
Overload 2 dbms_sql.parse(
c             IN INTEGER,
statement     IN VARCHAR2A,
lb            IN INTEGER,
ub            IN INTEGER,
lfflg         IN BOOLEAN,
language_flag IN INTEGER);
TBD
Overload 3 dbms_sql.parse(
c             IN INTEGER,
statement     IN VARCHAR2S,
lb            IN INTEGER,
ub            IN INTEGER,
lfflg         IN BOOLEAN,
language_flag IN INTEGER);
TBD
VARIABLE_VALUE
Returns value of named variable for given cursor

Overload 1 		dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT NUMBER);
TBD
Overload 2 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT VARCHAR2 CHARACTER SET ANY_CS);
TBD
Overload 3 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT DATE);
TBD
Overload 4 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT BLOB);
TBD
Overload 5 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT CLOB CHARACTER SET ANY_CS);
TBD
Overload 6 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT BFILE);
TBD
Overload 7 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN NUMBER_TABLE);
TBD
Overload 8 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN VARCHAR2_TABLE);
TBD
Overload 9 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN DATE_TABLE);
TBD
Overload 10 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN BLOB_TABLE);
TBD
Overload 11 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN CLOB_TABLE);
TBD
Overload 12 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN BFILE_TABLE);
TBD
Overload 13 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT UROWID);
TBD
Overload 14 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN VARCHAR2,
value IN UROWID_TABLE);
TBD
Overload 15 dbms_sql.variable_value(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT TIME_UNCONSTRAINED);
TBD
Overload 16 dbms_sql.variable_value(
c     IN INTEGER,
name  IN VARCHAR2,
value IN TIME_TABLE);
TBD
VARIABLE_VALUE_CHAR
Undocumented dbms_sql.variable_value_char(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT CHAR CHARACTER SET ANY_CS);
TBD
VARIABLE_VALUE_RAW
Undocumented dbms_sql.variable_value_raw(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT RAW);
TBD
VARIABLE_VALUE_ROWID
Undocumented dbms_sql.variable_value_rowid(
c     IN  INTEGER,
name  IN  VARCHAR2,
value OUT ROWID);
TBD
Demos

Drop Synonym Demo 		SELECT synonym_name
FROM user_synonyms;

CREATE SYNONYM d FOR dept;
CREATE SYNONYM e FOR emp;

SELECT synonym_name
FROM user_synonyms;
DECLARE
 CURSOR syn_cur IS
 SELECT synonym_name
 FROM user_synonyms;

 RetVal  NUMBER;
 sqlstr  VARCHAR2(200);
 tCursor PLS_INTEGER;
BEGIN
  FOR syn_rec IN syn_cur
  LOOP
    sqlstr := 'DROP SYNONYM ' || syn_rec.synonym_name;
    tCursor := dbms_sql.open_cursor;
    dbms_sql.parse(tCursor, sqlstr, dbms_sql.NATIVE);
    RetVal := dbms_sql.execute(tCursor);
    dbms_sql.close_cursor(tCursor);
  END LOOP;
END dropsyn;
/

SELECT synonym_name
FROM user_synonyms;

Executing CLOBS Demo Tables CREATE TABLE workstations (
srvr_id     NUMBER(10),
ws_id       NUMBER(10),
location_id NUMBER(10),
cust_id     VARCHAR2(15),
status      VARCHAR2(1),
latitude    FLOAT(20),
longitude   FLOAT(20),
netaddress  VARCHAR2(15));

CREATE TABLE test (test VARCHAR2(50));

Demonstration dynamic SQL 		CREATE OR REPLACE PROCEDURE execute_plsql_block(plsql_code_block CLOB) IS

ds_cur    PLS_INTEGER := dbms_sql.open_cursor;
sql_table dbms_sql.VARCHAR2S;

c_buf_len CONSTANT BINARY_INTEGER := 256;
v_accum   INTEGER := 0;
v_beg     INTEGER := 1;
v_end     INTEGER := 256;
v_loblen  PLS_INTEGER;
v_RetVal  PLS_INTEGER;

---------------------------
-- local function to the execute_plsql_block procedure
FUNCTION next_row(
 clob_in IN CLOB,
 len_in IN INTEGER,
 off_in IN INTEGER) RETURN VARCHAR2 IS
BEGIN
  RETURN DBMS_LOB.SUBSTR(clob_in, len_in, off_in);
END next_row;
---------------------------

BEGIN
  v_loblen := DBMS_LOB.GETLENGTH(plsql_code_block);
  INSERT INTO test
  (test)
  VALUES
  ('Demo block is ' || TO_CHAR(v_loblen) || ' bytes in length');
  COMMIT;

  LOOP
    -- Set the length to the remaining size
    -- if there are < c_buf_len characters remaining.
    IF v_accum + c_buf_len > v_loblen THEN
      v_end := v_loblen - v_accum;
    END IF;

    sql_table(NVL(sql_table.LAST, 0) + 1) :=
    next_row(plsql_code_block, v_end, v_beg);

    v_beg := v_beg + c_BUF_LEN;
    v_accum := v_accum + v_end;

    IF v_accum >= v_loblen THEN
      EXIT;
    END IF;
  END LOOP;

  -- Parse the pl/sql and execute it
   dbms_sql.parse(ds_cur, sql_table, sql_table.FIRST, sql_table.LAST,
  FALSE, dbms_sql.NATIVE);

  v_RetVal := dbms_sql.execute(ds_cur);

   dbms_sql.close_cursor(ds_cur);
END execute_plsql_block;
/

Executing CLOBS Demo Data 		SQL> commit;

SQL> ed

-- delete "commit" and paste in colored section
DECLARE
  clob_in CLOB;
BEGIN
  clob_in := CAST( 'BEGIN
INSERT INTO WORKSTATIONS VALUES (1,1,20075,'''',''Y'',32.97948,-117.2569,'''');
INSERT INTO WORKSTATIONS VALUES (1,10,20077,'''',''N'',32.97125,-117.2675,'''');
INSERT INTO WORKSTATIONS VALUES (1,11,20078,'''',''N'',33.03865,-96.83579,'''');
INSERT INTO WORKSTATIONS VALUES (1,12,20079,'''',''Y'',32.97413,-117.2694,''10.128.48.121'');
INSERT INTO WORKSTATIONS VALUES (1,2,20081,'''',''N'',32.97948,-117.2569,'''');
INSERT INTO WORKSTATIONS VALUES (1,3,20082,'''',''Y'',32.97948,-117.2569,''10.128.0.1'');
INSERT INTO WORKSTATIONS VALUES (1,4,20083,''15689'',''N'',32.98195,-117.2636,'''');
INSERT INTO WORKSTATIONS VALUES (1,5,20085,'''',''Y'',32.98195,-117.2636,''10.128.16.105'');
INSERT INTO WORKSTATIONS VALUES (1,6,20086,'''',''N'',32.97096,-117.2689,'''');
INSERT INTO WORKSTATIONS VALUES (1,7,20077,'''',''Y'',32.97125,-117.2675,''10.128.48.105'');
INSERT INTO WORKSTATIONS VALUES (1,8,20090,'''',''N'',32.97124,-117.2676,'''');
INSERT INTO WORKSTATIONS VALUES (1,9,20092,'''',''N'',32.97023,-117.2688,'''');
INSERT INTO WORKSTATIONS VALUES (10,1,20094,'''',''Y'',61.2224,-149.8047,''10.128.112.1'');
INSERT INTO WORKSTATIONS VALUES (10,2,20095,'''',''N'',61.2224,-149.8047,'''');
INSERT INTO WORKSTATIONS VALUES (10,3,20096,'''',''Y'',61.2224,-149.8047,''10.128.112.113'');
INSERT INTO WORKSTATIONS VALUES (10,4,13545,'''',''Y'',61.14104,-149.9519,''10.128.112.121'');
INSERT INTO WORKSTATIONS VALUES (10,5,20104,'''',''N'',61.2224,-149.8047,'''');
INSERT INTO WORKSTATIONS VALUES (10,6,20106,'''',''Y'',61.21685,-149.8002,''10.128.80.113'');
INSERT INTO WORKSTATIONS VALUES (11,1,20110,'''',''N'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,10,20113,'''',''N'',61.14104,-149.9519,'''');
INSERT INTO WORKSTATIONS VALUES (11,11,20116,'''',''N'',61.14104,-149.9519,'''');
INSERT INTO WORKSTATIONS VALUES (11,12,20117,'''',''Y'',61.137,-149.9395,''10.128.32.193'');
INSERT INTO WORKSTATIONS VALUES (11,13,20118,'''',''Y'',61.137,-149.9395,''10.128.16.129'');
INSERT INTO WORKSTATIONS VALUES (11,14,20119,'''',''Y'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,15,20121,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,16,20122,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,17,13545,'''',''Y'',61.14104,-149.9519,'''');
INSERT INTO WORKSTATIONS VALUES (11,18,19922,'''',''Y'',61.13549,-149.959,''10.128.48.153'');
INSERT INTO WORKSTATIONS VALUES (11,19,19923,'''',''N'',61.13422,-149.962,'''');
INSERT INTO WORKSTATIONS VALUES (11,2,19924,'''',''N'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,20,19925,'''',''N'',61.146,-149.9799,'''');
INSERT INTO WORKSTATIONS VALUES (11,21,19926,'''',''N'',61.146,-149.9799,'''');
INSERT INTO WORKSTATIONS VALUES (11,22,19927,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,23,19928,'''',''N'',61.14104,-149.9519,'''');
INSERT INTO WORKSTATIONS VALUES (11,24,19930,'''',''N'',61.13422,-149.962,'''');
INSERT INTO WORKSTATIONS VALUES (11,25,19931,'''',''N'',61.13678,-149.9644,'''');
INSERT INTO WORKSTATIONS VALUES (11,26,20033,'''',''N'',61.14477,-149.9586,'''');
INSERT INTO WORKSTATIONS VALUES (11,27,20034,'''',''N'',61.13466,-149.975,'''');
INSERT INTO WORKSTATIONS VALUES (11,28,20035,'''',''N'',61.14142,-149.9668,'''');
INSERT INTO WORKSTATIONS VALUES (11,29,20036,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,3,20037,'''',''Y'',61.137,-149.9395,''10.128.16.105'');
INSERT INTO WORKSTATIONS VALUES (11,30,20038,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,31,20039,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,32,20040,'''',''N'',61.13695,-149.9396,'''');
INSERT INTO WORKSTATIONS VALUES (11,33,20042,'''',''N'',61.12887,-149.9578,'''');
INSERT INTO WORKSTATIONS VALUES (11,4,20043,'''',''N'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,5,20044,'''',''Y'',61.137,-149.9395,''10.128.32.129'');
INSERT INTO WORKSTATIONS VALUES (11,6,20045,'''',''N'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,7,20046,'''',''N'',61.137,-149.9395,'''');
INSERT INTO WORKSTATIONS VALUES (11,8,20047,'''',''N'',61.137,-149.9395,'''');
--====
INSERT INTO WORKSTATIONS VALUES (11,9,20048,'''',''Y'',61.137,-149.9395,''10.128.32.169'');
INSERT INTO WORKSTATIONS VALUES (12,1,20051,''15706'',''Y'',32.75604,-117.1201,'''');
INSERT INTO WORKSTATIONS VALUES (12,10,20053,'''',''N'',32.75689,-117.12,'''');
INSERT INTO WORKSTATIONS VALUES (12,100,20054,'''',''N'',32.7596,-117.124,'''');
INSERT INTO WORKSTATIONS VALUES (12,101,20056,'''',''N'',32.75689,-117.129,'''');
INSERT INTO WORKSTATIONS VALUES (12,102,20057,'''',''Y'',32.75677,-117.1241,''10.129.112.25'');
INSERT INTO WORKSTATIONS VALUES (12,103,20058,'''',''Y'',32.75662,-117.124,''10.129.112.33'');
INSERT INTO WORKSTATIONS VALUES (12,104,20060,'''',''N'',32.7571,-117.1242,'''');
INSERT INTO WORKSTATIONS VALUES (12,105,20061,'''',''N'',32.75316,-117.1253,'''');
INSERT INTO WORKSTATIONS VALUES (12,106,20063,'''',''N'',32.76154,-117.1251,'''');
--====
COMMIT;
END;' AS CLOB);

execute_plsql_block(clob_in);

END;
/

set linesize 121

SELECT * FROM workstations;

Final Demo 		CREATE TABLE one (
id    NUMBER(5),
name  VARCHAR2(30),
dob   DATE);

CREATE TABLE two (
id    NUMBER(5),
name  VARCHAR2(30),
dob   DATE);

INSERT INTO one
(id, name, dob)
VALUES
(100, 'Dan Morgan', SYSDATE+10);

INSERT INTO one
(id, name, dob)
VALUES
(200, 'Jack Cline', SYSDATE-10);
COMMIT;

CREATE OR REPLACE PROCEDURE copy_proc(src_tab VARCHAR2,
dest_tab VARCHAR2) IS

col1     NUMBER(5);
col2     VARCHAR2(30);
col3     DATE;
src_cur  INTEGER;
dest_cur INTEGER;
ignore   INTEGER;

BEGIN
  -- open cursor on source table
  src_cur := dbms_sql.open_cursor;

  -- parse the SELECT statement
  dbms_sql.parse(src_cur, 'SELECT id, name, dob FROM ' || src_tab,
  dbms_sql.NATIVE);

  -- define the column type
  dbms_sql.define_column(src_cur, 1, col1);
  dbms_sql.define_column(src_cur, 2, col2, 30);
  dbms_sql.define_column(src_cur, 3, col3);

  ignore := dbms_sql.execute(src_cur);

  -- open cursor on destination table
  dest_cur := dbms_sql.open_cursor;

  -- parse the INSERT statement
  dbms_sql.parse(dest_cur, 'INSERT INTO ' || dest_tab || ' VALUES
  (:n_bind, :c_bind, :d_bind)', dbms_sql.NATIVE);

    LOOP
      -- Fetch a row from the source table
      IF dbms_sql.fetch_rows(src_cur) > 0 THEN
        -- get column values of the row
        dbms_sql.column_value(src_cur, 1, col1);
        dbms_sql.column_value(src_cur, 2, col2);
        dbms_sql.column_value(src_cur, 3, col3);

        -- bind in the values to be inserted
        dbms_sql.bind_variable(dest_cur, ':n_bind', col1);
        dbms_sql.bind_variable(dest_cur, ':c_bind', col2);
        dbms_sql.bind_variable(dest_cur, ':d_bind', col3);
        ignore := dbms_sql.execute(dest_cur);
      ELSE
        -- No more rows to copy
        EXIT;
      END IF;
    END LOOP;

  -- Commit and close all cursors
  COMMIT;
  dbms_sql.close_cursor(src_cur);
  dbms_sql.close_cursor(dest_cur);
EXCEPTION
  WHEN OTHERS THEN
    IF dbms_sql.is_open(src_cur) THEN
      dbms_sql.close_cursor(src_cur);
    END IF;
    IF dbms_sql.is_open(dest_cur) THEN
      dbms_sql.close_cursor(dest_cur);
    END IF;
    RAISE;
END copy_proc;
/

exec copy_proc('ONE', 'TWO');

SELECT * FROM one;
SELECT * FROM two;

Bulk Insert Demo 		CREATE TABLE obj (
objno   INTEGER,
objname VARCHAR2(30));

CREATE OR REPLACE FUNCTION objname(rnum INTEGER) RETURN VARCHAR2 IS
 retval VARCHAR2(30);
BEGIN
  SELECT object_name
  INTO retval
  FROM (
    SELECT rownum X, object_name
    FROM all_objects
    WHERE rownum < 11)
  WHERE x = rnum+1;
  RETURN retval;
END objname;
/

DECLARE
 sqlstr        VARCHAR2(200);
 objno_array   dbms_sql.number_table;
 objname_array dbms_sql.varchar2_table;
 handle        NUMBER;
 dummy         NUMBER;
BEGIN
  FOR i IN 0..9
  LOOP
    objno_array(i) := 1000 + i;
    objname_array(i) := objname(i);
  END LOOP;

  sqlstr := 'INSERT INTO obj VALUES (:num_array, :name_array)';
  handle := dbms_sql.open_cursor;
  dbms_sql.parse(handle, sqlstr, dbms_sql.NATIVE);
  dbms_sql.bind_array(handle, ':num_array', objno_array);
  dbms_sql.bind_array(handle, ':name_array', objname_array);
  dummy := dbms_sql.execute(handle);
  dbms_sql.close_cursor(handle);

EXCEPTION
  WHEN OTHERS THEN
    IF dbms_sql.is_open(handle) THEN
      dbms_sql.close_cursor(handle);
    END IF;
    RAISE;
END;
/

SELECT * FROM obj;
Related Topics
Native Dynamic SQL


Oracle DBMS_SQLHASH Security Crypto

Oracle DBMS_SQLHASH
General Information
Source {ORACLE_HOME}/rdbms/admin/dbmsobtk.sql
Digest Types (DBMS_CRYPTO)
Digest Type | Data Type | Value
HASH_MD4 | BINARY_INTEGER | 1
HASH_MD5 | BINARY_INTEGER | 2
HASH_SH1 | BINARY_INTEGER | 3
Dependent Objects
DBMS_CRYPTO | DBMS_SQL
DBMS_LOB | UTL_RAW
GETHASH

Provides an interface to generate the hash value of the result set returned by a SQL query 		dbms_sqlhash.gethash(
sqltext     IN VARCHAR2,                 -- input sql statement
digest_type IN BINARY_INTEGER,           -- digest algorithm type
chunk_size  IN NUMBER DEFAULT 134217728) -- 128M
RETURN RAW;
-- To create the all_objs table: Click Here

set serveroutput on

DECLARE
 sqlstr VARCHAR2(4000):='SELECT object_name FROM all_objs WHERE rownum = 1';
 digtype PLS_INTEGER := 3;
 RetVal  RAW(2000);
BEGIN
  SELECT dbms_sqlhash.gethash(sqlstr, dbms_crypto.hash_sh1)
  INTO RetVal
  FROM dual;

  dbms_output.put_line(RetVal);
END;
/
Related Topics
DBMS_CRYPTO


Oracle AWR Automatic Workload Repository Grid

Oracle DBMS_WORKLOAD_REPOSITORY
AWR Objects
Source | {ORACLE_HOME}/rdbms/admin/dbmsawr.sql
First Availability | 10.1
Background Process | MMON - Automatic data purging every 7 days by default
Constants
Name | Retention | Data Type | Value
MAX_INTERVAL | 100 years | NUMBER | 52560000
MIN_INTERVAL | 10 minutes | NUMBER | 10
MAX_RETENTION | 100 years | NUMBER | 52560000
MIN_RETENTION | 1 day | NUMBER | 1440
Data Types AWRRPT_TEXT_TYPE
AWRRPT_HTML_TYPE
AWRRPT_TEXT_TYPE_TABLE
AWRRPT_HTML_TYPE_TABLE
SYS AWRRPT_ROW_TYPE
Dependencies
dba_hist_baseline | dba_hist_snapshot
- | -
awrrpt_html_type | plitblm
awrrpt_html_type_table | wrm$_baseline
awrrpt_text_type | wrm$_snapshot
awrrpt_type_table | wrm$_snap_error
dbms_swrf_lib | wrm$_wr_control
dbms_swrf_report_internal |
File that create the AWR schema {ORACLE_HOME}/rdbms/admin/catawr.sql
{ORACLE_HOME}/rdbms/admin/catawrpd.sql
{ORACLE_HOME}/rdbms/admin/catawrtb.sql
{ORACLE_HOME}/rdbms/admin/catawrwv.sql
-- must be run as SYSDBA
ADD_COLORED_SQL (new 11g)

Routine to add a colored SQL ID. If an SQL ID is colored, it will always be captured in every snapshot, independent of its level of activities (i.e. does not have to be a TOP SQL). Capturing will occur if the SQL is found in the cursor cache at snapshot time. 		dbms_workload_repository.add_colored_sql(
sql_id IN VARCHAR2,
dbid   IN NUMBER DEFAULT NULL);
desc wrm$_colored_sql

SELECT * FROM wrm$_colored_sql;

SELECT dbid
FROM gv$database;

SELECT sql_id
FROM gv$sql
WHERE rownum < 101;

exec dbms_workload_repository.add_colored_sql('5rygsj4dbw6jt', 1692970157);

SELECT * FROM wrm$_colored_sql;
ASH_REPORT_HTML (new 11g)

Display the ASH report in HTML 		dbms_workload_repository.ash_report_html(
l_dbid         IN NUMBER,
l_inst_num     IN NUMBER,
l_btime        IN DATE,
l_etime        IN DATE,
l_options      IN NUMBER DEFAULT 0,
l_slot_width   IN NUMBER DEFAULT 0,
l_sid          IN NUMBER DEFAULT NULL,
l_sql_id       IN VARCHAR2 DEFAULT NULL,
l_wait_class   IN VARCHAR2 DEFAULT NULL,
l_service_hash IN NUMBER DEFAULT NULL,
l_module       IN VARCHAR2 DEFAULT NULL,
l_action       IN VARCHAR2 DEFAULT NULL,
l_client_id    IN VARCHAR2 DEFAULT NULL,
l_plsql_entry  IN VARCHAR2 DEFAULT NULL)
RETURN awrrpt_html_type_table PIPELINED;
SELECT dbid
FROM gv$database;

SELECT inst_id
FROM gv$instance;

SELECT sample_time
FROM gv$active_session_history
ORDER BY 1;

set pagesize 0
set linesize 121

spool c:\temp\ash_rpt.html

SELECT * FROM TABLE(dbms_workload_repository.ash_report_html(1692970157, 1, SYSDATE-30/1440, SYSDATE-1/1440));

spool off

Alternative ASH HTML Report 		define report_type = 'html';
define begin_time = '-30'
define duration = '';
define report_name = 'c:\temp\ashrpt.html';
@?/rdbms/admin/ashrpt

Alternative ASH HTML Report 		define report_type = 'html';
define begin_time = '-30'
define duration = '';
define report_name = 'c:\temp\ashrpt.html';
@?/rdbms/admin/ashrpti
ASH_REPORT_TEXT (new 11g)

Display the ASH report in TEXT 		dbms_workload_repository.ash_report_text(
l_dbid         IN NUMBER,
l_inst_num     IN NUMBER,
l_btime        IN DATE,
l_etime        IN DATE,
l_options      IN NUMBER DEFAULT 0,
l_slot_width   IN NUMBER DEFAULT 0,
l_sid          IN NUMBER DEFAULT NULL,
l_sql_id       IN VARCHAR2 DEFAULT NULL,
l_wait_class   IN VARCHAR2 DEFAULT NULL,
l_service_hash IN NUMBER DEFAULT NULL,
l_module       IN VARCHAR2 DEFAULT NULL,
l_action       IN VARCHAR2 DEFAULT NULL,
l_client_id    IN VARCHAR2 DEFAULT NULL,
l_plsql_entry  IN VARCHAR2 DEFAULT NULL)
RETURN awrrpt_text_type_table PIPELINED;
SELECT dbid
FROM gv$database;

SELECT inst_id
FROM gv$instance;

SELECT sample_time
FROM gv$active_session_history
ORDER BY 1;

set pagesize 0
set linesize 121

spool c:\temp\ash_rpt.html

SELECT * FROM TABLE(dbms_workload_repository.ash_report_text(1692970157, 1, SYSDATE-30/1440, SYSDATE-1/1440));

spool off

Alternative ASH Text Report 		define report_type = 'text';
define begin_time = '-30'
define duration = '';
define report_name = 'c:\temp\ashrpt.txt';
@?/rdbms/admin/ashrpt

Alternative ASH Text Report 		define report_type = 'text';
define begin_time = '-30'
define duration = '';
define report_name = 'c:\temp\ashrpt.txt';
@?/rdbms/admin/ashrpti
AWR_DIFF_REPORT_HTML (new 11g)

This table function displays the
AWR Compare Periods Report in HTML format. The output
is one column of VARCHAR2(5000).
         dbms_workload_repository.awr_diff_report_html(
dbid1     IN NUMBER,
inst_num1 IN NUMBER,
bid1      IN NUMBER,
eid1      IN NUMBER,
dbid2     IN NUMBER,
inst_num2 IN NUMBER,
bid2      IN NUMBER,
eid2      IN NUMBER)
RETURN awrrpt_html_type_table PIPELINED;
TBD
AWR_DIFF_REPORT_TEXT (new 11g)

This table function displays the
AWR Compare Periods Report in TEXT format. The output
is one column of VARCHAR2(240). 		dbms_workload_repository.awr_diff_report_text(
awr_diff_report_text(dbid1 IN NUMBER,
inst_num1 IN NUMBER,
bid1      IN NUMBER,
eid1      IN NUMBER,
dbid2     IN NUMBER,
inst_num2 IN NUMBER,
bid2      IN NUMBER,
eid2      IN NUMBER)
RETURN awrdrpt_text_type_table PIPELINED;
TBD
AWR_REPORT_HTML

Display the AWR report in HTML 		dbms_workload_repository.awr_report_html(
l_dbid     IN NUMBER,
l_inst_num IN NUMBER,
l_bid      IN NUMBER,
l_eid      IN NUMBER,
l_options  IN NUMBER DEFAULT 0)
RETURN awrrpt_text_type_table PIPELINED;

awrrpt_text_type_table is VARCHAR2(150)
See AWR Report demo linked at the bottom of the page
AWR_REPORT_TEXT

Display the AWR report in ASCII text 		dbms_workload_repository.awr_report_text(
l_dbid     IN NUMBER,
l_inst_num IN NUMBER,
l_bid      IN NUMBER,
l_eid      IN NUMBER,
l_options  IN NUMBER DEFAULT 0)
RETURN awrrpt_text_type_table PIPELINED;

awrrpt_text_type_table is VARCHAR2(80)
See AWR Report demo linked at the bottom of the page
AWR_SQL_REPORT_HTML (new 11g)

Display the AWR SQL report in HTML 		dbms_workload_repository.awr_sql_report_html(
l_dbid     IN NUMBER,
l_inst_num IN NUMBER,
l_bid      IN NUMBER,
l_eid      IN NUMBER,
l_sqlid    IN VARCHAR2,
l_options  IN NUMBER DEFAULT 0)
RETURN awrrpt_html_type_table PIPELINED;
SELECT dbid
FROM gv$database;

SELECT inst_id
FROM gv$instance;

set pagesize 0
set linesize 121
col instart_fmt noprint;
col inst_name format a12 heading 'Instance';
col db_name format a12 heading 'DB Name';
col snap_id format 99999990 heading 'Snap Id';
col snapdat format a18 heading 'Snap Started' just c;
col lvl format 99 heading 'Snap|Level';
set heading on;
break on inst_name on db_name on host on instart_fmt skip 1;
ttitle off;

SELECT TO_CHAR(s.startup_time,' DD MON "at" HH24:MI:SS') INSTART_FMT,
di.instance_name INST_NAME, di.db_name DB_NAME, s.snap_id SNAP_ID,
TO_CHAR(s.end_interval_time,'DD MON YYYY HH24:MI') SNAPDAT,
s.snap_level LVL
FROM dba_hist_snapshot s, dba_hist_database_instance di
WHERE di.dbid = s.dbid
AND di.instance_number = s.instance_number
AND di.startup_time = s.startup_time
ORDER BY snap_id;

SELECT sql_id
FROM gv$active_session_history
WHERE TRUNC(sql_exec_start) = TRUNC(SYSDATE);

spool c:\temp\awr_sql_rpt.html

SELECT * FROM TABLE(dbms_workload_repository.awr_sql_report_html(1692970157, 1, 1230, 1231, 'a01hp0psv0rrh'));

spool off
AWR_SQL_REPORT_TEXT (new 11g)

Display the AWR SQL report in TEXT 		dbms_workload_repository.awr_sql_report_text(
l_dbid     IN NUMBER,
l_inst_num IN NUMBER,
l_bid      IN NUMBER,
l_eid      IN NUMBER,
l_sqlid    IN VARCHAR2,
l_options  IN NUMBER DEFAULT 0)
RETURN awrsqrpt_text_type_table PIPELINED;
SELECT dbid
FROM gv$database;

SELECT inst_id
FROM gv$instance;

set pagesize 0
set linesize 121
col instart_fmt noprint;
col inst_name format a12 heading 'Instance';
col db_name format a12 heading 'DB Name';
col snap_id format 99999990 heading 'Snap Id';
col snapdat format a18 heading 'Snap Started' just c;
col lvl format 99 heading 'Snap|Level';
set heading on;
break on inst_name on db_name on host on instart_fmt skip 1;
ttitle off;

SELECT TO_CHAR(s.startup_time,' DD MON "at" HH24:MI:SS') INSTART_FMT,
di.instance_name INST_NAME, di.db_name DB_NAME, s.snap_id SNAP_ID,
TO_CHAR(s.end_interval_time,'DD MON YYYY HH24:MI') SNAPDAT,
s.snap_level LVL
FROM dba_hist_snapshot s, dba_hist_database_instance di
WHERE di.dbid = s.dbid
AND di.instance_number = s.instance_number
AND di.startup_time = s.startup_time
ORDER BY snap_id;

SELECT sql_id
FROM gv$active_session_history
WHERE TRUNC(sql_exec_start) = TRUNC(SYSDATE);

spool c:\temp\awr_sql_rpt.txt

SELECT * FROM TABLE(dbms_workload_repository.awr_sql_report_text(1692970157, 1, 1230, 1231, 'a01hp0psv0rrh'));

spool off
CREATE_BASELINE (new 11g parameter)

Creates a baseline returns the baseline_id

Overload 1 		dbms_workload_repository.create_baseline(
start_snap_id IN NUMBER,
end_snap_id   IN NUMBER,
baseline_name IN VARCHAR2,
dbid          IN NUMBER DEFAULT NULL,
expiration    IN NUMBER DEFAULT NULL)
RETURN NUMBER;
SELECT dbid
FROM gv$database;

set linesize 121
col startup_time format a40

SELECT snap_id, startup_time
FROM dba_hist_snapshot
ORDER BY 1,2;

SELECT baseline_name, dbid
FROM dba_hist_baseline;

set serveroutput on

DECLARE
 i dba_hist_baseline.baseline_id%TYPE;
BEGIN
  i := dbms_workload_repository.create_baseline(1199, 1207,
  'UW_BASE', 1692970157);
  dbms_output.put_line(TO_CHAR(i));
END;
/

SELECT baseline_id, baseline_name
FROM dba_hist_baseline;

Overload 2 		dbms_workload_repository.create_baseline(
start_snap_id IN NUMBER,
end_snap_id   IN NUMBER,
baseline_name IN VARCHAR2,
dbid          IN NUMBER DEFAULT NULL
expiration    IN NUMBER DEFAULT NULL);
SELECT dbid
FROM gv$database;

SELECT snap_id, startup_time
FROM dba_hist_snapshot
ORDER BY 1,2;

SELECT baseline_name, dbid
FROM dba_hist_baseline;

exec dbms_workload_repository.create_baseline(1199, 1207, 'UW_BASE', 1692970157);

SELECT baseline_name, dbid
FROM dba_hist_baseline;
CREATE_BASELINE_TEMPLATE (new 11g)

Creates a Baseline Template for a
single time period. There will be a MMON task that will use these inputs to create a Baseline for the time period when the time comes.

Overload 1 		dbms_workload_repository.create_baseline_template(
start_time    IN DATE,
end_time      IN DATE,
baseline_name IN VARCHAR2,
template_name IN VARCHAR2,
expiration    IN NUMBER DEFAULT NULL,
dbid          IN NUMBER DEFAULT NULL);
desc dba_hist_baseline_template

SELECT dbid, template_id, template_name, template_type
FROM dba_hist_baseline_template;

SELECT baseline_name, dbid
FROM dba_hist_baseline;

exec dbms_workload_repository.create_baseline_template(SYSDATE+1/1440, SYSDATE+5/1440, 'UW_BASE2', 'UW_TEMPLATE', 1);

SELECT dbid, template_id, template_name, template_type
FROM dba_hist_baseline_template;

Overload 2 		dbms_workload_repository.create_baseline_template(
day_of_week          IN VARCHAR2,
hour_in_day          IN NUMBER,
duration             IN NUMBER,
start_time           IN DATE,
end_time             IN DATE,
baseline_name_prefix IN VARCHAR2,
template_name        IN VARCHAR2,
expiration           IN NUMBER DEFAULT 35,
dbid                 IN NUMBER DEFAULT NULL);
TBD
CREATE_SNAPSHOT

Create snapshot and return snapshot ID

Overload 1 		dbms_workload_repository.create_snapshot(
flush_level IN VARCHAR2 DEFAULT 'TYPICAL') RETURN NUMBER;
Flush Levels
ALL
TYPICAL
set linesize 121
col begin_interval_time format a30
col end_interval_time format a30

SELECT snap_id, startup_time, begin_interval_time, end_interval_time
FROM dba_hist_snapshot
ORDER BY 1,2;

set serveroutput on

DECLARE
 i dba_hist_snapshot.snap_id%TYPE;
BEGIN
  i := dbms_workload_repository.create_snapshot;
  dbms_output.put_line(TO_CHAR(i));
END;
/

SELECT snap_id, startup_time, begin_interval_time, end_interval_time
FROM dba_hist_snapshot
ORDER BY 1,2;

Overload 2 		dbms_workload_repository.create_snapshot(
flush_level IN VARCHAR2 DEFAULT 'TYPICAL');
Flush Levels
ALL
TYPICAL
set linesize 121
col begin_interval_time format a30
col end_interval_time format a30

SELECT snap_id, startup_time, begin_interval_time, end_interval_time
FROM dba_hist_snapshot
ORDER BY 1,2;

exec dbms_workload_repository.create_snapshot;

SELECT snap_id, startup_time, begin_interval_time, end_interval_time
FROM dba_hist_snapshot
ORDER BY 1,2;
DROP_BASELINE

Drop a baseline 		dbms_workload_repository.drop_baseline(
baseline_name IN VARCHAR2,
cascade       IN BOOLEAN DEFAULT FALSE,
dbid          IN NUMBER  DEFAULT NULL);

Cascade
False | Drop baseline but not snapshots
True | Drops baseline and snapshots
SELECT baseline_name, dbid
FROM dba_hist_baseline;

exec dbms_workload_repository.drop_baseline('UW_BASE', FALSE, 1692970157);

SELECT baseline_name, dbid
FROM dba_hist_baseline;
DROP_BASELINE_TEMPLATE (new 11g)

Drops a Baseline Template 		dbms_workload_repository.drop_baseline_template(
template_name IN VARCHAR2,
dbid          IN NUMBER DEFAULT NULL);
SELECT dbid, template_id, template_name, template_type
FROM dba_hist_baseline_template;

exec dbms_workload_repository.drop_baseline_template('UW_TEMPLATE');

SELECT dbid, template_id, template_name, template_type
FROM dba_hist_baseline_template;
DROP_SNAPSHOT_RANGE

Drop a range of snapshots 		dbms_workload_repository.drop_snapshot_Range(
low_snap_id  IN NUMBER,
high_snap_id IN NUMBER
dbid         IN NUMBER DEFAULT NULL);
set linesize 121
col startup_time format a40

SELECT snap_id, startup_time
FROM dba_hist_snapshot
ORDER BY 1,2;

exec dbms_workload_repository.drop_snapshot_range(1105, 1199);

SELECT snap_id, startup_time
FROM dba_hist_snapshot
ORDER BY 1,2;
MODIFY_BASELINE_WINDOW_SIZE (new 11g)

Modifies the window size for the default moving window baseline

Installation default is 8 days

 dbms_workload_repository.modify_baseline_window_size(
window_size IN NUMBER,
dbid        IN NUMBER DEFAULT NULL );
set linesize 121
col baseline_name format a30

SELECT dbid, baseline_name, baseline_type, moving_window_size
FROM dba_hist_baseline;

exec dbms_workload_repository.modify_baseline_window_size(5);

SELECT dbid, baseline_name, baseline_type, moving_window_size
FROM dba_hist_baseline;

exec dbms_workload_repository.modify_baseline_window_size(8);
MODIFY_SNAPSHOT_SETTINGS

Modifies the interval between snapshots and/or the retention of snapshots in the repository

Overload 1

Note: Some of this functionality also exists in DBMS_MANAGEMENT_PACKS
MODIFY_AWR_SETTINGS proc

 dbms_workload_repository.modify_snapshot_settings(
retention IN NUMBER DEFAULT NULL,
interval  IN NUMBER DEFAULT NULL,
topnsql   IN NUMBER DEFAULT NULL,
dbid      IN NUMBER DEFAULT NULL);

Defaults
Retention | 7 days = 10080 minutes
Interval | 60 minutes *
* Reset to 15-30 min. maximum between snapshots
set linesize 121
col retention format a20
col snap_interval format a20

SELECT retention, snap_interval, topnsql
FROM wrm$_wr_control;

SELECT dbid
FROM gv$database;

exec dbms_workload_repository.modify_snapshot_settings(14400, 20, 1000, 1692970157);

SELECT retention, snap_interval, topnsql
FROM wrm$_wr_control;

Overload 2 		dbms_workload_repository.modify_snapshot_settings(
retention IN NUMBER   DEFAULT NULL,
interval  IN NUMBER   DEFAULT NULL,
topnsql   IN VARCHAR2 DEFAULT NULL,
dbid      IN NUMBER   DEFAULT NULL);

Defaults
Retention | 7 days = 10080 minutes
Interval | 60 minutes *
* Reset to 15-30 min. maximum between snapshots
set linesize 121
col retention format a20
col snap_interval format a20

SELECT retention, snap_interval, topnsql
FROM wrm$_wr_control;

SELECT dbid
FROM gv$database;

exec dbms_workload_repository.modify_snapshot_settings(14400, 20, '1001', 1692970157);

SELECT retention, snap_interval, topnsql
FROM wrm$_wr_control;
REMOVE_COLORED_SQL (new 11g)

Routine to remove a colored SQL ID. If an SQL ID is colored, it will always be captured in every snapshot, independent of its level of activities (i.e. does not have to be a TOP SQL). 		dbms_workload_repository.remove_colored_sql(
sql_id IN VARCHAR2,
dbid   IN NUMBER DEFAULT NULL );
desc wrm$_colored_sql

SELECT * FROM wrm$_colored_sql;

exec dbms_workload_repository.remove_colored_sql('5rygsj4dbw6jt', 1692970157);

SELECT * FROM wrm$_colored_sql;
RENAME_BASELINE (new 11g)

Rename a baseline 		dbms_workload_repository.rename_baseline(
old_baseline_name IN VARCHAR2,
new_baseline_name IN VARCHAR2,
dbid              IN NUMBER DEFAULT NULL);
SELECT dbid, baseline_name, baseline_type
FROM dba_hist_baseline;

exec dbms_workload_repository.rename_baseline('UW_BASE', 'UW_BASE2');

SELECT dbid, baseline_name, baseline_type
FROM dba_hist_baseline;

exec dbms_workload_repository.rename_baseline('UW_BASE', 'UW_BASE');
SELECT_BASELINE_DETAILS (new 11g)

Display baseline statistics 		dbms_workload_repository.select_baseline_metrics(
l_baseline_id IN NUMBER,
l_beg_snap IN NUMBER DEFAULT NULL,
l_end_snap IN NUMBER DEFAULT NULL,
l_dbid     IN NUMBER DEFAULT NULL)
RETURN awrbl_details_type_table PIPELINED;
SELECT dbid, baseline_id, baseline_name, baseline_type
FROM dba_hist_baseline;

set linesize 121
col start_snap_time format a30
col end_snap_time format a30

SELECT *
FROM TABLE(dbms_workload_repository.select_baseline_details(1));
SELECT_BASELINE_METRIC (new 11g)

Display metric stats for a baseline 		dbms_workload_repository.select_baseline_metric(
l_baseline_name IN VARCHAR2,
l_dbid          IN NUMBER DEFAULT NULL,
l_instance_num  IN NUMBER DEFAULT NULL)
RETURN awrbl_metric_type_table PIPELINED;
SELECT dbid, baseline_id, baseline_name, baseline_type
FROM dba_hist_baseline;

set pagesize 0
set linesize 121

SELECT *
FROM TABLE(dbms_workload_repository.select_baseline_metric(0));
Related Topics
AWR Report


Oracle DBMS_XDBUTIL_INT
Version 10.2
General Information
Source | {ORACLE_HOME}/rdbms/admin/prvtxdb0.plb
Dependencies
ALL_POLICIES | DBMS_SYS_SQL | SYS
ALL_TRIGGERS | DBMS_XDBZ0 | XDB$PATCHUPSCHEMA
ALL_USERS | DBMS_XDB_LIB | XMLTYPE
DBMS_SQL | SETMODFLG |
Object Privileges | execute on dbms_xdbutil_int is granted to public
CREATESYSTEMVIRTUALFOLDER

Undocumented 		dbms_xdbutil_int.createsystemvirtualfolder(abspath VARCHAR2)
RETURN BOOLEAN
-- from $ORACLE_HOME/rdbms/admin/catxdbst.sql and xdbu9202.sql

Rem Create OID virtual folder
Rem This step is repeatable.
DECLARE
 ret BOOLEAN;
BEGIN
  ret := dbms_xdbutil_int.createSystemVirtualFolder('/sys/oid');
  IF ret THEN
    dbms_xdb.setacl('/sys/oid', '/sys/acls/bootstrap_acl.xml');
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    ret := FALSE;
END;
/

COMMIT;

Rem Create ASM virtual folder
Rem This step is repeatable.
DECLARE
 ret BOOLEAN;
BEGIN
  ret := dbms_xdbutil_int.createSystemVirtualFolder('/sys/asm');
  IF ret THEN
    dbms_xdb.setacl('/sys/asm', '/sys/acls/all_owner_acl.xml');
END IF;
EXCEPTION
  WHEN OTHERS THEN
    ret := FALSE;
END;
/

COMMIT;
GETNAMESPACE
Get the resolved namespace for an attribute in the list (by position) dbms_xdbutil_int.getnamespace(schemadoc XMLTYPE, inde BINARY_INTEGER)
RETURN VARCHAR2
conn xdb/xdb

set long 1000000

SELECT XMLTYPE(s.getclobval())
FROM xdb$schema s;

SELECT dbms_xdbutil_int.getnamespace(XMLTYPE(s.getclobval()), 0)
FROM xdb$schema s;
ISOBJECTGENERATED
Undocumented: Presumably returns 1 for a generated object, otherwise 0 dbms_xdbutil_int.isobjectgenerated(objname VARCHAR2, schname VARCHAR2)
RETURN NUMBER
SELECT dbms_xdbutil_int.isobjectgenerated('XDB', 'SYS_LOB0000042280C00022$$')
FROM dual;
ISTABLEOUTOFLINE
Undocumented: Presumably returns 1 for an out of line table, otherwise 0 dbms_xdbutil_int.istableoutofline(tablename VARCHAR2, owner VARCHAR2)
RETURN NUMBER
SELECT dbms_xdbutil_int.istableoutofline('XDB$PATH_INDEX_PARAMS', 'XDB')
FROM dual;
ISXMLNESTEDTABLE
Undocumented: Presumably returns 1 if a nested table, otherwise 0 dbms_xdbutil_int.isxmlnestedtable(tablename VARCHAR2, schname VARCHAR2)
RETURN NUMBER
SELECT dbms_xdbutil_int.isxmlnestedtable('XDB$SCHEMA', 'XDB')
FROM dual;
NUMTOHEX

Converts a number to hex 		dbms_xdbutil_int.numtohex(NUMBER) RETURN RAW
SELECT dbms_xdbutil_int.numtohex(42)
FROM dual;

SELECT dbms_xdbutil_int.numtohex(43)
FROM dual;

SELECT dbms_xdbutil_int.numtohex(47)
FROM dual;

SELECT dbms_xdbutil_int.numtohex(48)
FROM dual;
RAWTONUM
Converts RAW to NUMBER | dbms_xdbutil_int.rawtonum(prefix_code RAW) RETURN NUMBER
SELECT utl_raw.cast_to_raw('ABC')
FROM dual;

SELECT dbms_xdbutil_int.rawtonum(utl_raw.cast_to_raw('ABC'))
FROM dual;
SETPRINTMODE
Undocumented | dbms_xdbutil_int.setprintmode(modeval BINARY_INTEGER)
public static String SET_PRINT_MODE="begin
dbms_xdbutil_int.setPrintMode(:1); end;";
XMLSCHEMAGETDEPENDENCYLIST
Undocumented dbms_xdbutil_int.xmlschemagetdependencylist(
schoid RAW, owner VARCHAR2, depclob CLOB) RETURN BINARY_INTEGER
TBD
XMLSCHEMASTRIPUSERNAME

Undocumented 		dbms_xdbutil_int.xmlschemastripusername(
schemadoc XMLTYPE, username VARCHAR2) RETURN CLOB
conn xdb/xdb

set long 1000000
set pagesize 0
set linesize 131
col xml_out format a130
col xml_len format 999999

SELECT XMLTYPE(s.getclobval()) as xml_out
FROM xdb$schema s;

SELECT LENGTH(XMLTYPE(s.getclobval())) as xml_len
FROM xdb$schema s;

SELECT xdb.dbms_xdbutil_int.XMLSchemaStripUsername(XMLTYPE(s.getClobVal()),
'XDB') xml_out
FROM xdb$schema s;

col xml_out format 999999

SELECT LENGTH(
xdb.dbms_xdbutil_int.XMLSchemaStripUsername(XMLTYPE(s.getClobVal()),
'XDB')) xml_len
FROM xdb$schema s;


Oracle DBMS_XMLGEN XML

Oracle DBMS_XMLGEN
Version 10.2
General Information
Note: Converts the results of a SQL query to a canonical XML format. The package takes an arbitrary SQL query as input, converts it to XML format, and returns the result as a CLOB. This package is similar to the DBMS_XMLQUERY package, except that it is written in C and compiled into the kernel. This package can only be run on the database.
Source | $ORACLE_HOME/rdbms/admin/dbmsxml.sql
First Availability | 9.0.1
Constants
Name | Data Type | Value
Conversion or Schema Specs
DTD | NUMBER | 1
NONE | NUMBER | 0
SCHEMA | NUMBER | 2
Conversion Type
ENTITY_DECODE | conversionType | 1
ENTITY_ENCODE | conversionType | 0
Null Handling
DROP_NULLS | NUMBER | 0
EMPTY_TAG | NUMBER | 2
NULL_ATTR | NUMBER | 1
Defined Data Types SUBTYPE ctxHandle IS NUMBER;
SUBTYPE ctxType IS NUMBER;
SUBTYPE conversionType IS NUMBER;

TYPE PARAM_HASH IS TABLE OF VARCHAR2(100)
INDEX BY VARCHAR2(32);
/
Dependencies DBMS_LOB
DBMS_XMLGEN_LIB
URIFACTORY
URITYPE
WRI$_ADV_OBJSPACE_TREND_T
XMLTYPE

Is XDK For PL/SQL Installed 		col comp_name format a45

SELECT comp_name, status, substr(version,1,10) as version
FROM dba_registry;

-- should return
COMP_NAME                          STATUS    VERSION
----------------------             --------  ---------
Oracle Database Catalog Views      VALID     10.2.0.1.0
Oracle Database Packages and Types VALID     10.2.0.1.0
Oracle Workspace Manager           VALID     10.2.0.1.0
JServer JAVA Virtual Machine       VALID     10.2.0.1.0
Oracle XDK                         VALID     10.2.0.1.0
Oracle Database Java Packages      VALID     10.2.0.1.0
Oracle Expression Filter           VALID     10.2.0.1.0
Oracle interMedia                  VALID     10.2.0.1.0
Oracle Data Mining                 VALID     10.2.0.1.0
Oracle Text                        VALID     10.2.0.1.0
Oracle XML Database                VALID     10.2.0.1.0
OLAP Analytic Workspace            VALID     10.2.0.1.0
Oracle OLAP API                    VALID     10.2.0.1.0
OLAP Catalog                       VALID     10.2.0.1.0
Spatial                            VALID     10.2.0.1.0
Oracle Enterprise Manager          VALID     10.2.0.1.0
Oracle Ultra Search                NO SCRIPT 10.1.0.4.0

-- if not installed run
$ORACLE_HOME/rdbms/admin/initxml.sql
Demo Tables -- emp table from SCOTT schema
CREATE TABLE test (testcol VARCHAR2(4000));
clearBindValues
Undocumented | dbms_xmlgen.clearBindValues(ctx IN ctxHandle);
TBD
closeContext

Closes a given context and releases all resources associated with it, including the SQL cursor and bind and define buffers 		dbms_xmlgen.closeContext(ctx IN ctxHandle);
conn scott/tiger

set serveroutput on

DECLARE
 ctx    dbms_xmlgen.ctxHandle;
 emp_no NUMBER := 7369;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno =
  '|| emp_no);
  dbms_xmlgen.closeContext(ctx);
  dbms_output.put_line(ctx);
END;
/
Convert
Converts the XML into the escaped or unescaped XML equivalent

Overload 1 		dbms_xmlgen.convert(
xmlData IN VARCHAR2,
flag    IN NUMBER := ENTITY_ENCODE)
RETURN VARCHAR2;

-- Flags are the Conversion Type constants
TBD
Overload 2 dbms_xmlgen.convert(
xmlData IN CLOB,
flag    IN NUMBER := ENTITY_ENCODE)
RETURN CLOB;

-- Flags are the Conversion Type constants
TBD
getNumRowsProcessed

Gets the number of SQL rows that were processed in the last call to getXML 		dbms_xmlgen.getNumRowsProcessed(ctx IN ctxHandle) RETURN NUMBER;
conn scott/tiger

set serveroutput on

DECLARE
 ctx    dbms_xmlgen.ctxHandle;
 xml    CLOB;
 emp_no NUMBER := 7369;
 i      PLS_INTEGER;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno = '|| emp_no);

  xml := dbms_xmlgen.getXML(ctx);
  i := dbms_xmlgen.getNumRowsProcessed(ctx);
  dbms_output.put_line(TO_CHAR(i));
END;
/
getXML
Gets the XML document

Overload 1 		dbms_xmlgen.getXML(
ctx         IN     ctxHandle,
tmpclob     IN OUT NCOPY CLOB,
dtdOrSchema IN     NUMBER := NONE);
TBD
Overload 2 dbms_xmlgen.getXML(
ctx         IN     ctxHandle,
dtdOrSchema IN number := NONE);
TBD

Overload 3 		dbms_xmlgen.getXML(
sqlQuery    IN VARCHAR2,
dtdOrSchema IN NUMBER := NONE)
RETURN CLOB;
conn scott/tiger

set serveroutput on

DECLARE
 ctx    dbms_xmlgen.ctxHandle;
 xml    CLOB;
 emp_no NUMBER := 7369;
 xmlc   VARCHAR2(4000); -- Required to convert LOB to VARCHAR2
 off    PLS_INTEGER := 1;
 len    PLS_INTEGER := 4000;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno =
  '|| emp_no);
  dbms_output.put_line(ctx);

  xml := dbms_xmlgen.getXML(ctx);
  dbms_output.put_line(xml);

  dbms_xmlgen.closeContext(ctx);

  dbms_lob.read(xml, len, off, xmlc); -- Display first part
  dbms_output.put_line(xmlc);
END;
/
getXMLType
Gets the XML document and returns it as XMLType

Overload 1 		dbms_xmlgen.getXMLType(
ctx         IN     ctxHandle,
tmpxmltype  IN OUT NOCOPY xmltype,
dtdOrSchema IN     NUMBER := NONE);
See newContextFromHierarchy Demo
Overload 2 dbms_xmlgen.getXMLType(
ctx         IN ctxHandle,
dtdOrSchema IN number:= NONE)
RETURN sys.XMLType;
TBD
Overload 3 dbms_xmlgen.getXMLType(
sqlQuery    IN VARCHAR2,
dtdOrSchema IN NUMBER := NONE)
RETURN sys.XMLType;
TBD
newContext

Creates a new context handle

Overload 1 		dbms_xmlgen.newContext(query VARCHAR2) RETURN ctxHandle;
conn scott/tiger

set serveroutput on

DECLARE
 ctx    dbms_xmlgen.ctxHandle;
 emp_no NUMBER := 7369;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno = '|| emp_no);
   dbms_output.put_line(ctx);
   dbms_xmlgen.closeContext(ctx);
END;
/
Overload 2 | dbms_xmlgen.newContext(queryString SYS_REFCURSOR) RETURN ctxHandle;
TBD
newContextFromHierarchy

Undocumented 		dbms_xmlgen.newContextFromHierarchy(queryString IN VARCHAR2)
RETURN ctxHandle;
conn scott/tiger

desc emp

set serveroutput on

DECLARE
 qryctx dbmx_xmlgen.ctxhandle;
 result XMLTYPE;

 PROCEDURE lob_output (p_clob CLOB) IS l_clob CLOB;
  l_clob_length  NUMBER;
  l_iterations   NUMBER;
  l_chunk        VARCHAR2(32767);
  l_chunk_length NUMBER := 32767;
 BEGIN
   l_clob := p_clob;
   l_clob_length := dbms_lob.getlength(l_clob);
   l_iterations := CEIL(l_clob_length / l_chunk_length);

   FOR i IN 0 .. l_iterations - 1 LOOP
     l_chunk := dbms_lob.substr(l_clob,l_chunk_length,i*l_chunk_length+1);
     dbms_output.put_line(l_chunk);
   END LOOP;
 END;
BEGIN
  qryctx := dbms_xmlgen.newcontextFromHierarchy('SELECT level,
  XMLElement("Position", XMLElement("Name", ename), XMLElement("Title",
  job)) FROM emp CONNECT BY PRIOR empno = mgr START WITH mgr is NULL');

  result := dbms_xmlgen.getxmltype(qryctx);

  dbms_xmlgen.closeContext(qryctx);

  lob_output(RESULT.getClobVal());
END;
/
restartQUERY
Restarts the query to start fetching from the beginning | dbms_xmlgen.restartQUERY(ctx IN ctxHandle);
TBD
removeXSLTParam
Undocumented | dbms_xmlgen.removeXSLTParam(ctx IN ctxType, name IN VARCHAR2);
TBD
setBindValue
Undocumented dbms_xmlgen.setBindValue(
ctx       IN ctxHandle,
bindName  IN VARCHAR2,
bindValue IN VARCHAR2);
TBD
setCheckInvalidChars

Sets whether checking for invalid characters such as the NULL character 		dbms_xmlgen.setCheckInvalidChars(ctx IN ctxHandle, chk IN BOOLEAN);
conn scott/tiger

set serveroutput on

DECLARE
  ctx    dbms_xmlgen.ctxHandle;
  emp_no NUMBER := 7369;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno = '|| emp_no);
   dbms_xmlgen.setCheckInvalidChars (ctx, TRUE);
   dbms_xmlgen.closeContext(ctx);
   dbms_output.put_line(ctx);
END;
/
setConvertSpecialChars
Sets whether special characters such as $, which are non-XML characters, should be converted or not to their escaped representation | dbms_xmlgen.setConvertSpecialChars(ctx  IN ctxHandle, conv IN BOOLEAN);
TBD
setIndentationWidth

Undocumented 		dbms_xmlgen.setIndentationWidth(ctx IN ctxHandle, width IN NUMBER);
conn scott/tiger

set serveroutput on

DECLARE
  ctx    dbms_xmlgen.ctxHandle;
  xml    CLOB;
  emp_no NUMBER := 7369;
  xmlc   VARCHAR2(4000); -- Required to convert LOB to VARCHAR2
  off    PLS_INTEGER := 1;
  len    PLS_INTEGER := 4000;
BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno =
  '|| emp_no);

  dbms_xmlgen.setIndentationWidth(ctx, 10);

  dbms_output.put_line(ctx);

  xml := dbms_xmlgen.getXML(ctx);
  dbms_output.put_line(xml);

  dbms_xmlgen.closeContext(ctx);

  dbms_lob.read(xml, len, off, xmlc); -- Display first part
  dbms_output.put_line(xmlc);
END;
/
SetMaxRows

Sets the maximum number of rows to be fetched each time 		dbms_xmlgen.setMaxRows(ctx IN ctxHandle, maxRows IN NUMBER);
set serveroutput on

DECLARE

ctx  dbms_xmlgen.ctxHandle;
xml  CLOB;

xmlc VARCHAR2(4000); -- required to convert LOB to VARCHAR2
off  PLS_INTEGER := 1;
len  PLS_INTEGER := 4000;
i    PLS_INTEGER;

BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp');
  dbms_xmlgen.setMaxRows(ctx, 14);
  xml := dbms_xmlgen.getXML(ctx);
  i := dbms_xmlgen.getNumRowsProcessed(ctx);
  dbms_output.put_line(TO_CHAR(i));
  dbms_xmlgen.closeContext(ctx);

  dbms_lob.read(xml, len, off, xmlc); -- Display first part
  INSERT INTO test VALUES (xmlc);
  commit;
END;
/
SetNullHandling
Sets NULL handling options dbms_xmlgen.setNullHandling(ctx IN ctxHandle, flag IN NUMBER);

-- Flags are the NULL handling constants
TBD
SetPrettyPrinting
Undocumented | dbms_xmlgen.setPrettyPrinting(ctx IN ctxHandle, pp IN BOOLEAN);
TBD
setRowSetTag

Sets the name of the element enclosing the entire result 		dbms_xmlgen.setRowSetTag(
ctx           IN ctxHandle,
rowSetTagName IN VARCHAR2);
set serveroutput on

DECLARE

ctx    dbms_xmlgen.ctxHandle;
xml    CLOB;
emp_no NUMBER := 7369;

xmlc VARCHAR2(4000); -- required to convert LOB to VARCHAR2
off  PLS_INTEGER := 1;
len  PLS_INTEGER := 4000;

BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno = '|| emp_no);
  dbms_xmlgen.setRowSetTag(ctx, 'SRST');
  xml := dbms_xmlgen.getXML(ctx);
  dbms_output.put_line(xml);

  dbms_xmlgen.closeContext(ctx);

  dbms_lob.read(xml, len, off, xmlc); -- Display first part
  dbms_output.put_line(xmlc);
END;
/
setRowTag

Sets the name of the element enclosing each row of the result 		dbms_xmlgen.setRowTag(ctx IN ctxHandle, rowTagName IN VARCHAR2);
set serveroutput on

DECLARE

ctx    dbms_xmlgen.ctxHandle;
xml    CLOB;
emp_no NUMBER := 7369;

xmlc VARCHAR2(4000); -- required to convert LOB to VARCHAR2
off  PLS_INTEGER := 1;
len  PLS_INTEGER := 4000;

BEGIN
  ctx := dbms_xmlgen.newContext('SELECT * FROM emp WHERE empno = '|| emp_no);
  dbms_xmlgen.setRowTag(ctx, 'SRT');
  xml := dbms_xmlgen.getXML(ctx);
  dbms_output.put_line(xml);

  dbms_xmlgen.closeContext(ctx);

  dbms_lob.read(xml, len, off, xmlc); -- Display first part
  dbms_output.put_line(xmlc);
END;
/
setSkipRows
Sets the number of rows to skip every time before generating the XML | dbms_xmlgen.setSkipRows(ctx IN ctxHandle, skipRows IN NUMBER);
TBD
setXSLT
Undocumented

Overload 1 		dbms_xmlgen.setXSLT(ctx IN ctxType, stylesheet IN CLOB);
TBD
Overload 2 | dbms_xmlgen.setXSLT(ctx IN ctxType, stylesheet IN XMLType);
TBD
Overload 3 | dbms_xmlgen.setXSLT(ctx IN ctxType, uri IN VARCHAR2);
TBD
setXSLTParam
Undocumented dbms_xmlgen.setXSLT(
ctx   IN ctxType,
name  IN VARCHAR2,
value IN VARCHAR2);
TBD
useItemTabsForColl
Forces the use of the collection column name appended with the tag _ITEM for collection elements | dbms_xmlgen.useItemTagsForColl(ctx IN ctxHandle);
TBD
useNullAttributeIndicator
Specified whether to use an XML attribute to indicate NULLness, or to do it by omitting the inclusion of the particular entity in the XML document. dbms_xmlgen.useNullAttributeIndicator(
ctx     IN ctxHandle,
attrind IN BOOLEAN := TRUE);
TBD
Related Topics
DBMS_LOB


Oracle DDL Event Trigger ON SCHEMA ON DATABASE DDL

Oracle DDL Event Triggers
General
Dependant Objects trigger$
dba_triggers all_triggers user_triggers
System Privileges create trigger
create any trigger
administer database trigger -- required for ON DATABASE
alter any trigger
drop any trigger

DDL Trigger - Triggering Operations 		BEFORE / AFTER ALTER
BEFORE / AFTER ANALYZE
BEFORE / AFTER ASSOCIATE STATISTICS
BEFORE / AFTER AUDIT
BEFORE / AFTER COMMENT
BEFORE / AFTER CREATE
BEFORE / AFTER DDL
BEFORE / AFTER DISASSOCIATE STATISTICS
BEFORE / AFTER DROP
BEFORE / AFTER GRANT
BEFORE / AFTER NOAUDIT
BEFORE / AFTER RENAME
BEFORE / AFTER REVOKE
BEFORE / AFTER TRUNCATE
AFTER SUSPEND
Demo Table

Demo User 		GRANT create session TO uwclass;
GRANT create procedure TO uwclass;
GRANT create sequence TO uwclass;
GRANT create table TO uwclass;
GRANT create trigger TO uwclass;
GRANT create view TO uwclass;

GRANT select ON gv_$open_cursor TO uwclass;

CONN uwclass/uwclass
Table To Capture DDL Trigger Output CREATE TABLE ddl_log (
operation   VARCHAR2(30),
obj_owner   VARCHAR2(30),
object_name VARCHAR2(30),
sql_text    VARCHAR2(64),
attempt_by  VARCHAR2(30),
attempt_dt  DATE);
DDL Triggers

Trigger To Log A Single DDL Activity On A Schema 		CREATE OR REPLACE TRIGGER <trigger_name>
<BEFORE | AFTER> <triggering_action>
ON <SCHEMA | DATABASE>

DECLARE
 -- variable declarations
BEGIN
  -- trigger code
EXCEPTION
  -- exception handler
END <trigger_name>;
/
CREATE OR REPLACE TRIGGER bcs_trigger
BEFORE CREATE
ON SCHEMA

DECLARE
 oper ddl_log.operation%TYPE;
BEGIN
  INSERT INTO ddl_log
  SELECT ora_sysevent, ora_dict_obj_owner,
  ora_dict_obj_name, NULL, USER, SYSDATE
  FROM dual;
END bcs_trigger;
/

col object_name format a20
SELECT object_name, object_type FROM user_objects;

col triggering_event format a20
SELECT trigger_name, trigger_type,
triggering_event, base_object_type
FROM user_triggers;

SELECT * FROM ddl_log;

CREATE SEQUENCE s_test;

CREATE TABLE t_test (
testcol VARCHAR2(20));

CREATE OR REPLACE VIEW v_test AS
SELECT * FROM t_test;

set linesize 150

SELECT operation, obj_owner, object_name
FROM ddl_log;

TRUNCATE TABLE ddl_log;

conn system/manager

CREATE TABLE uwclass.xyz (
testcol VARCHAR2(20));

conn uwclass/uwclass

SELECT operation, obj_owner, object_name
FROM ddl_log;

TRUNCATE TABLE ddl_log;

Trigger To Log A Single DDL Activity On The Database 		CREATE OR REPLACE TRIGGER <trigger_name>
<BEFORE | AFTER> <triggering_action>
ON <SCHEMA | DATABASE>

DECLARE
 -- variable declarations
BEGIN
  -- trigger code
EXCEPTION
  -- exception handler
END <trigger_name>;
/
conn system/manager

GRANT administer database trigger TO uwclass;

CONN uwclass/uwclass

CREATE OR REPLACE TRIGGER bcd_trigger
BEFORE CREATE
ON DATABASE

DECLARE
 oper ddl_log.operation%TYPE;
BEGIN
  INSERT INTO ddl_log
  SELECT ora_sysevent, ora_dict_obj_owner,
  ora_dict_obj_name, NULL, USER, SYSDATE
  FROM dual;
END bcd_trigger;
/

col object_name format a20
SELECT object_name, object_type FROM user_objects;

col triggering_event format a20
SELECT trigger_name, trigger_type,
triggering_event, base_object_type
FROM user_triggers;

SELECT * FROM ddl_log;

CREATE SEQUENCE s_test;

CREATE TABLE t_test (
testcol VARCHAR2(20));

CREATE OR REPLACE VIEW v_test AS
SELECT * FROM t_test;

set linesize 150

SELECT operation, obj_owner, object_name
FROM ddl_log;

TRUNCATE TABLE ddl_log;

conn system/manager

CREATE TABLE uwclass.xyz (
testcol VARCHAR2(20));

conn uwclass/uwclass

SELECT operation, obj_owner, object_name
FROM ddl_log;

DROP TRIGGER bcd_trigger;
TRUNCATE TABLE ddl_log;

Trigger To Log Multiple DDL Activities 		CREATE OR REPLACE TRIGGER <trigger_name>
<BEFORE | AFTER> <triggering_action> OR <trigger_action>
ON SCHEMA

DECLARE
 -- variable declarations
BEGIN
  -- trigger code
EXCEPTION
  -- exception handlers
END <trigger_name>;
/
desc ddl_log

CREATE OR REPLACE TRIGGER ddl_trigger
BEFORE CREATE OR ALTER OR DROP
ON SCHEMA

DECLARE
 oper ddl_log.operation%TYPE;
 sql_text ora_name_list_t;
 i        PLS_INTEGER;
BEGIN
  SELECT ora_sysevent
  INTO oper
  FROM dual;

  i := sql_txt(sql_text);

  IF oper IN ('CREATE', 'DROP') THEN
    INSERT INTO ddl_log
    SELECT ora_sysevent, ora_dict_obj_owner,
    ora_dict_obj_name, sql_text(1), USER, SYSDATE
    FROM dual;
  ELSIF oper = 'ALTER' THEN
    INSERT INTO ddl_log
    SELECT ora_sysevent, ora_dict_obj_owner,
    ora_dict_obj_name, sql_text(1), USER, SYSDATE
    FROM sys.gv_$sqltext
    WHERE UPPER(sql_text) LIKE 'ALTER%'
    AND UPPER(sql_text) LIKE '%NEW_TABLE%';
  END IF;
END ddl_trigger;
/

col operation format a20
col obj_owner format a10

SELECT * FROM ddl_log;

alter system flush shared_pool;

CREATE TABLE new_table (
charcol VARCHAR(20));

SELECT * FROM ddl_log;

ALTER TABLE new_table
ADD (numbcol NUMBER(10));

SELECT * FROM ddl_log;

DROP TABLE new_table PURGE;

SELECT * FROM ddl_log;

TRUNCATE TABLE ddl_log;

DDL Trigger To Stop And Log Attempts To Drop Or Truncate

Requires the stored procedure below is created first 		CREATE OR REPLACE TRIGGER save_our_db
BEFORE DROP OR TRUNCATE
ON SCHEMA

DECLARE
 oper ddl_log.operation%TYPE;
BEGIN
  SELECT ora_sysevent
  INTO oper
  FROM dual;

  log_proc(ora_sysevent, ora_dict_obj_owner, ora_dict_obj_name);

  IF oper = 'DROP' THEN
    RAISE_APPLICATION_ERROR(-20998, 'Attempt To Drop
    In Production Has Been Logged');
  ELSIF oper = 'TRUNCATE' THEN
    RAISE_APPLICATION_ERROR(-20999, 'Attempt To Truncate A
    Production Table Has Been Logged');
  END IF;
END save_our_db;
/

-- be sure log_proc is built first (see below)
SELECT * FROM ddl_log;

DROP TRIGGER ddl_trigger;

SELECT * FROM ddl_log;

ALTER TRIGGER save_our_db DISABLE;

DROP TRIGGER ddl_trigger;

SELECT * FROM ddl_log;

TRUNCATE TABLE ddl_log;

SELECT * FROM ddl_log;

ALTER TRIGGER save_our_db ENABLE;

DROP VIEW v_test;

SELECT * FROM ddl_log;

SELECT object_name FROM user_objects;

DROP SEQUENCE v_test;

SELECT * FROM ddl_log;

SELECT object_name FROM user_objects;

DROP TRIGGER save_our_db;
TRUNCATE TABLE ddl_log;

Logging Procedure 		CREATE OR REPLACE PROCEDURE log_proc (
ose  ddl_log.operation%TYPE,
odoo ddl_log.obj_owner%TYPE,
odon ddl_log.object_name%TYPE)
IS

PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN
  INSERT INTO ddl_log
  SELECT ora_sysevent, ora_dict_obj_owner,
  ora_dict_obj_name, 'Not Allowed', USER, SYSDATE
  FROM dual;
  COMMIT;
END log_proc;
/

DDL Trigger To Prevent Creating Objects That Whose Names Begin With The Letter 'X' 		CREATE OR REPLACE TRIGGER no_xtabs
BEFORE CREATE
ON SCHEMA

DECLARE
 x user_tables.table_name%TYPE;
BEGIN
  SELECT ora_dict_obj_name
  INTO x
  FROM dual;

  IF SUBSTR(x, 1, 1) = 'X' THEN
    RAISE_APPLICATION_ERROR(-20099, 'Table Names Can Not
    Start With The Letter X');
  END IF;
END no_xtabs;
/

CREATE TABLE ztest (
testcol VARCHAR2(20));

CREATE TABLE xtest (
testcol VARCHAR2(20));

Demo of an application that identifies and logs all DDL 		conn / as sysdba

CREATE TABLESPACE logging
DATAFILE 'c:\temp\logtsp01.dbf' SIZE 100M
EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 64K;

CREATE USER loguser
IDENTIFIED BY loguser
DEFAULT TABLESPACE logging
TEMPORARY TABLESPACE temp
QUOTA 0 ON SYSTEM
QUOTA UNLIMITED ON logging;

CREATE TABLE loguser.ddl_log (
user_name     VARCHAR2(30),
ddl_date      DATE,
ddl_type      VARCHAR2(30),
object_type   VARCHAR2(18),
owner         VARCHAR2(30),
object_name   VARCHAR2(128))
TABLESPACE logging;

CREATE OR REPLACE TRIGGER ddl_trig
AFTER DDL
ON DATABASE

BEGIN
  INSERT INTO loguser.ddl_log
  (user_name, ddl_date, ddl_type,
   object_type, owner,
   object_name)
  VALUES
  (ora_login_user, SYSDATE, ora_sysevent,
   ora_dict_obj_type, ora_dict_obj_owner,
   ora_dict_obj_name);
END ddl_trig;
/
Related Topics
Instead Of Trigger
System Events
System Triggers
Table Triggers


Oracle Deadlocks
Demo

Deadlocks Demo 		-- session 1
CREATE TABLE deadlock (
id NUMBER, fld VARCHAR2(1));

INSERT INTO deadlock VALUES (1,'A');
INSERT INTO deadlock values (2,'B');
COMMIT;

SELECT * FROM deadlock;

UPDATE deadlock
SET fld = 'M'
WHERE id = 1;

-- session 2
UPDATE deadlock
SET fld = 'N'
WHERE id = 2;

-- session 1
UPDATE deadlock
SET fld = 'X'
WHERE id = 2;

-- session as SYS
conn / as sysdba

SELECT (
  SELECT username
  FROM gv$session
  WHERE sid=a.sid) blocker,
  a.sid, ' is blocking ', (
  SELECT username
  FROM gv$session
  WHERE sid=b.sid) blockee,
  b.sid
FROM gv$lock a, gv$lock b
WHERE a.block = 1
AND b.request > 0
AND a.id1 = b.id1
AND a.id2 = b.id2;

-- session 2
UPDATE DEADLOCK
SET fld = 'Y'
WHERE id = 1;

SQL> ORA-00060: deadlock detected while waiting for resource

ROLLBACK;

GENERAL SELECT FOR UPDATE
View for viewing locks conn / as sysdba

GRANT SELECT ON dba_lock TO uwclass;
GRANT SELECT ON v_$mystat TO uwclass;

conn uwclass/uwclass

SELECT DISTINCT sid FROM gv$mystat;

set linesize 121
col object_name format a20
col lock_type format a15
col mode_held format a15
col mode_requested format a20
col blocking_others format a20

CREATE OR REPLACE VIEW locked_objs AS
SELECT o.object_name, l.lock_type, l.mode_held,
l.mode_requested, l.blocking_others
FROM dba_lock l, user_objects o
WHERE l.lock_id1 = o.object_id
AND session_id = 139;

FOR UPDATE locking demo 		SELECT *
FROM locked_objs;

SELECT *
FROM deadlock;

SELECT *
FROM locked_objs;

SELECT *
FROM deadlock
FOR UPDATE;

SELECT *
FROM locked_objs;

COMMIT;

SELECT *
FROM locked_objs;

SELECT *
FROM deadlock
FOR UPDATE;

SELECT *
FROM locked_objs;

ROLLBACK;

SELECT *
FROM locked_objs;
SELECTIVE SELECT FOR UPDATE

SELECT FOR UPDATE with WHERE clause 		-- session 1

CREATE TABLE deadlock (
id NUMBER, fld VARCHAR2(1));

INSERT INTO deadlock VALUES (1,'A');
INSERT INTO deadlock values (2,'B');
INSERT INTO deadlock VALUES (3,'C');
INSERT INTO deadlock values (4,'D');
COMMIT;

SELECT *
FROM deadlock;

SELECT *
FROM locked_objs;

SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE;

SELECT *
FROM locked_objs; 		-- session 2

UPDATE deadlock
SET fld = 'Z'
WHERE id = 3;

UPDATE deadlock
SET fld = 'Z'
WHERE id = 1;
ROLLBACK;
FOR UPDATE WITH NOWAIT
NOWAIT Demo

-- continuing from above demo 		SELECT <column_names>
FROM <table_name>
FOR UPDATE NOWAIT;
ROLLBACK;
SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE;
SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE NOWAIT;
FOR UPDATE WITH WAIT
WAIT Demo

-- continuing from above demo 		SELECT <column_names>
FROM <table_name>
FOR UPDATE WAIT <wait_period_in_seconds>;
SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE WAIT;

SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE WAIT 5;
FOR UPDATE WITH NOWAIT SKIP LOCKED
Skip Locked Demo

-- continuing from above demo 		-- this is an undocumented feature.

SELECT <column_names>
FROM <table_name>
FOR UPDATE NOWAIT SKIP LOCKED;
SELECT *
FROM deadlock
WHERE id IN (1, 2)
FOR UPDATE NOWAIT SKIP LOCKED;

SELECT *
FROM deadlock
FOR UPDATE NOWAIT SKIP LOCKED;
Related Topics
Locks
Update


ORACLE DECODE CASE SQL PL/SQL

Oracle DECODE & CASE Functions
Note: Decode and Case are very similar in their appearance but can produce very different results.
Demo Tables & Data
Airplanes Table Locations Table All other tables
DECODE (overload 1) | standard.decode(expr NUMBER, pat NUMBER, res NUMBER) RETURN NUMBER;
DECODE (overload 2) standard.decode(
expr NUMBER,
pat  NUMBER,
res  VARCHAR2 CHARACTER SET ANY_CS)
return VARCHAR2 CHARACTER SET res%CHARSET;
DECODE (overload 3) | standard.decode(expr NUMBER, pat NUMBER, res DATE) RETURN DATE;
DECODE (overload 4) standard.decode(
expr VARCHAR2 CHARACTER SET ANY_CS,
pat  VARCHAR2 CHARACTER SET expr%CHARSET,
res  NUMBER)
RETURN NUMBER;
DECODE (overload 5) standard.decode(
expr VARCHAR2 CHARACTER SET ANY_CS,
pat  VARCHAR2 CHARACTER SET expr%CHARSET,
res  VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET res%CHARSET;
DECODE (overload 6) standard.decode(
expr VARCHAR2 CHARACTER SET ANY_CS,
pat  VARCHAR2 CHARACTER SET expr%CHARSET,
res  DATE)
RETURN DATE;
DECODE (overload 7) | standard.decode(expr DATE, pat DATE, res NUMBER) RETURN NUMBER;
DECODE (overload 8) standard.decode(
expr DATE,
pat  DATE,
res  VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET res%CHARSET;
DECODE (overload 9) | standard.decode( expr DATE, pat DATE, res DATE) RETURN DATE;
DECODE (overload 10) | standard.decode(expr OBJECT, pat  OBJECT, res OBJECT) RETURN OBJECT;
DECODE (overload 11) standard.decode(expr UNDEFINED, pat UNDEFINED, res UNDEFINED)
RETURN UNDEFINED;
Decode Built-in Function

Simple DECODE 		SELECT DECODE (value, <if this value>, <return this value>)
FROM dual;
SELECT program_id,
  DECODE(customer_id, 'AAL', 'American Airlines') AIRLINE,
  delivered_date
FROM airplanes
WHERE ROWNUM < 11;

More Complex DECODE 		SELECT DECODE (value,<if this value>,<return this value>,
                     < if this value>,<return this value>,
                      ....)
FROM dual;
SELECT program_id,
       DECODE(customer_id,
              'AAL', 'American Airlines',
              'ILC', 'Intl. Leasing Corp.',
              'NWO', 'Northwest Orient',
              'SAL', 'Southwest Airlines',
              'SWA', 'Sweptwing Airlines',
              'USAF', 'U.S. Air Force') AIRLINE,
       delivered_date
FROM airplanes
WHERE ROWNUM < 11;

DECODE with DEFAULT 		SELECT DECODE (value,<if this value>,<return this value>,
                     <if this value>,<return this value>,
                     ....
                     <otherwise this value>)
FROM dual;
SELECT program_id,
       DECODE(customer_id,
             'AAL', 'American Airlines',
             'ILC', 'Intl. Leasing Corp.',
             'NWO', 'Northwest Orient',
             'SAL', 'Southwest Airlines',
             'SWA', 'Sweptwing Airlines',
             'USAF', 'United States Air Force',
             'Not Known') AIRLINE,
       delivered_date
FROM airplanes
WHERE ROWNUM < 11;
Note: The following crosstabulation is the standard for 10g or earlier. In 11g use the PIVOT and UNPIVOT operators
Simple DECODE Crosstab

Note how each decode only looks at a single possible value and turns it into a new column 		SELECT program_id,
       DECODE(customer_id, 'AAL', 'AAL') AMERICAN,
       DECODE(customer_id, 'DAL', 'DAL') DELTA,
       DECODE(customer_id, 'NWO', 'NWO') NORTHWEST,
       DECODE(customer_id, 'ILC', 'ILC') INTL_LEASING
FROM airplanes
WHERE rownum < 20;

DECODE as an in-line view with crosstab summation 		The above DECODE, in blue, used as an in-line view
SELECT program_id,
       COUNT (AMERICAN) AAL,
       COUNT (DELTA) DAL,
       COUNT (NORTHWEST) NWO,
       COUNT(INTL_LEASING) ILC
FROM (
   SELECT program_id,
          DECODE(customer_id, 'AAL', 'AAL') AMERICAN,
          DECODE(customer_id, 'DAL', 'DAL') DELTA,
          DECODE(customer_id, 'NWO', 'NWO') NORTHWEST,
          DECODE(customer_id, 'ILC', 'ILC') INTL_LEASING
   FROM airplanes)
GROUP BY program_id;

Query for DECODE demo 		CREATE TABLE stores (
store_name      VARCHAR2(20),
region_dir      NUMBER(5),
region_mgr      NUMBER(5),
store_mgr1      NUMBER(5),
store_mgr2      NUMBER(5),
asst_storemgr1  NUMBER(5),
asst_storemgr2  NUMBER(5),
asst_storemgr3  NUMBER(5));

INSERT INTO stores
VALUES ('San Francisco',100,200,301,302,401,0,403);

INSERT INTO stores
VALUES ('Oakland',100,200,301,0,404,0,0);

INSERT INTO stores
VALUES ('Palo Alto',100,200,0,305,0,405,406);

INSERT INTO stores
VALUES ('Santa Clara',100,250,0,306,0,0,407);
COMMIT;

SELECT DECODE(asst_storemgr1, 0,
       DECODE(asst_storemgr2, 0,
       DECODE(asst_storemgr3, 0, 0, asst_storemgr3),
       asst_storemgr2), asst_storemgr1) ASST_MANAGER,
       DECODE(store_mgr1,0, DECODE(store_mgr2,0, 0, store_mgr2),
       store_mgr1) STORE_MANAGER,
       REGION_MGR,
       REGION_DIR
FROM stores;

DECODE with Summary Function 		SELECT SUM(CA_COUNT) CA, SUM(TX_COUNT) TX
FROM (
   SELECT state,
   DECODE(state, 'CA', COUNT(*), 0) CA_COUNT,
   DECODE(state, 'TX', COUNT(*), 0) TX_COUNT
   FROM locations
   GROUP BY state);

DECODE in the WHERE clause 		set serveroutput on

DECLARE
 posn  PLS_INTEGER := 0;
 empid PLS_INTEGER := 178;
 x     NUMBER;
BEGIN
  SELECT NVL(SUM(ah.quantity * ah.saleprice * ap.payoutpct), 0)
  INTO x
  FROM accessoryhistory ah, payoutpercentage ap,
  sku s, store st
  WHERE empid = DECODE(posn,
                          0, st.areadir,
                          1, st.areamgr,
                          2, NVL(st.storemgr1, st.storemgr2),
                          3, NVL(st.asstmgr1, NVL(st.asstmgr2,
                       st.asstmgr3)))
   AND ah.statustype IN ('ACT', 'DEA')
  AND ah.store = st.store
  AND s.dbid = ah.dbid
  AND s.sku = ah.sku
  AND ap.productgroup = s.productgroup
  AND ap.position = posn;

  dbms_output.put_line(x);
END;
/

DECODE Altered WHERE Clause

Thanks to HJL 		CREATE TABLE test (
pubdate  DATE,
compdate DATE,
valuecol NUMBER(5));

INSERT INTO test VALUES (TRUNC(SYSDATE), TRUNC(SYSDATE+300), 1);
INSERT INTO test VALUES (TRUNC(SYSDATE-300), TRUNC(SYSDATE), 9);
COMMIT;

SELECT * FROM test;

CREATE OR REPLACE PROCEDURE testproc (
StartDate DATE, EndDate DATE, DateType IN VARCHAR2) IS

 i PLS_INTEGER;
BEGIN
  SELECT valuecol
  INTO i
  FROM test
  WHERE DECODE(DateType, 'AA',compdate, 'BB', pubdate, compdate) <= EndDate
  AND DECODE(DateType, 'AA', compdate, 'BB', pubdate, compdate) >= StartDate;

  dbms_output.put_line(TO_CHAR(i));
END testproc;
/

set serveroutput on

exec testproc(TRUNC(SYSDATE), TRUNC(SYSDATE), 'BB');
CASE

Simple CASE Demo 		SELECT CASE WHEN (<column_value>= <value>) THEN
            WHEN (<column_value> = <value>) THEN
            ELSE <value>
FROM <table_name>;
SELECT line_number,
  CASE WHEN (line_number = 1) THEN 'One'
       WHEN (line_number = 2) THEN 'Two'
       ELSE 'More Than Two'
  END AS RESULTSET
FROM airplanes;

More Complex CASE Demo With Between 		SELECT CASE WHEN (<column_value> BETWEEN <value>
             AND <value>) THEN
            WHEN (<column_value>
            BETWEEN <value> AND <value>) THEN
            ELSE <value>
FROM <table_name>;
SELECT line_number,
  CASE WHEN (line_number BETWEEN 1 AND 10) THEN 'One'
       WHEN (line_number BETWEEN 11 AND 100) THEN 'Big'
  ELSE 'Bigger'
  END
FROM airplanes;

More Complex CASE Demo With Booleans 		SELECT CASE WHEN (<column_value> <= <value>) THEN
            WHEN (<column_value> <= <value>) THEN
            ELSE <value>
FROM <table_name>;
SELECT line_number,
  CASE WHEN (line_number < 10) THEN 'Ones'
       WHEN (line_number < 100) THEN 'Tens'
       WHEN (line_number < 1000) THEN 'Hundreds'
  ELSE 'Thousands'
  END RESULT_SET
FROM airplanes;

The above demo turned into a view 		CREATE OR REPLACE VIEW line_number_view AS
SELECT line_number,
  CASE WHEN (line_number < 10) THEN 'Ones'
       WHEN (line_number < 100) THEN 'Tens'
       WHEN (line_number < 1000) THEN 'Hundreds'
  ELSE 'Thousands'
  END RESULT_SET
FROM airplanes;

CASE with BOOLEANS 		set serveroutput on

DECLARE
 boolvar BOOLEAN := TRUE;
BEGIN
  dbms_output.put_line(CASE boolvar WHEN TRUE THEN 'TRUE' WHEN FALSE THEN
  'FALSE' END);
END;
/
CASE - DECODE Comparison

The same functionality written using both functions 		SELECT parameter, DECODE(SIGN(parameter-1000),-1,'C','P') AS BAND
FROM parameter_table;

SELECT parameter,
       CASE WHEN parameter < 1000 THEN 'C' ELSE 'P' END AS BAND
FROM parameter_table;

Another example using SIGN 		SELECT min_cached, COUNT(*), ROUND(AVG(executions),2)
FROM (
  SELECT DECODE(min_cached,
                         0, '1) 00-01 min',
                         1, '2) 01-02min',
                         2, '2) 01-02min',
         DECODE(SIGN(min_cached -6), -1, '3) 03-05min',
         DECODE(SIGN(min_cached -16), -1, '4) 06-15min',
         DECODE(SIGN(min_cached -31), -1, '5) 16-30min',
         DECODE(SIGN(min_cached -61), -1, '6) 31-60min',
         DECODE(SIGN(min_cached-121), -1, '7) 1-2hrs',
                                          '8) 2 hrs+ ')))))) min_cached,
  executions
  FROM (
    SELECT ROUND((SYSDATE -
    TO_DATE(first_load_time,'YYYY-MM-DD/HH24:MI:SS'))*24*60) min_cached,
    executions
    FROM gv$sqlarea
    WHERE parsing_user_id != 0)
    )
GROUP BY min_cached
Related Topics
PIVOT
Select
String Functions
UN PIVOT


Oracle Directories Directory

Oracle Directories
General
Related Data Dictionary Objects
dir$ | all_directories | ku$_directory_t
 | dba_directories | ku$_directory_view
System Privileges GRANT create any directory TO <user_name>;
GRANT drop any directory TO <user_name>;
GRANT create any directory TO uwclass;
GRANT drop any directory TO uwclass;
Create Directory

Create A Directory 		CREATE OR REPLACE DIRECTORY <directory_name> AS '<operating_system_path>';
conn / as sysdba

desc dba_directories

set linesize 121
col owner format a15
col directory_name format a20
col directory_path format a70

SELECT *
FROM dba_directories;

CREATE OR REPLACE DIRECTORY ctemp AS 'c:\temp';

SELECT *
FROM dba_directories;
Granting Privileges To A Directory

Grant Read On A Directory 		GRANT READ ON DIRECTORY <directory_name> TO <schema_name>
col grantor format a20
col grantee format a20
col table_schema format a20
col table_name format a20
col privilege format a10

SELECT grantor, grantee, table_schema, table_name, privilege
FROM all_tab_privs
WHERE table_name = 'CTEMP';

GRANT READ ON DIRECTORY ctemp TO uwclass;

SELECT grantor, grantee, table_schema, table_name, privilege
FROM all_tab_privs
WHERE table_name = 'CTEMP';
Grant Write On A Directory | GRANT WRITE ON DIRECTORY <directory_name> TO <schema_name>
GRANT WRITE ON DIRECTORY ctemp TO uwclass;

SELECT grantor, grantee, table_schema, table_name, privilege
FROM all_tab_privs
WHERE table_name = 'CTEMP';
Revoke Read On A Directory | REVOKE READ ON DIRECTORY <directory_name> FROM <schema_name>
REVOKE READ ON DIRECTORY ctemp FROM uwclass;
Revoke Write On A Directory | REVOKE WRITE ON DIRECTORY <directory_name> FROM <schema_name>
REVOKE WRITE ON DIRECTORY ctemp FROM uwclass;
Drop Directory
Drop A Directory | DROP DIRECTORY <directory_name>;
SELECT *
FROM dba_directories;

DROP DIRECTORY ctemp;

SELECT *
FROM dba_directories;
Related Topics
ADDM
DataPump
DBMS_FILE_TRANSFER
DBMS_HPROF
DBMS_LOB
External Tables
Intermedia Audio
Intermedia Video
Transportable Tablespaces
UTL_FILE


Oracle DIUTIL
General Information
Source | {ORACLE_HOME}/rdbms/admin/diutil.sql
First Available | 7.3.4
Constants
Name | Data Type | Value
s_ok (successful) | NUMBER | 0
s_notinpackage (package found / proc not found) | NUMBER | 6
s_stubtoolong (subprogram not found) | NUMBER | 3
s_logic (logic error) | NUMBER | 4
s_other (other error) | NUMBER | 5
s_defaultval (true if parameters have default values) | NUMBER | 8
s_notv6compat (found non v6 TYPE OR construct) | NUMBER | 7
char_for_varchar2 | BOOLEAN |
libunit_type_spec | NUMBER | 1
libunit_type_body | NUMBER | 2
load_source_yes | NUMBER | 1
load_source_no | NUMBER | 2
Defined Data Types SUBTYPE ptnod IS pidl.ptnod;

SUBTYPE ub4 IS pidl.ub4;
Dependencies
DIANA PIDL SUBPTXT2
Exceptions
Error Code | Name
N/A | e_subpnotfound
N/A | e_notinpackage
N/A | e_nopriv
N/A | e_stubtoolong
N/A | e_notv6compat
N/A | e_other
ATTRIBUTE_USE_STATISTICS
Reports libunit's attribute count and limit diutil.attribute_use_statistics(
libunit_node    IN  ptnod,
attribute_count OUT ub4,
attribute_limit OUT ub4);
Source code included in package
BOOL_TO_INT

Translates 3-valued BOOLEAN TO NUMBER FOR USE in sending BOOLEAN parameter / RETURN VALUES between pls v1 (client) AND pls v2. since sqlnet. Has no BOOLEAN bind variable TYPE, we encode booleans AS false = 0, true = 1, NULL = NULL FOR network transfer AS NUMBER 		diutil.bool_to_int( b BOOLEAN) RETURN NUMBER;
set serveroutput on

DECLARE
 b BOOLEAN := TRUE;
BEGIN
  IF diutil.bool_to_int(b) = 1 THEN
    dbms_output.put_line('First it is TRUE');

    b := FALSE;
    IF diutil.bool_to_int(b) = 0 THEN
      dbms_output.put_line('Then it is FALSE');
    END IF;
  ELSE
    dbms_output.put_line('FALSE');
  END IF;
END;
/
GET_D
Returns the root OF the diana OF a libunit, given name AND usr. name will be first folded TO upper CASE IF NOT IN quotes, ELSE stripped OF quotes. diutil.get_d(
name         IN     VARCHAR2,
usr          IN     VARCHAR2,
dbname       IN     VARCHAR2,
dbowner      IN     VARCHAR2,
status       IN OUT ub4,
nod             OUT ptnod,
libunit_type IN     NUMBER := libunit_type_spec,
load_source  IN     NUMBER := load_source_no);
Source code included in package
GET_DIANA

Returns the root OF the diana OF a libunit, given name AND usr. name will be first folded TO upper CASE IF NOT IN quotes, ELSE stripped OF quotes. will trace synonym links. 		diutil.get_diana(
name         IN     VARCHAR2,
usr          IN     VARCHAR2,
dbname       IN     VARCHAR2,
dbowner      IN     VARCHAR2,
status       IN OUT ub4,
nod          IN OUT ptnod,
libunit_type IN     NUMBER := libunit_type_spec,
load_source  IN     NUMBER := load_source_no);
Source code included in package
INT_TO_BOOL

Translates 3-valued NUMBER encoding to BOOLEAN for use in sending BOOLEAN parameter / RETURN VALUES between pls v1 (client) AND pls v2. since sqlnet has no BOOLEAN bind variable TYPE, we encode booleans AS false = 0, true = 1, NULL = NULL FOR network transfer AS NUMBER 		diutil.int_to_bool
set serveroutput on

DECLARE
 i PLS_INTEGER := 1;
BEGIN
  IF diutil.int_to_bool(i) THEN
    dbms_output.put_line('First it is TRUE');

    i := 0;
    IF NOT diutil.int_to_bool(i) THEN
      dbms_output.put_line('Then it is FALSE');
    END IF;
  ELSE
    dbms_output.put_line('FALSE');
  END IF;
END;
/
NODE_USE_STATISTICS
Reports libunit's node count and limit diutil.node_use_statistics(
libunit_node IN  ptnod,
node_count   OUT ub4,   -- diana nodes
node_limit   OUT ub4);
Source code included in package
SUBPTXT
returns the text OF a subprogram source (describe). diutil.subptxt(
name    IN     VARCHAR2,
subname IN     VARCHAR2,
usr     IN     VARCHAR2,
dbname  IN     VARCHAR2,
dbowner IN     VARCHAR2,
txt     IN OUT VARCHAR2,
status  IN OUT ub4);
Source code included in package
Thanks to Maxim Demenko for pointing me to this package


Oracle Exception Handing WHEN OTHERS SQLCODE SQLERRM PRAGMA INIT

Oracle Exception Handling
General
NOTE: How Oracle Does Implicit Rollbacks

Before executing an INSERT, UPDATE, or DELETE statement, Oracle marks an implicit savepoint (unavailable to you). If the statement fails, Oracle rolls back to the savepoint. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, if the statement raises an unhandled exception, the host environment determines what is rolled back.

If you exit a stored subprogram with an unhandled exception, PL/SQL does not assign values to OUT parameters. Also, PL/SQL does not roll back database work done by the subprogram.

At the level of the SQL*Plus prompt, every update/insert/delete has one implicit savepoint, and also the invocation of any unnamed block. Below that, the unnamed block itself has 'sub' savepoints - one for each insert/update/delete statement in it, and one for each subprogram unit. And so on down the line.

If an error occurs, and that error is handled at any level by the time we're back at the SQL*Plus prompt, we only rollback to the immediate savepoint at the start of the update/insert/delete that errors. Otherwise we rollback to the top-level 'virtual' savepoint currently in existence, which is my offending unnamed block. That is, a handled error is handled and so can be dealt with without rolling back all the way to the top. It is handled and the transaction proceeds.

Commits define the end of a transaction (and start of a new one) - rollbacks only define the end of a transaction if they rollback to the last commit, rather than savepoint (whether explicit or implicit).

I came to my 'version' from the following by no means exhaustive tests:

CASE 1:
I created a table a with one column, a1 number, and at the sqlplus prompt inserted a row with a1 = 1.
I then ran that unnamed block I referred in an earlier post that, without an exception handler, does the following:

INSERT INTO a VALUES (2);
INSERT INTO a VALUES (3);
INSERT INTO a VALUES ('a');

As expected I get an unhandled error on the last line. When I do a select for everything in the table a,
I get the first row I inserted 'manually', the one with a1 = 1.

So there seems to have been an invisible savepoint set just before the unnamed block ran.

CASE 2:
Then I modified the unnamed block so it did two good inserts and then called a stored procedure that did two good inserts and ended with one 'bad' - inserting a character into a number column. The stored
procedure also had no error trap.

When I run this one, as expected, error message. When I select everything from the table, it gets that single row with a1 = 1.

Again, the unnamed block seems to set an invisible savepoint. And everything in the stored procedure got rolled back.

CASE 3:
Then I reran everything, except the unnamed block had a generic when others then null; error trap, and the stored procedure had a generic when others the null; error trap.

In this case as expected, no error message was generated, and when I selected * from the table, it had inserted all the rows that were valid and only failed to insert the 'bad' rows.

CASE 4:
Then I deleted everything from the table a except the a1 = 1 and did a commit.

Then I reran everything just as in case3, except that: the stored procedure had NO error trap but the unnamed block that calls it DOES. The result was exactly the same as in case3 - everything was stored
except 'bad' rows.

CASE 5:
Then I deleted everything from the table 1 except the a1 = 1 and did a commit.

Then I reran everything just as in case4, except that the stored procedure was the one with the error trap and unnamed block the one without an error trap. The results were that everything was stored in the table except the 'bad' lines.

CASE 6:
Finally ran case where my unnamed block did some ok inserts, I called a proc that did some more ok updates, then I called a proc that did some ok inserts and a bad insert; and there were no error traps in any proc or block. Everything got rolled back.

Usenet source: Ken Quirici (c.d.o.server - 29-Oct-2004)
Basic Exception Handling

With Error Basic Block Structure Handling 		CREATE OR REPLACE PROCEDURE <procedure_name> IS

BEGIN
  NULL;

EXCEPTION
  WHEN <named_exception> THEN
    -- handle identified exception
  WHEN <named_exception> THEN
    -- handle identified exception
  WHEN OTHERS THEN
    -- handle any exceptions not previously handled
END;
/
CREATE OR REPLACE PROCEDURE myproc IS

BEGIN
  NULL;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    NULL;
  WHEN ZERO_DIVIDE THEN
    NULL;
  WHEN OTHERS THEN
     NULL;
END;
/
WHEN OTHERS THEN with SQLCODE and SQLERRM
Note: If not the only exception handler ... must be the last exception handler

A Procedure That Does Nothing 		CREATE OR REPLACE PROCEDURE no_error IS

BEGIN
  NULL;
END no_error;
/
SQL> exec no_error

Modified To Force An Error 		CREATE OR REPLACE PROCEDURE force_error IS

BEGIN
  NULL;
  RAISE too_many_rows;
END force_error;
/

exec force_error

Trap And Hide The Error 		CREATE OR REPLACE PROCEDURE trap_error IS

BEGIN
  NULL;
  RAISE too_many_rows;
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END trap_error;
/

exec trap_error

Display Error With SQLCODE 		CREATE OR REPLACE PROCEDURE trap_errcode IS

ecode    NUMBER(38);
thisproc CONSTANT VARCHAR2(50) := 'trap_errmesg';

BEGIN
  NULL;
  RAISE too_many_rows;
EXCEPTION
  WHEN OTHERS THEN
    ecode := SQLCODE;
    dbms_output.put_line(thisproc || ' - ' || ecode);
END trap_errcode;
/

set serveroutput on

exec trap_errcode

Display Error With SQLERRM 		CREATE OR REPLACE PROCEDURE trap_errmesg IS
 emesg VARCHAR2(250);
BEGIN
  NULL;
  RAISE too_many_rows;
EXCEPTION
  WHEN OTHERS THEN
    emesg := SQLERRM;
    dbms_output.put_line(emesg);
END trap_errmesg;
/

set serveroutput on

exec trap_errmesg

No Error Condition 		DECLARE
 ecode NUMBER;
 emesg VARCHAR2(200);
BEGIN
  NULL;
  ecode := SQLCODE;
  emesg := SQLERRM;
  dbms_output.put_line(TO_CHAR(ecode) || '-' || emesg);
END;
/
WHEN <name exception> THEN & Named Exceptions
Note: A table of the named exceptions is at the bottom of this web page.

When Invalid Cursor Exception Demo 		CREATE OR REPLACE PROCEDURE invcur_exception IS

CURSOR x_cur is
SELECT *
FROM all_tables;

x_rec x_cur%rowtype;

BEGIN
  LOOP
    -- note the cursor was not opened before the FETCH
    FETCH x_cur INTO x_rec;
    EXIT WHEN x_cur%notfound;

    NULL;
  END LOOP;
EXCEPTION
  WHEN INVALID_CURSOR THEN
    dbms_output.put_line('Whoops!');
  WHEN OTHERS THEN
    dbms_output.put_line('Some Other Problem');
END invcur_exception;
/

set serveroutput on

exec invcur_exception

Two Many Rows Exception Demo 		CREATE OR REPLACE PROCEDURE tmr_exception IS
 x all_tables.table_name%TYPE;
BEGIN
  -- note the statement will try to fetch many values
  SELECT table_name -- try to SELECT many things into 1 var
  INTO x
  FROM all_tables;
EXCEPTION
  WHEN TOO_MANY_ROWS THEN
    dbms_output.put_line('Too Many Rows');
  WHEN OTHERS THEN
    dbms_output.put_line('Some Other Problem');
END tmr_exception;
/

set serveroutput on

exec tmr_exception

Division By Zero Error Trapping Demo 		CREATE OR REPLACE PROCEDURE dbz_exception (numin NUMBER) IS
  z  NUMBER := 0;
 x  NUMBER;
BEGIN
  x := numin / z;
EXCEPTION
  WHEN ZERO_DIVIDE THEN
    dbms_output.put_line('Division By Zero');
  WHEN OTHERS THEN
    dbms_output.put_line('Some Other Problem');
END dbz_exception;
/

set serveroutput on

exec dbz_exception(6)

Divide By Zero Error Pass In The Zero 		CREATE OR REPLACE PROCEDURE zero_div (numin NUMBER) IS
 z NUMBER := TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY'));
 x NUMBER;
BEGIN
  x := z / numin;

  dbms_output.put_line('Division By ' || TO_CHAR(numin));
EXCEPTION
  WHEN ZERO_DIVIDE THEN
     dbms_output.put_line('Division By Zero');
   WHEN OTHERS THEN
      dbms_output.put_line('Some Other Problem');
END zero_div;
/

set serveroutput on

exec zero_div(2)
exec zero_div(0)
exec zero_div(7)
User Defined Exceptions

Named Exception In a Function Demo 		CREATE OR REPLACE FUNCTION is_ssn (string_in VARCHAR2)
RETURN VARCHAR2 IS
 -- validating ###-##-#### format
 delim VARCHAR2(1);
 part1 NUMBER(3,0);
 part2 NUMBER(2,0);
 part3 NUMBER(4,0);

  incorrect EXCEPTION;
BEGIN
  IF LENGTH(string_in) <> 11 THEN
    RAISE incorrect;
  END IF;

  part1 := TO_NUMBER(SUBSTR(string_in,1,3),'999');

  delim := SUBSTR(string_in,4,1);
  IF delim <> '-' THEN
    RAISE incorrect;
  END IF;

  part2 := TO_NUMBER(SUBSTR(string_in,5,2),'99');

  delim := SUBSTR(string_in,7,1);
  IF delim <> '-' THEN
    RAISE incorrect ;
  END IF;

  part3 := TO_NUMBER(SUBSTR(string_in,8,4),'9999');

  RETURN 'TRUE';
EXCEPTION
  WHEN incorrect THEN
    RETURN 'FALSE';
  WHEN OTHERS THEN
    RETURN 'FALSE';
END is_ssn;
/
Pragma Exception_Init

PRAGMA EXCEPTION_INIT Demo 		CREATE TABLE results (
sourceno     NUMBER(10) NOT NULL,
testno       NUMBER(3) NOT NULL,
locationid   NUMBER(10) NOT NULL);

-- the basic procedure
CREATE OR REPLACE PROCEDURE PragmaExcInit IS

BEGIN
  INSERT INTO results
  (sourceno)
  VALUES
  ('1');
  COMMIT;
END PragmaExcInit;
/

exec pragmaexcinit

-- the same procedure with exception trapping
CREATE OR REPLACE PROCEDURE PragmaExcInit IS

FieldsLeftNull EXCEPTION;
PRAGMA EXCEPTION_INIT(FieldsLeftNull, -01400);

BEGIN
  INSERT INTO results
  (sourceno)
  VALUES
  ('1');
  COMMIT;
EXCEPTION
  WHEN FieldsLeftNull THEN
    dbms_output.put_line('ERROR: Trapped Fields Left Null');
  WHEN OTHERS THEN
    dbms_output.put_line(SQLERRM);
END PragmaExcInit;
/

set serveroutput on

exec pragmaexcinit
RAISE

Demo Procedure With User Defined Exceptions And RAISE 		CREATE OR REPLACE PROCEDURE raise_demo (inval NUMBER) IS
  evenno EXCEPTION;
  oddno  EXCEPTION;
BEGIN
  IF MOD(inval, 2) = 1 THEN
    RAISE oddno;
  ELSE
    RAISE evenno;
  END IF;
EXCEPTION
  WHEN evenno THEN
    dbms_output.put_line(TO_CHAR(inval) || ' is even');
  WHEN oddno THEN
    dbms_output.put_line(TO_CHAR(inval) || ' is odd');
END raise_demo;
/

exec raise_demo
RAISE_APPLICATION_ERROR

Demo Procedure Without
RAISE_APPLICATION_ERROR 		RAISE_APPLICATION_ERROR(<error_number>, <error_message>, <TRUE | FALSE>);

error_number -20000 to -20999
error_message VARCHAR2(2048)
TRUE          add to error stack
FALSE         replace error stack (the default)
CREATE OR REPLACE PROCEDURE raise_app_error (inval NUMBER) IS
 evenno EXCEPTION;
 oddno  EXCEPTION;
BEGIN
  IF MOD(inval, 2) = 1 THEN
    RAISE oddno;
  ELSE
    RAISE evenno;
  END IF;
EXCEPTION
  WHEN evenno THEN
    RAISE_APPLICATION_ERROR(-20001, 'Even Number Entered');
  WHEN oddno THEN
    RAISE_APPLICATION_ERROR(-20999, 'Odd Number Entered');
END raise_app_error;
/
Locator Variables

Locating Errors With Locator Variables 		The use of variables to identify the location with a code block where the error was raised
set serveroutput on

DECLARE
 step  VARCHAR2(2);
 i     NUMBER(1) := 5;
 n     NUMBER(2) := 10;
BEGIN
  step := 'A';
  n := n/i;
  i := i-1;

  step := 'B';
  n := n/i;
  i := i-2;

  step := 'C';
  n := n/i;
  i := i-2;

  step := 'D';
  n := n/i;
  i := i-2;

  step := 'E';
  n := n/i;
  i := i-1;
EXCEPTION
  WHEN ZERO_DIVIDE THEN
    dbms_output.put_line('Failure at: ' || step);
END;
/
Declaration Exceptions

Declaration Exceptions 		Declaration exceptions can not be trapped with an error handler
DECLARE
 i NUMBER(3) := 1000;
BEGIN
  NULL;
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END;
/

CREATE OR REPLACE PROCEDURE demo(someval IN NUMBER) IS
 i NUMBER(3) := someval;
BEGIN
  i := i+0;
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END;
/

exec demo(999);
exec demo(1000);
Exception Handling Demo

Incomplete Handling 		CREATE TABLE test (
col INT);

ALTER TABLE test
ADD CONSTRAINT pk_test
PRIMARY KEY (col)
USING INDEX;

CREATE OR REPLACE PROCEDURE p IS
BEGIN
  INSERT INTO test VALUES (1);
END p;
/

BEGIN
  p;
  p;
END;
/

-- no records inserted as expected
SELECT * FROM test;

BEGIN
  p;
  p;
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END;
/

-- one record inserted
SELECT * FROM test;
System-Defined Event Trapping

Error Stack Trapping with System Events 		Declaration exceptions can not be trapped with an error handler
set serveroutput on

CREATE OR REPLACE TRIGGER e_trigger
BEFORE delete
ON t

DECLARE
  l_text ora_name_list_t;
  l_n number;
BEGIN
  dbms_output.put_line( '--------------------' );
  dbms_output.put_line('statment causing error: ' );

  l_n := ora_sql_txt( l_text );

  FOR i in 1 .. nvl(l_text.count,0)
  LOOP
    dbms_output.put_line(l_text(i) );
  END LOOP;

  dbms_output.put_line( 'error text: ' );

  FOR i IN 1 .. ora_server_error_depth
  LOOP
    dbms_output.put_line(ora_server_error_msg(i) );
  END LOOP;

  dbms_output.put_line( '--------------------' );
END e_trigger;
/
Simple Error Handling Procedure

Function To Identify The User Logged Onto Oracle 		CREATE OR REPLACE FUNCTION getosuser RETURN VARCHAR2 IS
 vOSUser user_users.username%TYPE;
BEGIN
  SELECT osuser
  INTO vOSUser
  FROM sys.v_$session
  WHERE sid = (
    SELECT sid
    FROM sys.v_$mystat
    WHERE rownum = 1);

  RETURN vOSUser;
EXCEPTION
  WHEN OTHERS THEN
    RETURN 'UNK';
END getosuser;
/

SELECT getosuser FROM dual;
The Table Holding The Output Of The Error Logging Procedure CREATE TABLE errorlog (
procname     VARCHAR2(61),
loadfilename VARCHAR2(40),
runtime      DATE DEFAULT SYSDATE,
osuser       VARCHAR2(30),
mesgtext     VARCHAR2(250));

The Error Logging Procedure 		CREATE OR REPLACE PROCEDURE log_error (
pProcName VARCHAR2,
pLoadFile VARCHAR2,
pMesgText VARCHAR2)
IS

PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN
  INSERT INTO errorlog
  (procname, loadfilename, osuser, mesgtext)
  VALUES
  (pProcName, pLoadFile, getOSUser, pMesgText);
  COMMIT;

-- No exception handler intentionally. Why?

END log_error;
/
To Test The Error Logging Procedure exec log_error('Test', 'None', 'Did it work?');

SELECT * FROM errorlog;
Database-Wide Exception Handling

Using AFTER SERVERERROR 		CREATE TABLE error_log (
error_timestamp TIMESTAMP(9),
database_name   VARCHAR(50),
instance_number NUMBER,
error_number    NUMBER,
error_message   VARCHAR2(255),
logged_on_as    VARCHAR2(30),
client_host     VARCHAR2(50),
service_name    VARCHAR2(30));

CREATE OR REPLACE PROCEDURE error_trap IS
 odbname VARCHAR2(50); -- Oracle database name
 oinst NUMBER; -- Oracle instance number
 enum NUMBER; -- Error Message number
 emsg VARCHAR2(250); -- Error text
 curschema VARCHAR2(30);
 clihost VARCHAR2(50);
 serv_name VARCHAR2(30);

-- PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  enum := sqlcode;
  emsg := sqlerrm;

  odbname := ora_database_name;
  oinst := ora_instance_num;

  SELECT sys_context('USERENV', 'CURRENT_SCHEMA')
  INTO curschema
  FROM dual;

  SELECT sys_context('USERENV', 'HOST')
  INTO clihost
  FROM dual;

  SELECT sys_context('USERENV', 'SERVICE_NAME')
  INTO serv_name
  FROM dual;

  INSERT INTO error_log
  (error_timestamp, database_name, instance_number,
   error_number, error_message, logged_on_as,
   client_host, service_name)
  VALUES
  (SYSTIMESTAMP, odbname, oinst, enum, emsg,
   curschema, clihost, serv_name);
  COMMIT;
END error_trap;
/

CREATE OR REPLACE TRIGGER error_trig
AFTER SERVERERROR ON DATABASE
CALL error_trap
/

BEGIN
  RAISE zero_divide;
END;
/

set linesize 141
col error_timestamp format a31
col database_name format a40
col error_message format a40
col logged_on_as format a20
col client_host format a20
col service_name format a20

SELECT error_timestamp, database_name, instance_number
FROM error_log;

SELECT error_timestamp, error_number, error_message
FROM error_log;

SELECT logged_on_as, client_host, service_name
FROM error_log;
Robust Error Handling Procedure

Formatting Error Stack Tables

And Sequence 		CREATE TABLE errors (
module       VARCHAR2(50),
seq_number   NUMBER,
error_number NUMBER,
error_mesg   VARCHAR2(100),
error_stack  VARCHAR2(2000),
call_stack   VARCHAR2(2000),
timestamp    DATE);

ALTER TABLE errors
ADD CONSTRAINT pk_errors
PRIMARY KEY (module, seq_number)
USING INDEX
TABLESPACE indx_sml;

CREATE TABLE call_stacks (
module VARCHAR2(50),
seq_number NUMBER,
call_order NUMBER,
object_handle VARCHAR2(10),
line_num NUMBER,
object_name VARCHAR2(80));

ALTER TABLE call_stacks
ADD CONSTRAINT pk_call_stacks
PRIMARY KEY (module, seq_number, call_order)
USING INDEX
TABLESPACE indx_sml;

ALTER TABLE call_stacks
ADD CONSTRAINT fk_cs_errors
FOREIGN KEY (module, seq_number)
REFERENCES errors (module, seq_number)
ON DELETE CASCADE;

CREATE TABLE error_stacks (
module VARCHAR2(50),
seq_number NUMBER,
error_order NUMBER,
facility CHAR(3),
error_number NUMBER(5),
error_mesg VARCHAR2(100));

ALTER TABLE error_stacks
ADD CONSTRAINT pk_error_stacks
PRIMARY KEY (module, seq_number, error_order)
USING INDEX
TABLESPACE indx_sml;

ALTER TABLE error_stacks
ADD CONSTRAINT fk_es_errors
FOREIGN KEY (module, seq_number)
REFERENCES errors (module, seq_number)
ON DELETE CASCADE;

CREATE SEQUENCE error_seq
START WITH 1
INCREMENT BY 1;

Error Handling Package Header 		CREATE OR REPLACE PACKAGE ErrorPkg AS

/* Generic error handling package, using DBMS_UTILITY.FORMAT_ERROR_STACK and DBMS_UTILITY.FORMAT_CALL_STACK. This package stores general error information in the errors table, with detailed call stack and error stack information in the call_stacks and error_stacks tables, respectively.

Entry point for handling errors. HandleAll should be called from all exception handlers where you want the error to be logged. p_Top should be TRUE only at the topmost level of procedure nesting. It should be FALSE at other levels.
*/

PROCEDURE HandleAll(p_Top BOOLEAN);

/*
Prints the error and call stacks (using DBMS_OUTPUT) for the given module and sequence number.
*/
PROCEDURE PrintStacks(p_Module IN errors.module%TYPE,
p_SeqNum IN errors.seq_number%TYPE);

/*
Unwinds the call and error stacks, and stores them in the errors and call stacks tables. Returns the sequence number under which the error is stored. If p_CommitFlag is TRUE,
then the inserts are committed. In order to use StoreStacks, an error must have been handled. Thus HandleAll should have been called with p_Top = TRUE.
*/

PROCEDURE StoreStacks(p_Module IN errors.module%TYPE,
p_SeqNum OUT errors.seq_number%TYPE,
p_CommitFlag BOOLEAN DEFAULT FALSE);

END ErrorPkg;
/

Error Handling Package Body 		CREATE OR REPLACE PACKAGE BODY ErrorPkg IS

v_NewLine CONSTANT CHAR(1) := CHR(10);

v_Handled BOOLEAN := FALSE;
v_ErrorStack VARCHAR2(2000);
v_CallStack VARCHAR2(2000);

PROCEDURE HandleAll(p_Top BOOLEAN) IS

BEGIN
  IF p_Top THEN
    v_Handled := FALSE;
  ELSIF NOT v_Handled THEN
    v_Handled := TRUE;
    v_ErrorStack := DBMS_UTILITY.FORMAT_ERROR_STACK;
    v_CallStack := DBMS_UTILITY.FORMAT_CALL_STACK;
  END IF;
END HandleAll;
--===================================================
PROCEDURE PrintStacks(
p_Module IN errors.module%TYPE,
p_SeqNum IN errors.seq_number%TYPE)
IS

v_TimeStamp errors.timestamp%TYPE;
v_ErrorMsg errors.error_mesg%TYPE;

CURSOR c_CallCur IS
SELECT object_handle, line_num, object_name
FROM call_stacks
WHERE module = p_Module
AND seq_number = p_SeqNum
ORDER BY call_order;

CURSOR c_ErrorCur IS
SELECT facility, error_number, error_mesg
FROM error_stacks
WHERE module = p_Module
AND seq_number = p_SeqNum
ORDER BY error_order;

BEGIN
  SELECT timestamp, error_mesg
  INTO v_TimeStamp, v_ErrorMsg
  FROM errors
  WHERE module = p_Module
  AND seq_number = p_SeqNum;

  -- Output general error information.
  dbms_output.put_line(TO_CHAR(v_TimeStamp, 'DD-MON-YY HH24:MI:SS'));
  dbms_output.put(' Module: ' || p_Module);
  dbms_output.put(' Error #' || p_SeqNum || ': ');
  dbms_output.put_line(v_ErrorMsg);

  -- Output the call stack.
  dbms_output.put('Complete Call Stack:');
  dbms_output.put(' Object Handle Line Number Object Name');
  dbms_output.put_line(' ------------- ----------- -----------');

  FOR v_CallRec in c_CallCur
  LOOP
    dbms_output.put(RPAD(' ' || v_CallRec.object_handle, 15));
    dbms_output.put(RPAD(' ' || TO_CHAR(v_CallRec.line_num), 13));
    dbms_output.put_line(' ' || v_CallRec.object_name);
  END LOOP;

  -- Output the error stack.
  dbms_output.put_line('Complete Error Stack:');

  FOR v_ErrorRec in c_ErrorCur
  LOOP
    dbms_output.put(' ' || v_ErrorRec.facility || '-');
    dbms_output.put(TO_CHAR(v_ErrorRec.error_number) || ': ');
    dbms_output.put_line(v_ErrorRec.error_mesg);
  END LOOP;
END PrintStacks;
--===================================================
PROCEDURE StoreStacks(p_Module IN errors.module%TYPE,
 p_SeqNum OUT errors.seq_number%TYPE,
 p_CommitFlag BOOLEAN DEFAULT FALSE)
IS

v_SeqNum     NUMBER;
v_Index      NUMBER;
v_Length     NUMBER;
v_End        NUMBER;
v_Call       VARCHAR2(100);
v_CallOrder  NUMBER := 1;
v_Error      VARCHAR2(120);
v_ErrorOrder NUMBER := 1;

v_Handle      call_stacks.object_handle%TYPE;
v_LineNum     call_stacks.line_num%TYPE;
v_ObjectName  call_stacks.object_name%TYPE;

v_Facility    error_stacks.facility%TYPE;
v_ErrNum      error_stacks.error_number%TYPE;
v_ErrMsg      error_stacks.error_mesg%TYPE;

v_FirstErrNum errors.error_number%TYPE;
v_FirstErrMsg errors.error_mesg%TYPE;

BEGIN
  -- Get the error sequence number.
  SELECT error_seq.nextval
  INTO v_SeqNum
  FROM dual;

  p_SeqNum := v_SeqNum;

  -- Insert first part of header info. into the errors table
  INSERT INTO errors
  (module, seq_number, error_stack, call_stack, timestamp)
  VALUES
  (p_Module, v_SeqNum, v_ErrorStack, v_CallStack, SYSDATE);

  /*
  Unwind the error stack to get each error out by scanning the
  error stack string. Start with the index at the beginning of
  the string
  *;
  v_Index := 1;

  /*
  Loop through the string, finding each newline
  A newline ends each error on the stack
  */
  WHILE v_Index < LENGTH(v_ErrorStack) LOOP
    -- v_End is the position of the newline.
    v_End := INSTR(v_ErrorStack, v_NewLine, v_Index);

    -- The error is between the current index and the newline
    v_Error := SUBSTR(v_ErrorStack, v_Index, v_End - v_Index);

    -- Skip over the current error, for the next iteration
    v_Index := v_Index + LENGTH(v_Error) + 1;

    /* An error looks like 'facility-number: mesg'. Get each
    piece out for insertion. The facility is the first 3
    characters of the error.
    */

    v_Facility := SUBSTR(v_Error, 1, 3);

    -- Remove the facility and the dash (always 4 characters)
    v_Error := SUBSTR(v_Error, 5);

    -- Next get the error number
    v_ErrNum := TO_NUMBER(SUBSTR(v_Error, 1, INSTR(v_Error,
    ':') - 1));

    -- Remove the error number, colon & space (always 7 chars)
     v_Error := SUBSTR(v_Error, 8);

    -- What's left is the error message
    v_ErrMsg := v_Error;

    /*
    Insert the errors, and grab the first error number and
    message while we're at it
    */

    INSERT INTO error_stacks
    (module, seq_number, error_order, facility, error_number,
    error_mesg)
    VALUES
    (p_Module, p_SeqNum, v_ErrorOrder, v_Facility, v_ErrNum,
    v_ErrMsg);

    IF v_ErrorOrder = 1 THEN
      v_FirstErrNum := v_ErrNum;
      v_FirstErrMsg := v_Facility || '-' || TO_NUMBER(v_ErrNum)
      || ': ' || v_ErrMsg;
    END IF;

    v_ErrorOrder := v_ErrorOrder + 1;
  END LOOP;

  -- Update the errors table with the message and code
  UPDATE errors
  SET error_number = v_FirstErrNum,
      error_mesg = v_FirstErrMsg
  WHERE module = p_Module
  AND seq_number = v_SeqNum;

  /*
  Unwind the call stack to get each call out by scanning the
  call stack string. Start with the index after the  first call
  on the stack. This will be after the first occurrence of
  'name' and the newline.
  */
  v_Index := INSTR(v_CallStack, 'name') + 5;

  /* Loop through the string, finding each newline. A newline
  ends each call on the stack.
  */
  WHILE v_Index < LENGTH(v_CallStack) LOOP
    -- v_End is the position of the newline
    v_End := INSTR(v_CallStack, v_NewLine, v_Index);

    -- The call is between the current index and the newline
    v_Call := SUBSTR(v_CallStack, v_Index, v_End - v_Index);

    -- Skip over the current call, for the next iteration
    v_Index := v_Index + LENGTH(v_Call) + 1;

    /*
    Within a call, we have the object handle, then the line
    number, then the object name, separated by spaces. Separate
    them out for insertion.

    -- Trim white space from the call first.
    */
    v_Call := TRIM(v_Call);

    -- First get the object handle
    v_Handle := SUBSTR(v_Call, 1, INSTR(v_Call, ' '));

    -- Remove the object handle,then the white space
    v_Call := SUBSTR(v_Call, LENGTH(v_Handle) + 1);
    v_Call := TRIM(v_Call);

    -- Get the line number
    v_LineNum := TO_NUMBER(SUBSTR(v_Call,1,INSTR(v_Call,' ')));

    -- Remove the line number, and white space
    v_Call := SUBSTR(v_Call, LENGTH(v_LineNum) + 1);
    v_Call := TRIM(v_Call);

    -- What is left is the object name
    v_ObjectName := v_Call;

    -- Insert all calls except the call for ErrorPkg
    IF v_CallOrder > 1 THEN
      INSERT INTO call_stacks
      (module, seq_number, call_order, object_handle, line_num,
      object_name)
      VALUES
      (p_Module, v_SeqNum, v_CallOrder, v_Handle, v_LineNum,
       v_ObjectName);
    END IF;

    v_Callorder := v_CallOrder + 1;
  END LOOP;

  IF p_CommitFlag THEN
    COMMIT;
  END IF;
END StoreStacks;

END ErrorPkg;
/

Format Error Stack Demo Table And Trigger 		CREATE TABLE ttt (f1 number);

CREATE OR REPLACE TRIGGER ttt_insert
BEFORE INSERT ON ttt

BEGIN
  RAISE ZERO_DIVIDE;
END ttt_insert;
/

Error Producing Procedures (A, B, And C) 		CREATE OR REPLACE PROCEDURE C AS

BEGIN
  INSERT INTO ttt VALUES (7);
EXCEPTION
  WHEN OTHERS THEN
    ErrorPkg.HandleAll(FALSE);
    RAISE;
END C;
/
--===================================================
CREATE OR REPLACE PROCEDURE B AS

BEGIN
  C;
EXCEPTION
  WHEN OTHERS THEN
    ErrorPkg.HandleAll(FALSE);
RAISE;

END B;
/
--===================================================
CREATE OR REPLACE PROCEDURE A AS
 v_ErrorSeq NUMBER;
BEGIN
 B;
EXCEPTION
  WHEN OTHERS THEN
    ErrorPkg.HandleAll(TRUE);
    ErrorPkg.StoreStacks('Scott', v_ErrorSeq, TRUE);
    ErrorPkg.PrintStacks('Scott', v_ErrorSeq);
END A;
/
Run Format Error Stack Demo exec a;

-- Examine the tables errors, call_stack, and error_stack
Predefined (Named) PL/SQL Exceptions
Exception Name | Error | Description
ACCESS_INTO_NULL | ORA-06530 | Attempted to assign values to the attributes of an uninitialized (NULL) object
CASE_NOT_FOUND | ORA-06592 | None of the choices in the WHEN clauses of a CASE statement is selected and there is no ELSE clause
COLLECTION_IS_NULL | ORA-06531 | Attempt to apply collection methods other than EXISTS to an uninitialized (NULL) PL/SQL table or varray
CURSOR_ALREADY_OPEN | ORA-06511 | Exactly what it seems to be. Tried to open a cursor that was already open
DUP_VAL_ON_INDEX | ORA-00001 | An attempt to insert or update a record in violation of a primary key or unique constraint
INVALID_CURSOR | ORA-01001 | The cursor is not open or not valid in the context in which it is being called
INVALID_NUMBER | ORA-01722 | It isn't a number even though you are treating it like one to trying to turn it into one
LOGIN_DENIED | ORA-01017 | Invalid name and/or password for the instance
NO_DATA_FOUND | ORA-01403 | The SELECT statement returned no rows or referenced a deleted element in a nested table or referenced an initialized element in an Index-By table
NOT_LOGGED_ON | ORA-01012 | You lost your connection to the database
PROGRAM_ERROR | ORA-06501 | Internal PL/SQL error
ROWTYPE_MISMATCH | ORA-06504 | The rowtype does not match the values being fetched, or assigned, to it
SELF_IS_NULL | ORA-30625 | Program attempted to call a MEMBER method, but the instance of the object type has not been intialized. The built-in parameter SELF points to the object, and is always the first parameterpassed to a MEMBER method
STORAGE_ERROR | ORA-06500 | A hardware problem: Either RAM or disk drive
SUBSCRIPT_BEYOND_COUNT | ORA-06533 | Reference to a nested table or varray index higher than the number of elements in the collection
SUBSCRIPT_OUTSIDE_LIMIT | ORA-06532 | Reference to a nested table or varray index outside the declared range (such as -1)
SYS_INVALID_ROWID | ORA-01410 | The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid
TIMEOUT_ON_RESOURCE | ORA-00051 | The activity took too long and timed out
TOO_MANY_ROWS | ORA-01422 | The SQL INTO statement brought back more than one value or row (only one is allowed)
VALUE_ERROR | ORA-06502 | An arithmetic, conversion, truncation, or size-constraint error. Usually raised by trying to cram a 6 character string into a VARCHAR2(5) variable
ZERO_DIVIDE | ORA-01476 | Not only would your math teacher not let you do it. Computer's won't either. Who said you didn't learn anything useful in primary school
Related Topics
Anonymous Block
DBMS_UTILITY
DDL Triggers
Instead-Of Triggers
Errors
Function
Procedure
System Events
System Triggers
Table Triggers
UTL_LMS
Warnings


Oracle Group By Having SQL PL/SQL

Oracle GROUP BY & HAVING Clauses
Basic Group By
GROUP BY is used in conjunction with aggregating functions to group the results by the unaggregated columns
Aggregating Functions AVG
COUNT
FIRST
LAST
MAX
MIN
STDDEV
SUM
VARIANCE

 For more use the link to Aggregating Functions at the bottom of the page
SQL Statement Not Requiring GROUP BY SELECT COUNT(*)
FROM all_tables;
SQL Statement With A Single Ungrouped Column Requiring GROUP BY SELECT table_name, COUNT(*)
FROM all_tables;

SELECT table_name, COUNT(*)
FROM all_indexes
GROUP BY table_name;
SQL Statement With Multiple Ungrouped Columns And Multiple Grouped Columns set linesize 121
col index_type format a20

SELECT table_name, index_type, COUNT(leaf_blocks), COUNT(distinct_keys)
FROM all_indexes
GROUP BY table_name, index_type;
Group By Result Merging

The following demo is based on a demo posted by Michel Cadot in comp.databases.oracle.server 		CREATE TABLE grp_test (
year   VARCHAR2(4),
result NUMBER(7));

INSERT INTO grp_test VALUES ('2002', 1000);
INSERT INTO grp_test VALUES ('1998', 1250);
INSERT INTO grp_test VALUES ('1999', 3786);
INSERT INTO grp_test VALUES ('2000', 977);
INSERT INTO grp_test VALUES ('1997', 5000);
INSERT INTO grp_test VALUES ('2001', 123);
INSERT INTO grp_test VALUES ('1998', 125);
INSERT INTO grp_test VALUES ('2003', 2000);
INSERT INTO grp_test VALUES ('2004', 2200);
INSERT INTO grp_test VALUES ('2003', 150);
COMMIT;

SELECT * FROM grp_test;

SELECT DECODE(SIGN(year-1999),1,year,'1999 or before'), SUM(result)
FROM grp_test
GROUP BY DECODE(SIGN(year-1999),1,year,'1999 or before');
Group By With Having
HAVING is used to perform an action on groups created by GROUP BY similar to that of the WHERE clause on rows in a basic SQL statement. The WHERE clause limits the rows evaluated. The HAVING clause limits the grouped rows returned.

GROUP BY With HAVING Clause 		SELECT table_name, COUNT(*)
FROM all_indexes
GROUP BY table_name
HAVING COUNT(*) > 1;

SELECT table_name, COUNT(*)
FROM all_indexes
GROUP BY table_name
HAVING COUNT(*) = 2;

SELECT table_name, COUNT(*)
FROM all_indexes
GROUP BY table_name
HAVING COUNT(*) BETWEEN 2 AND 3;
Group By Substitute

GROUP BY Substitution Demo 		-- To create the all_objs table: Click Here

CREATE TABLE t1 AS
SELECT rownum objid, 'name'||rownum objname
FROM all_objs;

CREATE TABLE t2 AS
SELECT objid, dbms_random.value(1,10) PRICE
FROM t1;

INSERT INTO t2
SELECT objid, dbms_random.value(1,10) PRICE
FROM t1;

CREATE INDEX t1_idx
ON t1 (objid);

CREATE INDEX t2_idx
ON t2(objid);

exec dbms_stats.gather_schema_stats(USER, CASCADE=>TRUE);
-- Observe the output

SELECT t1.objid, MAX(t2.price) PRICE
FROM t1, t2
WHERE t1.objid = t2.objid
AND t1.objname = 'name120'
GROUP BY t1.objid;

SELECT t1.objid, (
  SELECT MAX(price)
  FROM t2
  WHERE t2.objid = t1.objid) PRICE
FROM t1
WHERE objname = 'name120';
-- Compare the plans

set autotrace traceonly exp statistics

SELECT t1.objid, MAX(t2.price) PRICE
FROM t1, t2
WHERE t1.objid = t2.objid
AND t1.objname = 'name120'
GROUP BY t1.objid;

SELECT t1.objid, (
  SELECT MAX(price)
  FROM t2
  WHERE t2.objid = t1.objid) PRICE
FROM t1
WHERE objname = 'name120';

set autotrace off

More Than One Way To Approach A Problem 		conn / as sysdba

set autotrace traceonly

-- conventional group by
SELECT table_name, COUNT(*) TAB_CNT
FROM all_indexes
GROUP BY table_name;

-- sub-query solution
SELECT DISTINCT table_name, (
  SELECT COUNT(*)
  FROM all_indexes ai2
  WHERE ai2.table_name = ai1.table_name) TAB_CNT
FROM all_indexes ai1;

-- analytic counterpart
SELECT DISTINCT table_name, COUNT(*)
OVER (PARTITION BY table_name) TAB_CNT
FROM all_indexes;

set autotrace off

-- Note: this demo does not take into account the possibility that
-- indexes with the same name occur in more than one schema

Find the most prevalent value in a column 		SELECT cnt1.initial_extent
FROM (
  SELECT initial_extent, COUNT(*) TOTAL
  FROM all_tables
  GROUP BY initial_extent) cnt1,
     (
  SELECT MAX(total) MAXTOTAL
  FROM (
    SELECT initial_extent, COUNT(*) TOTAL
    FROM all_tables
    GROUP BY initial_extent)) cnt2
WHERE cnt1.total = cnt2.maxtotal;
Removing Duplicate Rows With GROUP BY

Duplicate record Removal Demo 		CREATE TABLE t (
col1 VARCHAR2(3),
col2 VARCHAR2(3));

INSERT INTO t VALUES ('AAA', '123');
INSERT INTO t VALUES ('BBB', '123');
INSERT INTO t VALUES ('CCC', '789');
INSERT INTO t VALUES ('AAA', '123');
INSERT INTO t VALUES ('DDD', '123');
INSERT INTO t VALUES ('CCC', '789');
INSERT INTO t VALUES ('CCC', '987');
COMMIT;

SELECT * FROM t;

SELECT MIN(rowid), col1, col2
FROM t
GROUP BY col1, col2;

DELETE FROM t
WHERE rowid NOT IN (
  SELECT MIN(rowid)
  FROM t
  GROUP BY col1, col2);

COMMIT;

SELECT * FROM t;
Related Topics
Aggregating Functions
CUBE
DECODE
GROUP_ID
GROUPING_ID
GROUPING
GROUPING_SETS
ROLLUP
SELECT


Oracle Indexes SQL Tuning BTree B*Tree Bitmap Reverse Key Descending Global Local Compressed

Oracle Indexes
General
Index types specifically related to clusters, index organized tables, nested tables, and partitioned tables are handled in the specific library sections dealing with those object types.
Index Types
B*Tree
Bitmap
Bitmap Join
Compressed
Descending
Function Based
Invisible
No-Segment
Reverse
Data Dictionary Objects Related To Indexes
col$ | ind$ | ind_online$
indpart$ | ind_stats$ | indsubpart$
index_histograms | index_stats | v$object_usage
DBA | ALL | USER
dba_indexes | all_indexes | user_indexes
dba_ind_columns | all_ind_columns | user_ind_columns
dba_ind_expressions | all_ind_expressions | user_ind_expressions
System Privileges Related To Indexes create index
create any index
Related initialization parameters optimizer_index_caching
optimizer_index_cost_adj
optimizer_use_invisible_indexes
skip_unusable_indexes
_disable_function_based_index

Index Usage Notes

This unedited explanation, one of the most lucid I have seen, was posted by Richard Foote at c.d.o.server on 20 January, 2005. 		"hastenthunder" wrote in message news:56uHd.2452$Ny6.4229@mencken.net.nih.gov...

>> Hello,
>>
>> I've read many documentations online stating to only create an index if
>> queries against this table frequently retrieve less than 15% of the rows.
>> However, if the query returns, say, 40% of the rows, wouldn't indexing the
>> column still help by cutting the work by roughly half?
>>
>>
>> hastenthunder
>>

A much *simplified* example on how I teach this stuff...

Let's say we have a table that has 10,000,000 rows which are stored in 1,000,000 data blocks meaning we have approximately 10 rows per block on average.

Let's say we have an index on this table that has 100,000 leaf blocks meaning we have on average approximately 100 leaf entries per leaf block the index has 3 levels.

Let's also say we have an "effective" multi-block read capability of 10 blocks per I/O (meaning Oracle will read 10 "consecutive" blocks at a time on average during a full table scan multiblock read).

Finally, let's say we're interested in accessing *just* 10% of the data (or 1,000,000 of the total 10,000,000 rows). Will Oracle use the index or won't it ? Hopefully, I've picked an easy set of numbers to help illustrate the answer ...

Firstly, to calculate the "cost" of using the index access path.

We need to read the root block + a branch block in order to get to the first leaf block of interest. That's 2 logical I/Os (LIOs). We then need to read approximately 10% of the leaf blocks in order to get our 1,000,000 leaf entries required to directly access our 1,000,000 rows of interest, that's 10% of the 100,000 leaf blocks = 10,000 leaf blocks. Because we're reading an index via a range scan and because the leaf blocks are not (necessarily) physically co-related, Oracle must read each leaf block via a single I/O. So that's 10,000 LIOs. So, just to read the index alone, we require 2 + 10,000 = 10,002 LIOs.

Note by default, Oracle assumes the above "cost" to be physical I/Os (PIOs). Now assuming this index is heavily accessed, a good number of these index blocks may already be cached in memory. The optimizer_index_caching parameter can be used to adjust the above cost by suggesting that x% are actually already cached and so are "cheaper" to access. To keep things simple, we'll assume the default value of 0% or that no index blocks are actually likely to be cached (generally not a wise assumption but let's keep the arithmetic simple).

To access the corresponding table blocks, again Oracle can only perform these reads via a single block read as each index entry points to a table block that contains it's specific table row . Now we're after 1,000,000 rows which means we require 1,000,000 LIOs in order to access the required rows. Question is, how many *different* table blocks do we need to access ? Well, this is entirely dependent on the Clustering Factor (CF) of the index, or how closely aligned are the corresponding rows in the table in relation to the order of the index (which must be in the order of the index values). In the "best" possible case, all the required rows are all ordered and grouped together in the same "collection" of table blocks meaning we only have to
access 10% of the 1,000,000 table blocks or 100,000 table blocks in a roughly *consecutively* manner.

However, as is more common, if the required rows are randomly and evenly distributed among the table blocks, then on average we need to read 1 row (10%) from *each and every table block*. Note in your case of wanting to access 40% of the data, we might depending on a poor CF need to visit on average *each and every* data block *4 times*. This is the key point (no pun intended).

The greater the number of differing blocks we access, then the less likely we will find the block in memory from it being previously read and the more likely that the block will need to be read from disk (PIO). Oracle considers this and uses the CF in it's costing calculations. Assuming a randomly distributed set of required rows, note we will need to visit *all* the table blocks on average because on average we are interested in 1 in 10 of the rows that each block contains (yes, some blocks may not actually be visited and some may be visited a number of times but with such volume of blocks, it conceivably might be a significant duration between reads to the same block meaning it could easily have been aged and be physically re-read anyways).

The point though is that it's 1,000,000 LIOs regardless, of which a very significant number *could* be *actual distinct* (or differing) blocks. So that's 10,002 for the index + 1,000,000 for the table = 1,010,002 LIOs to read *just* 10% of the data via an index.

Now to calculate the "cost" of a FTS. A FTS has a number of advantages over an index access path. Firstly, because we read each block "consecutively" (kinda) Oracle can investigate the appropriate selectiveness of each row within the block ensuring that each table block is read just *once* (special blocks such as extent maps withstanding). Secondly, again because each block is read consecutively, Oracle can perform a multi-block read and read multiple blocks within the one LIO. This is based on factors such as db_file_multiblock_read_count, system statistics, OS I/O characteristics, the caching characteristics of the table and the "fudge-factor" that the
Oracle CBO applies in it's calculations.

For simplicity (and to keep the numbers really simple), assuming an effective multi-block read of 10, we can read the entire table in approximately 1,000,000 table blocks / 10 = 100,000 LIOs. Note that although these are larger and potentially more "costly" I/Os than the single block I/Os used by the index, Oracle assumes by default that the actual cost of each type of I/O to be the same. The optimizer_index_cost_adj parameter can be used to more accurately estimate (if necessary) the relative cost of
a single block I/O to that of a FTS multi-block I/O. Again for simplicity, we'll assume the default of 100 meaning that the cost of a single block I/O is 100% (or the same) as a FTS I/O.

So, we now have our two comparative costings. The index access has a rough cost of 1,010,002 and the FTS has a rough cost of just 100,000. The FTS wins hands down.... Note for 40% of the data, the relative costs would have been roughly 4,040,002 vs. 100,000. Even more hands down ...

The break-even point can now be calculated based on the above criteria, some of which include:
  • the selectivity of the query
  • number of leaf blocks
  • average number of leaf entries per leaf block
  • height of index
  • caching characteristics of index
  • clustering factor of index
  • number of table blocks (below HWM)
  • average number of rows per block
  • effective (or calculated) multi-block read
  • caching characteristics of the table (which can influence the effective
    multi-block read)
  • relative cost of a single block I/O vs. a multi-block I/O
  • amount of row migration / row chaining (although the CBO is not so good
    with this)
  • parallelism (potentially a major factor)

So your assumption that reading 40% of rows would cut the work by roughly half is not correct. In the example above, it would actually cost about 40 times as much. In my long-winded manner, I hope this makes some kind of sense and goes some way to explaining why.

One final piece of advice. Ignore any writings or suggestions that there is a magical break even point is x% (where x could be 2% or 10% or 50% or whatever). Hopefully the above will hint that there is *no* such percentage as it all depends on too many factors. I can easily give you an example where an index is most efficient when reading 0% of data and I can easily give you an example where an index is most efficient when reading *100%* of data (and *any* value in between). When one understands how the CBO functions, one understands why such so-called rules of thumb are a nonsense.

Cheers

Richard Foote

Indexes Demo Preparation

Create Tablespace For Index Demos 		conn uwclass/uwclass

SELECT tablespace_name
FROM user_tablespaces;

conn / as sysdba

CREATE TABLESPACE data_lrg
DATAFILE 'c:\temp\inddemo1.dbf'
SIZE 250M AUTOEXTEND ON
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 10M
SEGMENT SPACE MANAGEMENT MANUAL;

SELECT tablespace_name
FROM user_tablespaces;

ALTER USER uwclass QUOTA UNLIMITED ON data_lrg;

conn uwclass/uwclass

SELECT tablespace_name
FROM user_tablespaces;
Create Table For Index Demos conn uwclass/uwclass

CREATE TABLE index_demo (
person_id NUMBER(10),
gender    VARCHAR2(1),
state     VARCHAR2(2),
textcol   VARCHAR2(2000))
TABLESPACE data_lrg;

Demo Table and Data 		DECLARE
 g index_demo.gender%TYPE := 'F';
BEGIN
  FOR i IN 1 .. 50000
  LOOP
    INSERT INTO index_demo
    (person_id, gender, state, textcol)
    VALUES
    (i, g, 'WA', RPAD('x', 1799, 'x'));

    IF g = 'F' THEN
      g := 'M';
    ELSE
      g := 'F';
    END IF;
  END LOOP;
  COMMIT;

  UPDATE index_demo
  SET state = 'OR'
  WHERE person_id LIKE '%1';

  UPDATE index_demo
  SET state = 'CA'
  WHERE person_id LIKE '%2';

  UPDATE index_demo
  SET state = 'ID'
  WHERE person_id LIKE '%3';

  UPDATE index_demo
  SET state = 'NY'
  WHERE person_id LIKE '%4';

  UPDATE index_demo
  SET state = 'MA'
  WHERE person_id LIKE '%5';

  UPDATE index_demo
  SET state = 'MN'
  WHERE person_id LIKE '%6';

  UPDATE index_demo
  SET state = 'VA'
  WHERE person_id LIKE '%7';

  UPDATE index_demo
  SET state = 'NC'
  WHERE person_id LIKE '%8';

  UPDATE index_demo
  SET state = 'MI'
  WHERE person_id like '%9';

  COMMIT;
END;
/
B*Tree Indexes

Single Column Non-unique 		CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>;
CREATE INDEX ix_index_demo_person_id
ON index_demo(person_id)
PCTFREE 0
TABLESPACE uwdata;

SELECT index_name, index_type, uniqueness, num_rows
FROM user_indexes;

Sort / Nosort 		By default, Oracle sorts indexes in ascending order when it creates the index. You can specify NOSORT to indicate to Oracle that the rows are already stored in the database in ascending order, so that Oracle does not have to sort the rows when creating the index. If the rows of the indexed column or columns are not stored in ascending order, Oracle returns an error. For greatest savings of sort time and space, use this clause immediately after the initial load of rows into a table. If you specify neither of these keywords, SORT is the default.

CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
NOSORT;
CREATE TABLE sort_demo
AS SELECT table_name
FROM user_tables
ORDER BY num_rows;

SELECT *
FROM sort_demo;

CREATE INDEX ix_failure
ON sort_demo (table_name)
PCTFREE 0
TABLESPACE uwdata
NOSORT;

DROP TABLE sort_demo;

CREATE TABLE sort_demo
AS SELECT table_name
FROM user_tables
ORDER BY table_name;

SELECT *
FROM sort_demo;

CREATE INDEX ix_success
ON sort_demo (table_name)
PCTFREE 0
TABLESPACE uwdata
NOSORT;

Single Column Compute Statistics 		CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
COMPUTE STATISTICS;
CREATE INDEX ix_index_demo_person_id
ON index_demo(person_id)
PCTFREE 0
TABLESPACE dats_sml
COMPUTE STATISTICS;

SELECT index_name, index_type, uniqueness, num_rows
FROM user_indexes;

Multiple Column Non-unique 		CREATE INDEX <index_name>
ON <table_name> (<column_name>, <column_name>, ....)
PCTFREE <integer>
TABLESPACE <tablespace_name>;
CREATE INDEX ix_index_demo_gender_state
ON index_demo(person_id, state)
PCTFREE 0
TABLESPACE uwdata;

SELECT index_name, index_type, uniqueness
FROM user_indexes;

SELECT table_name, index_name, column_name, column_position
FROM user_ind_columns
ORDER BY table_name, index_name;

Parallel Index 		CREATE INDEX <index_name>
ON <table_name> (<column_name_list>)
PCTFREE 0
PARALLEL (DEGREE <integer>)
TABLESPACE <tablespace_name>
CREATE INDEX pix_index_demo_gender_state
ON index_demo(person_id, state)
PCTFREE 0
PARALLEL (DEGREE 4)
TABLESPACE uwdata;

SELECT index_name, index_type, degree
FROM user_indexes;

Create Unique Index 		CREATE UNIQUE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>;

Unique constraints are always preferable to unique indexes.
CREATE UNIQUE INDEX uix_index_demo_person_id
ON index_demo(person_id)
PCTFREE 0
TABLESPACE uwdata;

SELECT index_name, index_type, uniqueness
FROM user_indexes;

Now that you know how to build these: Don't!

Create Unusable Index 		CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
UNUSABLE;

Unique constraints are always preferable to unique indexes.
CREATE INDEX uix_index_demo_person_id
ON index_demo(person_id)
PCTFREE 0
TABLESPACE uwdata
UNUSABLE;

SELECT index_name, status
FROM user_indexes;

ALTER INDEX ix_test_newcol REBUILD;

SELECT index_name, status
FROM user_indexes;
Bitmap Indexes
Note: These are primarily intended for read-only data warehouse/decision support systems

Create Bitmap Index 		CREATE BITMAP INDEX <index_name>
ON (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>;
CREATE INDEX ix_gender
ON index_demo (gender)
PCTFREE 5
TABLESPACE uwdata;

exec dbms_stats.gather_index_stats('UWCLASS', 'IX_GENDER');

SELECT index_name, index_type, blevel, leaf_blocks
FROM user_indexes;

DROP INDEX ix_gender;

CREATE BITMAP INDEX bix_gender
ON index_demo (gender)
PCTFREE 5
TABLESPACE uwdata;

exec dbms_stats.gather_index_stats('UWCLASS', 'BIX_GENDER');

SELECT index_name, index_type, blevel, leaf_blocks
FROM user_indexes;
Bitmap Join Indexes

Create Bitmap Join Index 		CREATE BITMAP JOIN INDEX <index_name>
ON <table_name> (<table_name.column_name>)
FROM <table_name, table_name>
WHERE <join_condition>
CREATE TABLE table fact (
prod_id  VARCHAR2(10),
amount   NUMBER(10,2)
PARTITION BY RANGE (prod_id) (
PARTITION p1 VALUES LESS THAN ('M'),
PARTITION p2 VALUES LESS THAN (MAXVALUE));

CREATE TABLE product (
prod_id    VARCHAR2(15),
prod_name  VARCHAR2(30));

ALTER TABLE product
ADD CONSTRAINT pk_product
PRIMARY KEY (prod_id)
USING INDEX
PCTFREE 0;

CREATE BITMAP INDEX bjix_fact_prod
ON facts (product.prod_name)
FROM facts, products
WHERE fact.prod_id = product.prod_id
LOCAL;

SELECT index_name, index_type
FROM user_indexes;

set linesize 121
col inner_table_name format a20
col inner_table_column format a20
col outer_table_name format a20
col outer_table_column format a20

SELECT index_name, inner_table_name, inner_table_column,
outer_table_name, outer_table_column
FROM user_join_ind_columns;

CREATE TABLE facts_new AS
SELECT * FROM fact
WHERE 0 = 1;

CREATE BITMAP INDEX bjix_facts_new_prod
ON facts_new(product.prod_name)
FROM facts_new, products
WHERE facts_new.prod_id = products.prod_id;

SELECT index_name, inner_table_name, inner_table_column,
outer_table_name, outer_table_column
FROM user_join_ind_columns;
Compressed Indexes

Create Compressed Index 		CREATE INDEX <index_name>
ON (<first_column>, <second_column>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
COMPRESS <integer *>;

* Must be at least 1 less than the number of indexed columns
-- For a copy of postal_code visit the Setup Page: [Click Here]
CREATE INDEX ix_pcodes
ON postal_code (state_abbrev, city_name, zip_code)
PCTFREE 0
TABLESPACE uwdata;

ANALYZE INDEX ix_pcodes VALIDATE STRUCTURE;

exec dbms_stats.gather_index_stats(USER, 'IX_PCODES');

SELECT opt_cmpr_count, opt_cmpr_pctsave
FROM index_stats;

SELECT sum(bytes)
FROM user_segments
WHERE segment_name = 'IX_PCODES';

DROP INDEX ix_pcodes;

CREATE INDEX ix_pcodes
ON postal_code (state_abbrev, city_name, zip_code)
PCTFREE 0
TABLESPACE uwdata
COMPRESS 1;

ANALYZE INDEX ix_pcodes VALIDATE STRUCTURE;

exec dbms_stats.gather_index_stats(USER, 'IX_PCODES');

SELECT opt_cmpr_count, opt_cmpr_pctsave
FROM index_stats;

SELECT sum(bytes)
FROM user_segments
WHERE segment_name = 'IX_PCODES';

DROP INDEX ix_pcodes;

CREATE INDEX ix_pcodes
ON postal_code (state_abbrev, city_name, zip_code)
PCTFREE 0
TABLESPACE uwdata
COMPRESS 2;

ANALYZE INDEX ix_pcodes VALIDATE STRUCTURE;

exec dbms_stats.gather_index_stats(USER, 'IX_PCODES');

SELECT opt_cmpr_count, opt_cmpr_pctsave
FROM index_stats;

SELECT sum(bytes)
FROM user_segments
WHERE segment_name = 'IX_PCODES';

-- so pay attention to opt_comp_count
Uncompressing an index | ALTER INDEX <index_name> NOCOMPRESS;
ALTER INDEX cix_pcodes NOCOMPRESS;
Descending
Note: See sys_op_descend under Undocumented Oracle
Related Init Parameters | Oracle treats descending indexes as if they were function-based indexes. You do not need the QUERY REWRITE or GLOBAL QUERY REWRITE privileges to create them, as you do with other function-based indexes. However, as with other function-based indexes, Oracle does not use descending indexes until you first analyze the index and the table on which the index is defined. Oracle ignores DESC if index is bitmapped or if the COMPATIBLE initialization parameter is set to a value less than 8.1.0.

Create Descending Index 		CREATE INDEX <index_name>
ON <table_name>
(<column_name>, [<column_name>] DESC)
PCTFREE <integer>
TABLESPACE <tablespace_name>;
CREATE INDEX ix_index_demo_gender_state
ON index_demo(person_id, state DESC)
PCTFREE 0
TABLESPACE uwdata;

SELECT index_name, index_type
FROM user_indexes;
Function Based Indexes
Related Init Parameters To create a function-based index (FBI) in your own schema on your own table you must have the QUERY REWRITE system privilege. To create the index in another schema or on another schema's table, you must have the GLOBAL QUERY REWRITE privilege.

In either case, the table owner must also have the EXECUTE object privilege on the function(s) used in the creation of the FBI. In addition, in order for Oracle to use FBI's in queries, the QUERY_REWRITE_ENABLED parameter must be set to TRUE, and the QUERY_REWRITE_INTEGRITY parameter must be set to TRUSTED.
FBI Demo Table and Data

CREATE TABLE emp (
empno    NUMBER(4,0),
ename    VARCHAR2(10),
job      VARCHAR2(9),
mgr      NUMBER(4,0),
hiredate DATE,
sal      NUMBER(7,2),
comm     NUMBER(7,2),
deptno   NUMBER(2,0));

INSERT INTO emp VALUES (7369,'SMITH','CLERK',7902,TO_DATE('17-DEC-05'),8000,NULL,20);
INSERT INTO emp VALUES (7499, 'ALLEN', 'SALESMAN',7698, TO_DATE('20-FEB-98'),16000,300,30);
INSERT INTO emp VALUES (7521, 'WARD', 'SALESMAN',7698,TO_DATE('22-FEB-96'),12500,500,30);
INSERT INTO emp VALUES (7566,'JONES','MANAGER',7839,TO_DATE('02-APR-95'),29750,NULL,20);
INSERT INTO emp VALUES (7654, 'MARTIN', 'SALESMAN',7698, TO_DATE('28-SEP-92'),12500,1400,30);
INSERT INTO emp VALUES (7698,'MORGAN','MANAGER',7839,TO_DATE('01-MAY-03'),28500,NULL,30);
INSERT INTO emp VALUES (7782,'CLARK','MANAGER',7839,TO_DATE('09-JUN-91'),24500,NULL,10);
INSERT INTO emp VALUES (7788, 'SCOTT', 'ANALYST',7566,TO_DATE('19-APR-97'),30000,NULL,20);
INSERT INTO emp VALUES (7839,'KING','PRESIDENT',NULL, TO_DATE('17-NOV-91'),50000,NULL,10);
INSERT INTO emp VALUES (7844,'TURNER', 'SALESMAN',7698, TO_DATE('08-SEP-91'),15000,0,30);
INSERT INTO emp VALUES (7876,'ADAMS', 'CLERK',7788,TO_DATE('23-MAY-97'),1100,0,20);
INSERT INTO emp VALUES (7900,'JAMES', 'CLERK',7698,TO_DATE('03-DEC-91'),9500,NULL,30);
INSERT INTO emp VALUES (7902,'FORD','ANALYST',7566,TO_DATE('03-DEC-91'),30000,NULL,20);
INSERT INTO emp VALUES (7934,'MILLER', 'CLERK', 7782,TO_DATE('23-JAN-92'),13000,NULL,10);
COMMIT;

Index based on calculation using two columns 		CREATE INDEX <index_name>
ON <table_name> <function_or_calculation)
PCTFREE <integer>
TABLESPACE <tablespace_name>;
SELECT COUNT(*)
FROM emp;

exec dbms_stats.gather_schema_stats('UWCLASS', CASCADE=>TRUE);

set autotrace traceonly

SELECT ename
FROM emp
WHERE (sal * comm) < 300000;

set autotrace off

CREATE INDEX fbi_emp_sal_x_comm
ON emp (sal * comm);

SELECT index_name, index_type, funcidx_status, status
FROM user_indexes;

SELECT table_name, index_name, column_expression
FROM user_ind_expressions;

exec dbms_stats.gather_schema_stats('UWCLASS', CASCADE=>TRUE);

set autotrace traceonly

SELECT ename
FROM emp
WHERE (sal * comm) < 300000;

set autotrace off

Avoiding full table scans when records are being filtered by a function. 		conn sh/sh

set autotrace traceonly explain

SELECT cust_first_name
FROM customers
WHERE substr(cust_last_name,1,1) = 'L';

CREATE INDEX ix_customers_cust_ln
ON customers(cust_last_name);

SELECT cust_first_name
FROM customers
WHERE substr(cust_last_name,1,1) = 'L';

CREATE INDEX fbi_customers_cust_ln_init
ON customers (SUBSTR(cust_last_name,1,1));

SELECT cust_first_name
FROM customers
WHERE substr(cust_last_name,1,1) = 'L';

DROP INDEX fbi_customers_cust_ln_init;
DROP INDEX ix_customers_cust_ln;

set autotrace off

Avoiding indexing of values that won't be searched.

This demo based on a presentation by Tom Kyte for the Victoria Oracle Users Group 		CREATE TABLE fbidemo AS
SELECT object_name, object_type, temporary
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W';

CREATE INDEX ix_fbidemo
ON fbidemo (temporary)
PCTFREE 0;

CREATE INDEX fbi_fbidemo
ON fbidemo (DECODE(temporary, 'Y', 'Y', NULL));

set linesize 120

SELECT index_type, leaf_blocks, avg_leaf_blocks_per_key, avg_data_blocks_per_key, blevel
FROM user_indexes
WHERE table_name = 'FBIDEMO';

SELECT index_name, column_expression
FROM user_ind_expressions
WHERE column_expression IS NOT NULL;

-- =====================
DROP INDEX ix_fbidemo;
DROP INDEX fbi_fbidemo;

SET AUTOTRACE TRACEONLY

exec dbms_stats.gather_table_stats('UWCLASS', 'FBIDEMO', CASCADE=>TRUE);

SELECT object_name, object_type
FROM fbidemo
WHERE temporary = 'Y';

CREATE INDEX ix_fbidemo
ON fbidemo (temporary)
PCTFREE 0;

exec dbms_stats.gather_table_stats('UWCLASS', 'FBIDEMO', CASCADE=>TRUE);

SELECT object_name, object_type
FROM fbidemo
WHERE temporary = 'Y';

DROP INDEX ix_fbidemo;

CREATE INDEX fbi_fbidemo
ON fbidemo (DECODE(temporary, 'Y', 'Y', NULL));

exec dbms_stats.gather_table_stats('UWCLASS', 'FBIDEMO', CASCADE=>TRUE);

SELECT object_name, object_type
FROM fbidemo
WHERE (DECODE(temporary, 'Y', 'Y', NULL)) = 'Y';

Enforcing data integrity

This demo based on a presentation by Tom Kyte 		CREATE TABLE t (
col1 VARCHAR2(1) NOT NULL,
col2 NUMBER(5) NOT NULL);

CREATE UNIQUE INDEX ix_t
ON t (CASE WHEN col1='N' THEN col2 ELSE NULL END);

INSERT INTO t (col1, col2) VALUES ('Y', 1);
INSERT INTO t (col1, col2) VALUES ('Y', 2);
INSERT INTO t (col1, col2) VALUES ('Y', 1);
INSERT INTO t (col1, col2) VALUES ('N', 1);
INSERT INTO t (col1, col2) VALUES ('N', 2);
INSERT INTO t (col1, col2) VALUES ('N', 1);

Including NULL in an index

SYS_OP_MAP_NONNULL is covered on the undocumented Oracle page of the library 		CREATE TABLE t (
col1 VARCHAR2(1),
col2 NUMBER(5));

INSERT INTO t (col1, col2) VALUES ('Y', NULL);
INSERT INTO t (col1, col2) VALUES ('Y', 2);
INSERT INTO t (col1, col2) VALUES ('Y', NULL);
INSERT INTO t (col1, col2) VALUES ('N', 1);
INSERT INTO t (col1, col2) VALUES ('N', 2);
INSERT INTO t (col1, col2) VALUES ('N', 1);

CREATE INDEX ix_t
ON t (col2);

EXPLAIN PLAN FOR
SELECT *
FROM t
WHERE col2 IS NULL;

SELECT * FROM TABLE(dbms_xplan.display);

CREATE INDEX ix_t_nulls
ON t (sys_op_map_nonnull(col2));

EXPLAIN PLAN FOR
SELECT *
FROM t
WHERE sys_op_map_nonnull(col2) = sys_op_map_nonnull(NULL);

SELECT * FROM TABLE(dbms_xplan.display);
Invisible Indexes

Create Invisible Index 		CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
INVISIBLE;
CREATE TABLE visib AS
SELECT table_name, tablespace_name
FROM all_tables;

CREATE INDEX ix_visib
ON visib(table_name);

CREATE TABLE invis AS
SELECT table_name, tablespace_name
FROM all_tables;

CREATE INDEX ix_invis
ON invis(table_name)
INVISIBLE;

SELECT index_name, table_name, visibility
FROM user_indexes
WHERE index_name LIKE '%VIS%';

EXPLAIN PLAN FOR
SELECT table_name
FROM visib
WHERE table_name = 'SERVERS';

SELECT * FROM TABLE(dbms_xplan.display);

EXPLAIN PLAN FOR
SELECT table_name
FROM invis
WHERE table_name = 'SERVERS';

SELECT * FROM TABLE(dbms_xplan.display);

ALTER SESSION SET "optimizer_use_invisible_indexes" = TRUE;

EXPLAIN PLAN FOR
SELECT table_name
FROM invis
WHERE table_name = 'SERVERS';

SELECT * FROM TABLE(dbms_xplan.display);
Reverse Key Indexes

Create Reverse Key Index 		CREATE INDEX <index_name>
ON <table_name> (<column_name>)
PCTFREE <integer>
TABLESPACE <tablespace_name>
REVERSE;
CREATE INDEX rix_index_demo_person_id
ON index_demo(person_id)
PCTFREE 0
TABLESPACE uwdata
REVERSE;

SELECT index_name, index_type
FROM user_indexes;
Virtual / NoSegment
A virtual index is a non-physical (no-segments) index useful for evaluating whether the optimizer will benefit from index creation prior to creating a physical index. These are not officially supported by Oracle but are used, extensively, by the OEM Grid Control.

Create No Segment Index 		CREATE INDEX <index_name>
ON <table_name> (<column_name>, [<column_name>]) NOSEGMENT;
CREATE TABLE virtual AS
SELECT table_name, tablespace_name
FROM all_tables;

CREATE INDEX vix_virtual_table_name
ON virtual(table_name)
NOSEGMENT;

SELECT segment_name
FROM user_segments
WHERE segment_name = 'VIX_VIRTUAL_TABLE_NAME';

SELECT index_name, index_type
FROM user_indexes
WHERE index_name = 'VIX_VIRTUAL_TABLE_NAME';

desc virtual

SELECT column_name, column_position
FROM user_ind_columns
WHERE index_name = 'VIX_VIRTUAL_TABLE_NAME';

SELECT object_name
FROM user_objects
WHERE object_name = 'VIX_VIRTUAL_TABLE_NAME';

exec dbms_stats.gather_table_stats('UWCLASS', 'VIRTUAL', CASCADE=>TRUE);

SET AUTOTRACE TRACEONLY

SELECT table_name
FROM virtual
WHERE table_name = 'SERVERS';

alter session set "_use_nosegment_indexes" = TRUE;

SELECT table_name
FROM virtual
WHERE table_name = 'SERVERS';

SET AUTOTRACE OFF

ALTER INDEX vix_virtual_table_name COALESCE;
Local And Global Indexes
See the link below to Partitioning
Alter Index

Alter Index Monitor Usage 		ALTER INDEX <index_name> MONITORING USAGE;
ALTER INDEX ix_index_demo_gender_state MONITORING USAGE;

exec dbms_stats.gather_index_stats(OWNNAME=>'UWCLASS', INDNAME=>'IX_INDEX_DEMO_GENDER_STATE');

SELECT COUNT(*)
FROM index_demo
WHERE gender = 'M';

SELECT *
FROM v$object_usage;

ALTER INDEX ix_index_demo_gender_state NOMONITORING USAGE;

Alter Index Rename 		ALTER INDEX <index_name> RENAME TO <new_name>;
SELECT index_name
FROM user_indexes;

ALTER INDEX bix_gender RENAME TO ixb_gender;

SELECT index_name
FROM user_indexes;

ALTER INDEX ixb_gender RENAME TO bix_gender;
Alter Index Coalesce | ALTER INDEX <index_name> COALESCE;
ALTER INDEX ix_index_demo_gender_state COALESCE;
Alter Index Rebuild | ALTER INDEX <index_name> REBUILD;
ALTER INDEX ix_index_demo_gender_state REBUILD;

Alter Index Rebuild and
Change Tablespace 		ALTER INDEX <index_name>
REBUILD TABLESPACE <tablspace_name>;
SELECT index_name, tablespace_name
FROM user_indexes;

ALTER INDEX ix_index_demo_gender_state
REBUILD TABLESPACE uwdata;

SELECT index_name, tablespace_name
FROM user_indexes;

Alter Index Allocate Extent 		ALTER INDEX <index_name>
SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;

SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;

SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;

SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;
ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;
ALTER INDEX ix_index_demo_gender_state ALLOCATE EXTENT;

SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

Alter Index Deallocate Unused 		ALTER INDEX <index_name> DEALLOCATE UNUSED;
SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state
DEALLOCATE UNUSED KEEP 512;
Alter Index Deallocate Unused ALTER INDEX <index_name> DEALLOCATE UNUSED
KEEP <integer> <K|M>;
SELECT SUM(bytes), SUM(blocks)
FROM user_extents
WHERE segment_name = 'IX_INDEX_DEMO_GENDER_STATE';

ALTER INDEX ix_index_demo_gender_state
DEALLOCATE UNUSED;
Alter Index Logging | ALTER INDEX <index_name>
select index_name, logging from user_indexes;

ALTER INDEX bix_gender NOLOGGING;

select index_name, logging from user_indexes;

ALTER INDEX bix_gender LOGGING;

select index_name, logging from user_indexes;
Alter Index Parallel | ALTER INDEX <index_name> PARALLEL <integer>;
SELECT index_name, degree
FROM user_indexes;

ALTER INDEX bix_gender PARALLEL 2;

SELECT index_name, degree
FROM user_indexes;
Alter Index Disable
(applies only to FBIs) 		DISABLE applies only to a function-based index. This clause enables you to disable the use of a function-based index.

ALTER INDEX <index_name> DISABLE;
ALTER INDEX fbi_employee_sal_x_comm DISABLE;
Alter Index Enable
(applies only to FBIs) 		ALTER INDEX <index_name>
ALTER INDEX fbi_employee_sal_x_comm ENABLE;

Alter Index Usable / Unusable 		ALTER INDEX <index_name> UNUSABLE;
SELECT index_name, status
FROM user_indexes;

ALTER INDEX bix_gender UNUSABLE;

SELECT index_name, status
FROM user_indexes;

ALTER INDEX bix_gender REBUILD;

SELECT index_name, status
FROM user_indexes;

Alter Index Reverse 		ALTER INDEX <index_name> REBUILD REVERSE;
CREATE INDEX ix_index_demo_person_id
ON index_demo (person_id);

SELECT index_name, index_type
FROM user_indexes;

ALTER INDEX ix_index_demo_person_id REBUILD REVERSE;

SELECT index_name, index_type
FROM user_indexes;
Alter Index Update Block Reference | See Index Organized Tables
Drop Index
Drop Index | DROP INDEX <index_name>;
DROP INDEX ix_index_demo_gender_state;
Index Block Dump
Dumping an index tree including branch block headers, leaf block headers, and leaf block contents col object_name format a30

SELECT object_name, object_id
FROM user_objects;

ALTER SESSION SET EVENTS 'immediate trace name treedump level 54220';
Alternative index dump | ORADEBUG DUMP TREEDUMP 54220
Index Related Queries

Analyze Index 		set pages 60
set lines 80
col avg_leaf_blocks_per_key format 999
col avg_leaf_blocks_per_key head leafs_key
col avg_data_blocks_per_key format 999
col avg_data_blocks_per_key head data_key

SELECT index_name,blevel,distinct_keys,
avg_leaf_blocks_per_key,avg_data_blocks_per_key
FROM user_indexes;

Show all indexes and their columns and column positions 		set linesize 132
set verify off
col index_owner format a20
col column_name format a20
col tablespace_name format a20
break on table_name skip 1;

SELECT c.index_owner, i.index_name,
DECODE(i.uniqueness, 'UNIQUE', 'YES', 'NO') UNIQUENESS,
c.column_name, c.column_position, i.tablespace_name
FROM dba_ind_columns c, dba_indexes i
WHERE i.index_name = c.index_name
AND i.table_owner = c.table_owner
ORDER BY c.index_owner, i.index_name, c.column_position;
Related Topics
Autotrace
Clustering Factor
Clusters
DBMS_I_INDEX_UTL
DBMS_INDEX_UTL
DBMS_SPACE.CREATE_INDEX_COST
DBMS_STATS
Index Organized Table
Nested Tables
Partitioning


Oracle Functions

Oracle Miscellaneous Functions
General Information
Note: These are functions not covered on other site pages
LNNVL

Evaluates a condition when one or both operands of the condition may be null

 LNNVL(<condition>)
conn hr/hr

SELECT COUNT(*) FROM employees WHERE commission_pct >= .2;

SELECT COUNT(*) FROM employees WHERE LNNVL(commission_pct >= .2);
NULLIF

Compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.

 NULLIF(<expression1>, <expression2>)
conn hr/hr

SELECT e.last_name, NULLIF(e.job_id, j.job_id) "OLD JOB ID"
FROM employees e, job_history j
WHERE e.employee_id = j.employee_id
ORDER BY last_name;
NVL

Returns a Value if the Expression IS NULL 		NVL(
s1 VARCHAR2 CHARACTER SET ANY_CS,        -- expression
s2 VARCHAR2 CHARACTER SET s1%CHARSET)    -- return value if null
RETURN VARCHAR2 CHARACTER SET s1%CHARSET;
set serveroutput on

DECLARE
 i PLS_INTEGER;
BEGIN
  SELECT NVL(i, 93)
  INTO i
  FROM dual;

  dbms_output.put_line('i1: ' || i);

  SELECT NVL(i, 39)
  INTO i
  FROM dual;

  dbms_output.put_line('i2: ' || i);
END;
/
NVL2

Returns First Value if NOT NULL, Second Value if NULL

Thanks Cary Hogan and Kaifer Bohus for the corrections. 		NVL2(<expression>, <return_if_not_null>, <return_if_null>)
CREATE TABLE test (
category  VARCHAR2(20),
outval    NUMBER(3),
inval     NUMBER(3));

INSERT INTO test VALUES ('Groceries', 10, NULL);
INSERT INTO test VALUES ('Payroll', NULL, 100);
INSERT INTO test VALUES ('Groceries', 20, NULL);
INSERT INTO test VALUES ('Payroll', NULL, 200);
INSERT INTO test VALUES ('Groceries', 30, NULL);

SELECT * FROM test;

SELECT category, SUM(NVL2(outval, -outval, inval)) NET
FROM test
GROUP BY category;

Note: If used in PL/SQL must be used in the form of SELECT INTO
thus you can not use this syntax:

set serveroutput on

DECLARE
 x NUMBER(5);
BEGIN
  x := NVL2(10, 10, 20);
  dbms_output.put_line(TO_CHAR(x));
END;
/

but you can write:

DECLARE
 x NUMBER(5);
BEGIN
  SELECT NVL2(10, 10, 20)
  INTO x
  FROM dual;

  dbms_output.put_line(TO_CHAR(x));
END;
/
SQLCODE
number of the most recent exception raised by PL/SQL. 0 if none. | standard.sqlcode RETURN PLS_INTEGER;
set serveroutput on

BEGIN
  dbms_output.put_line(SQLCODE);
END;
/

See Exceptions Page
SQLERRM
Error message associated with the specified code standard.sqlerrm RETURN VARCHAR2;

standard.sqlerrm(code_in IN INTEGER := SQLCODE) RETURN VARCHAR2
set serveroutput on

BEGIN
  dbms_output.put_line(SQLERRM);
END;
/

See Exceptions Page
SQL_GUID

Generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier, a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread. 		SYS_GUID() RETURN RAW
CREATE TABLE t (
rid RAW(32),
col VARCHAR2(20));

desc t

INSERT INTO t
(rid, col)
VALUES
(SYS_GUID(), 'ABC');

INSERT INTO t
(rid, col)
VALUES
(SYS_GUID(), 'DEF');

SELECT * FROM t;
SYS_TYPEID

Returns the typeid of the most specific type of the operand 		SYS_TYPEID(<object_type_value>)
CREATE TYPE person_t AS OBJECT (name VARCHAR2(30), ssn NUMBER)
NOT FINAL;
/

CREATE TABLE persons OF person_t;

INSERT INTO persons
VALUES
(person_t('Morgan', 123));

SELECT name, SYS_TYPEID(VALUE(p)) TYPE_ID FROM persons p;
UID
User Session ID SELECT UID
FROM dual;

SELECT user#
FROM gv$session
WHERE schemaname = USER;
USER
User As Logged On | SELECT USER FROM dual;
USERENV(deprecated: use SYS_CONTEXT)
Usage SELECT userenv('<parameter>')
FROM dual;
Session info. stored with DBMS_APPLICATION_INFO SELECT USERENV('CLIENT_INFO') FROM dual;

exec dbms_application_info.set_client_info('TEST');

SELECT USERENV('CLIENT_INFO') FROM dual;
The current audit entry number. The audit entryid sequence is shared between fine-grained audit records and regular audit records. You cannot use this attribute in distributed SQL statements. SELECT userenv('ENTRYID')
FROM dual;
Current instance identifier SELECT userenv('INSTANCE')
FROM dual;
ISDBA returns 'TRUE' if the user has been authenticated as having DBA privileges either through the operating system or through a password file. SELECT userenv('ISDBA')
FROM dual;
The ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter. SELECT userenv('LANG')
FROM dual;
The language and territory currently used by your session, along with the database character set, in the form:
language_territory dot characterset. 		SELECT userenv('LANGUAGE')
FROM dual;
The auditing session identifier. You cannot use this option in distributed SQL statements. SELECT userenv('SESSIONID')
FROM dual;

SELECT audsid
FROM v_$session;
TERMINAL returns the operating system identifier for the terminal of the current session. In distributed SQL statements, this parameter returns the identifier for your local session. In a distributed environment, this parameter is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations. SELECT userenv('TERMINAL')
FROM dual;
VALUE

Takes as its argument a correlation variable (table alias) associated with a row of an object table and returns object instances stored in the object table. The type of the object instances is the same type as the object table. 		VALUE(correlation_variable)
CREATE TYPE address_t AS OBJECT (
hno    NUMBER,
street VARCHAR2(40),
city   VARCHAR2(20),
zip    VARCHAR2(5),
phone  VARCHAR2(10));
/

CREATE TYPE person AS OBJECT (
name        VARCHAR2(40),
dateofbirth DATE,
homeaddress address_t,
manager REF person );
/

CREATE OR REPLACE TYPE person_t AS OBJECT (
name VARCHAR2(100),
ssn  NUMBER)
NOT FINAL;
/

CREATE TABLE persons OF person_t;

INSERT INTO persons VALUES (person_t('Bob', 1234));

SELECT VALUE(p) FROM persons p;
Related Topics
Character Set Functions
Conversion Functions
Date Functions
Data Mining Functions
Exception Handling
Numeric Functions
String Functions
SYS_CONTEXT
Timestamp
XML Functions


Oracle Model Clause OLAP Warehouse DataMart SQL

Oracle Model Clause
Version 10.2
Set up
Materialized View CREATE MATERIALIZED VIEW sales_view AS
SELECT country_name country, prod_name prod,
calendar_year year,
SUM(amount_sold) sale, COUNT(amount_sold) cnt
FROM sales, times, customers, countries, products
WHERE sales.time_id = times.time_id
AND sales.prod_id = products.prod_id
AND sales.cust_id = customers.cust_id
AND customers.country_id = countries.country_id
GROUP BY country_name, prod_name, calendar_year;
Basic Model Clause model [main]
[ reference models ]
[ partition by (<cols>)]
dimension by (<cols>)
measures (<cols>)
[ ignore nav ] | [ keep nav ]
[ rules
[ upsert | update]
[ automatic order | sequential order ]
[ iterate (n) [ until <condition>]
]
(<cell_assignment> = <expression> ...)
This statement partitions data by country, so the formulas are applied to data of one country at a time. Our sales fact data ends with 2001, so any rules defining values for 2002 or later will insert new cells. The first rule defines the sales of a video games called "Bounce" in 2002 as the sum of its sales in 2000 and 2001. The second rule defines the sales for Y Box in 2002 to be the same value they were for 2001. The third rule defines a product called "2_Products," which is simply the sum of the Bounce and Y Box values for 2002. Since the values for 2_Products are derived from the results of the two prior formulas, the rules for Bounce and Y Box must be executed before the 2_Products rule.
col country format a20
col prod format a20

SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country IN ('Italy','Japan')
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (
sales['Bounce', 2002] = sales['Bounce', 2001] + sales['Bounce', 2000],
sales['Y Box', 2002] = sales['Y Box', 2001],
sales['2_Products', 2002] = sales['Bounce', 2002] + sales['Y Box',2002])
ORDER BY country, prod, year;
Positional Cell Reference – Single cell access and upserts | The value for the cell reference is matched to the appropriate dimension based on its position in the expression. The DIMENSION BY clause of the model determines the position assigned to each dimension: in this case, the first position is product ("prod") and the second position is year.
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales['Bounce', 2000] = 10)
ORDER BY country, prod, year;
Add a new cell | The formula in the query above sets the year value to 2005 and thus creates a new cell in the array.
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (
sales['Bounce', 2005] = 20 )
ORDER BY country, prod, year;
Symbolic Cell Reference: MultiI-Cell Access And Updates
         The query, below, uses "symbolic cell reference." With symbolic cell references, the standard SQL conditions are used to determine the cells which are part of a formula. You can use conditions such as <,>, IN, and BETWEEN. In this example the formula applies to any cell which has product value equal to Bounce and a year value greater than 1999. The example shows how a single formula can access multiple cells.
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales[prod='Bounce', year>1999] = 10)
ORDER BY country, prod, year;

Positional And Symbolic Cell References In A Single Query 		Since our example data has no values beyond the year 2001, any rule involving the year 2002 or later requires insertion of a new cell. The same applies to any new product name we define here. In the third formula we define a new product '2_Products' for 2005, so a cell will be inserted for it. The first rule, for Bounce in 2002, inserts new cells since it is positional notation. The second rule, for Y Box, uses symbolic notation, but since there are already values for 'Y Box' in the year 2001, it updates those values. The third rule, for '2_Products' in 2005, is positional, so it can insert new cells, and we see them in the output.
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view WHERE country IN ('Italy','Japan')
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (
sales['Bounce', 2002] = sales['Bounce', year = 2001] ,
--positional notation: can insert new cell
sales['Y Box', year>2000] = sales['Y Box', 1999],
--symbolic notation: can update existing cell
sales['2_Products', 2005] = sales['Bounce', 2001] +
sales['Y Box', 2000] )
--positional notation: permits creation of new cell
--for new product
ORDER BY country, prod, year;
Multi-Cell References On The Right Side Of A Formula | In the query above we use a BETWEEN condition to specify multiple cells on the right side of the formula, and these are aggregated to a single value with the MAX() function.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod,
year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales['Bounce', 2005] = 100 + MAX(sales)['Bounce',
year BETWEEN 1998 AND 2002])
ORDER BY country, prod, year;
CV Function
Use Left-Side Values In Right Side Calculations The two CV() functions used in the formula return the year dimension value of the cell currently referenced on the left side. When the left side of the formula above references the cell 'Bounce' and 1999, the right side expression would resolve to:
sales['Mouse Pad', 1999] + 0.2 * sales['Y Box', 1999].

Similarly, when the left side references the cell 'Bounce' and 2000, the right side expression we would evaluate is:
sales['Mouse Pad', 2000] + 0.2 * sales['Y Box', 2000].

CV() function takes a dimension key as its argument. It is also possible to use CV() without any argument as in CV() which causes positional referencing. Therefore the formula above can be written as:
s['Bounce', year BETWEEN 1995 AND 2002] = s['Mouse Pad', CV()] + 0.2 * s['Y Box', CV()]
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country  ='Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales['Bounce', year BETWEEN 1995 AND 2002] =
sales['Mouse Pad', CV(year)] + 0.2 * sales['Y Box', CV(year)])
ORDER BY country, prod, year;
Used In Expressions For Inter-Row Calculations | Note that the blank cells in the results are NULLs. The formula results in a null if there is no value for the product two years earlier. None of the products has a value for 1998, so in each case the 1999 growth calculation is NULL.
SELECT SUBSTR(country,1,10) country, SUBSTR(prod,1,10) prod, year, sales, growth_pct
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales, 0 growth_pct)
RULES (growth_pct[prod IN ('Bounce','Y Box', 'Mouse Pad'),
year BETWEEN 1998 and 2001] = 100 * (sales[CV(prod), CV(year)] -
sales[CV(prod), CV(year)-1]) / sales[CV(prod), CV(year)-1])
ORDER BY country, prod, year;
Wildcard With ANY Keyword
Any Keyword Demo Note that in the MEASURES clause above, we use the placeholder value of 0 when specifying the new measure growth_pct. Other numbers would also work as placeholder values. This query gives the same results as the prior query because the full data set ranges from 1998 to 2001, and that is the range specified in the prior query.

ANY can be used in cell references to include all dimension values including NULLs. In symbolic reference notation, we use the phrase "IS ANY". Note that the ANY wildcard prevents cell insertion when used with either positional or symbolic notation.
SELECT SUBSTR(country,1,10) country, SUBSTR(prod,1,10) prod, year, sales, growth_pct
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales, 0 growth_pct)
RULES (growth_pct[prod IN ('Bounce','Y Box','Mouse Pad'),
ANY] = 100 * (sales[CV(prod), CV(year)] - sales[CV(prod), CV(year)-1]) / sales[CV(prod), CV(year) -1])
ORDER BY country, prod, year;
FOR Loops
FOR LOOP To Create Specify New Cells By using positional notation on the left side of the formulas, we ensure that cells for these products in the year 2005 will be inserted if they are not already present in the array. This technique is bulky since it requires as many formulas as there are products. If we have to work with dozens of products, it becomes an unwieldy approach. With FOR we can reword this computation so it is concise yet has exactly the same behavior.

The FOR construct can be thought of as a tool to make a single formula generate multiple formulas with positional references, thus enabling creation of new cells (UPSERT behavior).
SELECT SUBSTR(country,1,20) country,
SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales[FOR prod IN ('Mouse Pad', 'Bounce', 'Y Box'),
2005] = 1.3 * sales[CV(prod), 2001])
ORDER BY country, prod, year;
FOR LOOP To Range Over A Value Sequence Project sales values of Mouse Pad for the years 2005 to 2012 so that they are equal to 120% of the value in 2001 using the sequence generation of the FOR construct.

This kind of FOR construct can be used for dimensions of numeric, date and datetime datatypes. The increment/decrement expression of the FOR loop should be numeric for numeric dimensions and can be numeric or interval for dimensions of date or datetime types.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales['Mouse Pad', FOR year FROM 2005 TO 2012 INCREMENT 1]
= 1.2 * sales[CV(prod), 2001])
ORDER BY country, prod, year;
Order Of Evaluation
Automatic Ordering Of Rule Application By default, formulas are evaluated in the order they appear in the MODEL clause.

The following query uses Automatic Order, so it recognizes that Bounce and Y Box sales must be calculated before 2_Products sales.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country IN ('Italy', 'Japan')
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES AUTOMATIC ORDER (sales['2_Products', 2002] =
sales['Bounce', 2002] + sales['Y Box', 2002],
sales['Bounce', 2002] = sales['Bounce', 2001] + sales['Bounce', 2000], sales['Y Box', 2002] = sales['Y Box', 2001])
ORDER BY country, prod, year;
Sequential Ordering Of Rule Application | Same as the above but with sequential ordering. This query uses Sequential Order, so it does not calculate the values for Bounce and Y Box before 2_Products, and 2_Products is assigned as NULL.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country IN ('Italy','Japan')
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES SEQUENTIAL ORDER (sales['2_Products', 2002] =
sales['Bounce', 2002] + sales['Y Box', 2002],
sales['Bounce', 2002] = sales['Bounce', 2001] + sales['Bounce', 2000], sales['Y Box', 2002] = sales['Y Box', 2001])
ORDER BY country, prod, year;
Null Measures And Missing Cells
By default, NULL cell measure values are treated the same way as NULLs are treated elsewhere in SQL. Missing cells are treated as cells with NULL measure value.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (sales['Mouse Pad', 2005] =
sales['Mouse Pad', 1999] + sales['Mouse Pad', 2004])
ORDER BY country, prod, year;
Once a NULL has been found in a set of values, it can cause many dependent calculations to result in NULLs. Therefore it can be more useful to treat NULLS and missing values as non-NULL values. In this way, NULLs will not be propagated through a set of calculations. You can use the IGNORE NAV option (NAV stands for non-available values) to default NULLs and missing cells to the following values:
  • 0 for numeric data
  • empty string for character/string data
  • 01-JAN-2001 for data type data
  • NULL for other data types

Note that the default behavior is KEEP NAV which treats NULLs in the standard manner and treats missing values as NULLs. When we add the IGNORE NAV option to the query above, it returns a numeric value for sales even though the value for 2004 is missing.
SELECT SUBSTR(country,1,20) country, SUBSTR(prod,1,15) prod, year, sales
FROM sales_view
WHERE country = 'Italy'
MODEL IGNORE NAV RETURN UPDATED ROWS
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale sales)
RULES (
sales['Mouse Pad', 2005] =
sales['Mouse Pad', 1999] + sales['Mouse Pad', 2004])
ORDER BY country, prod, year;
Reference Models

Calculate projected sales figures for two different countries and show these projections in both the country currency and US dollars 		REFERENCE model_name ON (query)
DIMENSION BY (cols)
MEASURES (cols) [reference options]
CREATE TABLE dollar_conv(country VARCHAR2(30),
exchange_rate NUMBER);

INSERT INTO dollar_conv VALUES('Canada', 0.75);
INSERT INTO dollar_conv VALUES('Brazil', 0.34);
COMMIT;

col localsales format 9,999,999.99
col dollarsales format 999,999.99

SELECT SUBSTR(country,1,20) country, year,
localsales, dollarsales
FROM sales_view
WHERE country IN ( 'Canada', 'Brazil')
GROUP BY country, year
MODEL RETURN UPDATED ROWS
REFERENCE conv_refmodel ON (
SELECT country, exchange_rate AS er FROM dollar_conv)
DIMENSION BY (country) MEASURES (er) IGNORE NAV
MAIN main_model
DIMENSION BY (country, year)
MEASURES (SUM(sale) sales, 0 localsales, 0 dollarsales)
IGNORE NAV RULES (
/* assuming that sales in Canada grow by 22% */
localsales['Canada', 2005] = sales[CV(country), 2001] * 1.22,
dollarsales['Canada', 2005] = sales[CV(country), 2001] * 1.22 *
conv_refmodel.er['Canada'],
/* assuming that sales in Brazil grow by 28% */
localsales['Brazil', 2005] = sales[CV(country), 2001] * 1.28,
dollarsales['Brazil', 2005] =
sales[CV(country), 2001] * 1.28 * er['Brazil']);

Working With Arrays Of Different Dimensionality 		Calculate sales for Brazil and Canada, applying the 2005 growth figures and converting the values to US dollars.
CREATE TABLE growth_rate(
country VARCHAR2(30),
year NUMBER, growth_rate NUMBER);

INSERT INTO growth_rate VALUES('Brazil', 2004, 17);
INSERT INTO growth_rate VALUES('Brazil', 2005, 28);
INSERT INTO growth_rate VALUES('Canada', 2004, 13);
INSERT INTO growth_rate VALUES('Canada', 2005, 22);
COMMIT;

SELECT SUBSTR(country,1,20) country, year, localsales, dollarsales
FROM sales_view
WHERE country IN ('Canada','Brazil')
GROUP BY country, year
MODEL RETURN UPDATED ROWS
REFERENCE conv_refmodel ON (
SELECT country, exchange_rate FROM dollar_conv)
DIMENSION BY (country c)
MEASURES (exchange_rate er) IGNORE NAV
REFERENCE growth_refmodel ON (
SELECT country, year, growth_rate FROM growth_rate)
DIMENSION BY (country c, year y)
MEASURES (growth_rate gr) IGNORE NAV
MAIN main_model
DIMENSION BY (country, year)
MEASURES (SUM(sale) sales, 0 localsales, 0 dollarsales) IGNORE NAV
RULES (
localsales[FOR country IN ('Brazil', 'Canada'), 2005] =
sales[CV(country), 2001] * (100+gr[CV(country), CV(year)])/100 ,
dollarsales[FOR country IN ('Brazil', 'Canada'),2005] =
sales[CV(country), 2001] * (100 + gr[CV(country), CV(year)])/100 * er[CV(country)])
ORDER BY country;
ITERATE Models
Iterate through and evaluate formulas a specified number of times | ITERATE (<number_of_iterations>)
CREATE TABLE ledger (
account VARCHAR2(20),
balance NUMBER(10,2));

INSERT INTO ledger VALUES ('Salary', 100000);
INSERT INTO ledger VALUES ('Capital_gains', 15000);
INSERT INTO ledger VALUES ('Net', 0);
INSERT INTO ledger VALUES ('Tax', 0);
INSERT INTO ledger VALUES ('Interest', 0);
COMMIT;

SELECT account, bal
FROM ledger
MODEL IGNORE NAV
DIMENSION BY (account)
MEASURES (balance bal)
RULES SEQUENTIAL ORDER
ITERATE (100) (
bal['Net'] = bal['Salary'] + bal['Capital_gains']
- bal['Interest'] - bal['Tax'],
bal['Tax'] = (bal['Salary'] - bal['Interest']) * 0.38
+ bal['Capital_gains'] * 0.28,
bal['Interest'] = bal['Net'] * 0.30);
ITERATE With An UNTIL Condition
Until Condition Demo | ITERATE (<number_of_iterations>) UNTIL (some_condition_is_met>)
col bal format 999,999.99

SELECT account, bal
FROM ledger
MODEL IGNORE NAV
DIMENSION BY (account)
MEASURES (balance bal)
RULES SEQUENTIAL ORDER
ITERATE (100) UNTIL (ABS(
(PREVIOUS(bal['Net'])-bal['Net'])) < 0.01)
(bal['Net'] = bal['Salary'] + bal['Capital_gains'] -
bal['Interest'] - bal['Tax'],
bal['Tax'] = (bal['Salary'] - bal['Interest']) * 0.38 + bal['Capital_gains'] *0.28,
bal['Interest'] = bal['Net'] * 0.30,
bal['Iteration Count'] = ITERATION_NUMBER + 1);
ITERATION_NUMBER
Returns an integer representing the completed iteration through the model rules. The ITERATION_NUMBER function returns 0 during the first iteration. For each subsequent iteration, it returns the equivalent of iteration_number plus one. | ITERATION_NUMBER(
CREATE OR REPLACE VIEW sales_view_ref AS
SELECT country_name country, prod_name prod, calendar_year year,
SUM(amount_sold) sale, COUNT(amount_sold) cnt
FROM sales, times, customers, countries, products
WHERE sales.time_id = times.time_id
AND sales.prod_id = products.prod_id
AND sales.cust_id = customers.cust_id
AND customers.country_id = countries.country_id
AND (customers.country_id = 52779 OR customers.country_id = 52776)
AND (prod_name = 'Standard Mouse' OR prod_name = 'Mouse Pad')
GROUP BY country_name,prod_name,calendar_year;

set linesize 121
col country format a20
col prod format a20

SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER ITERATE(2)
(s['Mouse Pad', 2001 + ITERATION_NUMBER] =
 s['Mouse Pad', 1998 + ITERATION_NUMBER])
ORDER BY country, prod, year;
PRESENTNNV
Returns expr1 when, prior to the execution of the model_clause, cell_reference exists and is not null. Otherwise it returns expr2. | PRESENTNNV(<cell_reference>, <expression1>, <expression2>)
conn sh/sh

set linesize 121
col country format a20
col prod format a20

SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER (
s['Mouse Pad', 2002] =
PRESENTNNV(s['Mouse Pad', 2002], s['Mouse Pad', 2002], 10))
ORDER BY country, prod, year;
PRESENTV
Returns expr1 when, prior to the execution of the model_clause, cell_reference exists. Otherwise it returns expr2. | PRESENTV(<cell_reference>, <expression1>, <expression2>)
conn sh/sh

set linesize 121
col country format a20
col prod format a20

SELECT country, prod, year, s
FROM sales_view_ref
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER (
s['Mouse Pad', 2001] =
PRESENTV(s['Mouse Pad', 2000], s['Mouse Pad', 2000], 0))
ORDER BY country, prod, year;
Related Topics
Select


Oracle Nested Table Constraints
Primary Key Constraint

Object Identifier 		CREATE OR REPLACE TYPE address_type AS OBJECT (
street  VARCHAR2(30),
city    VARCHAR2(30),
state   VARCHAR2(2),
zipcode VARCHAR2(5));
/

desc address_type

SELECT text
FROM user_source
WHERE name = 'ADDRESS_TYPE';

CREATE OR REPLACE TYPE person_type AS OBJECT (
name         VARCHAR2(30),
dob          DATE,
home_address address_type,
work_address address_type);
/

desc person_type

set describe depth all linenum on indent on

desc person_type

SELECT text
FROM user_source
WHERE name = 'PERSON_TYPE';

SELECT type_name, type_oid, typecode, incomplete, final,
instantiable
FROM user_types;

CREATE TABLE people OF person_type (
CONSTRAINT pk_people
PRIMARY KEY (name))
OBJECT IDENTIFIER IS PRIMARY KEY;

desc people

-- not here
SELECT table_name, nested
FROM user_tables;

-- not here
SELECT table_name
FROM user_nested_tables;

-- here
SELECT table_name, nested
FROM user_all_tables;

col object_name format a30

SELECT object_name, object_type
FROM user_objects;

-- Note: use type name from above query
SELECT text
FROM user_source
WHERE name = 'SYS_YOID0000117802$';

SELECT constraint_name, constraint_type, table_name
FROM user_constraints;
DANGLING
When a REF value points to a nonexistent object, the REF is said to be "dangling". A dangling REF is different from a null REF. To determine whether a REF is dangling or not, use the condition IS [NOT] DANGLING. | DANGLING
conn oe/oe

SELECT o.customer_ref.cust_email
FROM oc_orders o
WHERE o.customer_ref IS NOT DANGLING;

SELECT o.customer_ref.cust_email
FROM oc_orders o
WHERE o.customer_ref IS DANGLING;
DEREF
returns the object reference of argument expr, where expr must return a REF to an object | DEREF(<expression>)
See Demo below
MAKE_REF
Creates a REF to a row of an object view or a row in an object table whose object identifier is primary key based. | MAKE_REF(<table_or_view_name>, <key>)
SELECT MAKE_REF (oc_inventories, 3003) FROM dual;
REF
Takes a correlation variable (table alias) associated with a row of an object table or an object view. A REF value is returned for the object instance that is bound to the variable or row. | REF(<correlation_variable>)
See Demo below
Referential Constraint Demo

Foreign Key Without OID Reference
CREATE OR REPLACE TYPE cust_address_t AS OBJECT (
street_address VARCHAR2(40),
postal_code    VARCHAR2(10),
city           VARCHAR2(30),
state_province VARCHAR2(2),
country_id     VARCHAR2(2));
/

CREATE TABLE address_table OF cust_address_t;

desc address_table

INSERT INTO address_table
VALUES ('123 Main St.','98040','Mercer Island','WA','US');

INSERT INTO address_table
VALUES ('1 Broadway','10202','New York','NY','US');

INSERT INTO address_table
VALUES ('2462 Edgar Crest','V6L 2C4','Vancouver','BC','CN');

SELECT * FROM address_table;

SELECT REF(tabref) FROM address_table tabref;

CREATE TABLE customer_addresses (
add_id  NUMBER(10),
address REF cust_address_t SCOPE IS address_table);

set describe depth all linenum on indent on

desc customer_addresses

INSERT INTO customer_addresses
SELECT 11, REF(a)
FROM address_table a
WHERE country_id = 'CN';

SELECT *
FROM customer_addresses;

ROLLBACK;

INSERT INTO customer_addresses
SELECT 11, REF(a)
FROM address_table a;

SELECT *
FROM customer_addresses;

col deref_add format a80

SELECT add_id, DEREF(address) DEREF_ADD
FROM customer_addresses;
Check Constraint
Conditions of check constraints cannot contain the following constructs:
  • Dereferencing of REF columns (for example, using the DEREF function)
  • Nested table columns or attributes
  • Calls to user-defined functions
Related Topics
Constraints
Conversion Functions (REFTOHEX)
Nested Tables


Oracle Nested Tables
Version 10.2
General Information
Note: A nested table is a table stored within the structure of another table.
Data Dictionary Objects
collection$ | tab$ | type$
dba_nested_tables | all_nested_tables | user_nested_tables
dba_nested_table_cols | all_nested_table_cols | user_nested_table_cols
dba_source | all_source | user_source
dba_tables | all_tables | user_tables
dba_tab_cols | all_tab_cols | user_tab_cols
dba_types | all_types | user_types
System Privileges CREATE TYPE
CREATE ANY TYPE
DROP ANY TYPE

CREATE TABLE
CREATE ANY TABLE
DROP ANY TABLE

Nested Table Example 		CREATE OR REPLACE TYPE CourseList AS TABLE OF VARCHAR2(64);
/

desc courselist

SELECT type, text
FROM user_source
WHERE name = 'COURSELIST';

CREATE TABLE department (
name     VARCHAR2(20),
director VARCHAR2(20),
office   VARCHAR2(20),
courses  CourseList)
NESTED TABLE courses STORE AS courses_tab;

desc department

desc courses_tab

SELECT table_name, nested
FROM user_tables;

set linesize 121
col table_name format a20
col data_type format a30
col table_type_name format a15
col parent_table_column format a10

SELECT column_name, data_type, data_length
FROM user_tab_cols
WHERE table_name = 'DEPARTMENT';

SELECT table_name, table_type_owner, table_type_name,
parent_table_column
FROM user_nested_tables;
Insert into Nested Table SELECT cardinality(courses)
FROM department;

INSERT INTO department
(name, director, office, courses)
VALUES
('English', 'Lynn Saunders', 'Breakstone Hall 205', CourseList(
'Expository Writing',
'Film and Literature',
'Modern Science Fiction',
'Discursive Writing',
'Modern English Grammar',
'Introduction to Shakespeare',
'Modern Drama',
'The Short Story',
'The American Novel'));

SELECT * FROM department;

SELECT cardinality(courses)
FROM department;
Update a nested table DECLARE
   new_courses CourseList :=
   CourseList('Expository Writing',
   'Film and Literature',
   'Discursive Writing',
   'Modern English Grammar',
   'Realism and Naturalism',
   'Introduction to Shakespeare',
   'Modern Drama',
   'The Short Story',
   'The American Novel',
   '20th-Century Poetry',
   'Advanced Workshop in Poetry');
BEGIN
   UPDATE department
   SET courses = new_courses
   WHERE name = 'English';
END;
/

SELECT * FROM department;
Drop nested table SELECT table_name
FROM user_tables;

DROP TABLE courses_tab;

 You cannot directly drop the storage table of a nested table. Instead, you must drop the nested table column using the ALTER TABLE ... DROP COLUMN clause.

desc department

ALTER TABLE department
DROP COLUMN courses;
Table Unnesting
Collection Unnesting Demo To select data from a nested table column you use the TABLE function to treat the nested table as columns of a table. This process is called "collection unnesting".
SELECT t1.department_id, t2.*
FROM hr_info t1, TABLE(t1.people) t2
WHERE t2.department_id = t1.department_id;

SELECT t1.name, t2.*
FROM department t1, TABLE(t1.courses) t2;
Related Topics
Collections
Instead-Of Triggers
Nested Table Constraints
REF Cursors
Tables
Types
VArrays


Oracle Net Services SQLNET SQL*NET

Oracle Net Services
Version 10.2
Node Checking
Windows Note: to find used ports on a Windows server:

c:\> netstat -a

to find the executable using that port:

c:\> netstat -b

to find the port by protocol:

c:\> netstat -p TCP (or other protocol name)

for help with additional options:

c:\> netstat -h
Note: Protocol specific parameters are not dynamic. They are read only at startup.

In 8i in protocol.ora
In 9i and 10g in sqlnet.ora
Node checking | TCP.VALIDNODE_CHECKING=<yes/no>
tcp.validnode_checking=yes
Excluding nodes

Use this parameter to specify which clients are denied access to the database 		TCP.EXCLUDED_NODES=
(hostname | ip_address, hostname | ip_address,...)
TCP.EXCLUDED_NODES=(finance.us.acme.com,
mktg.us.acme.com, 144.25.5.25)
Invited nodes

Use this parameter to check for invited and excluded nodes. This list takes precedence over the TCP.EXCLUDED_NODES
parameter if both lists are present 		TCP.INVITED_NODES=(hostname | ip_address, hostname | ip_address, ...)
TCP.INVITED_NODES=(sales.us.acme.com,
hr.us.acme.com, 144.185.5.73)
TCP delay

Use this parameter to preempt delays in buffer flushing within the TCP/IP protocol stack 		TCP.NODELAY=<yes/no>
TCP.NODELAY=yes
SQLNET.ORA Parameters
Authentication Services sqlnet.authentication_services (<value>)

Value | Description
NONE | Disables logging on without password
NTS | NT operating system authentication
ALL | All authentication methods
For Advanced Security Only
dcegssapi | DCE GSSAPI authentication
kerberos5 | Kerberos authentication
radius | RADIUS authentication
sqlnet.authentication_services = (NONE)
Client Identifier | Sets a unique identifier for a client computer. The identifier is passed to the listener with any connection request and is included in the Audit Trail. The identifier can be any alphanumeric string up to 128 characters long.
sqlnet.client_registration=42
Connection Routing | names.directory_path=(<values>)
names.directory_path=(LDAP, TNSNAMES, ONAMES, HOSTNAME)
Inactive Session Expiration Time Kill inactive SQLNET sessions. If set to a non-zero value enables DCD (Dead Connection Detection)

sqlnet.expire_time = <integer_minutes>
sqlnet.expire_time=10
Minimum Client Version | sqlnet.allowed_logon_version= <version_number>
sqlnet.allowed_logon_version=10
Names Directory Path names.directory_path=
(order_of_naming_methods_for_client_name_resolution)

 Naming Method Values
directory naming | A naming method that resolves a database service, net service name, or net service alias to a connect descriptor stored in a central directory server
external naming | A naming method that uses a third-party naming service, such as NIS or CDS
host naming | Name resolution in a TCP/IP environment to resolve names through the existing name resolution service.
local naming | A naming method that locates network addresses by using information configured and stored on each individual client's tnsnames.ora file. Local naming is most appropriate for simple distributed networks with a small number of services that change infrequently.
Network Information Service (NIS) | Sun Microsystems' Yellow Pages (yp) client/server protocol
NAMES.DIRECTORY_PATH=(tnsnames, onames, hostname)
Names Server Default Domain | names.default_domain=<domain_name>
NAMES.DEFAULT_DOMAIN=psoug.org
SDU Size Oracle Corporation recommends setting this parameter in both the client-side and server-side sqlnet.ora file to ensure the same SDU size is used throughout a connection. When the configured values of client and database server do not match for a session, the lower of the two values is used.

Default 2048 (2K) / Range 512 to 32768 (32K)
DEFAULT_SDU_SIZE=4096
Security Parameters
Cryptography Seed Value This optional parameter is required for when encryption or checksumming are turned on. Encryption is turned on if the SQLNET.ENCRYPTION_CLIENT parameter is specified for the client and the SQLNET.ENCRYPTION_SERVER parameter is specified for the database server

sqlnet.crypto_seed = <10_to_70_random_characters>

Default: qwertyuiopasdfghjkl;zxcvbnm,.s1
sqlnet.crypto_seed=pqowieuryt;laksjdhfgmznxbcv,.s1
Checksum Client Behavior | sqlnet.checksum_client = <accepted | rejected | requested | required>
sqlnet.checksum_client=required

Default: accepted
Checksum Server Behavior | sqlnet.checksum_server = <accepted | rejected | requested | required>
sqlnet.checksum_server=required

Default: accepted
Checksum Type Client Behavior | sqlnet.crypto_checksum_types_client = <md5 | sha1>
sqlnet.crypto_checksum_types_client=md5

Default: accepted
Checksum Type Server Behavior | sqlnet.crypto_checksum_types_server = <md5 | sha1>
sqlnet.crypto_checksum_types_server=md5

Default:
Encryption Client | sqlnet.encryption_client = <accepted | rejected | requested | required>
sqlnet.encryption_client=required

Default: accepted
Encryption Server | sqlnet.encryption_server = <accepted | rejected | requested | required>
sqlnet.encryption_server=required

Default:
Encryption Type: Client sqlnet.encryption_types_client = <value>

value choices:
3des112 for triple DES with a two-key (112 bit) option
3des168 for triple DES with a three-key (168 bit) option
des for standard 56 bit key size
des40 for 40 bit key size
rc4_40 for 40 bit key size
rc4_56 for 56 bit key size
rc4_128 for 128 bit key size
rc4_256 for 256 bit key size
sqlnet.encryption_types_client=(rc4_256)

Default: all avialable algorithms
Encryption Type: Server sqlnet.encryption_types_server = <value>

value choices:
3des112 for triple DES with a two-key (112 bit) option
3des168 for triple DES with a three-key (168 bit) option
des for standard 56 bit key size
des40 for 40 bit key size
rc4_40 for 40 bit key size
rc4_56 for 56 bit key size
rc4_128 for 128 bit key size
rc4_256 for 256 bit key size
sqlnet.encryption_types_server=(rc4_256)

Default: all available algorithms
Connection Tracing Parameters
LOG_DIRECTORY_CLIENT | log_directory_client = <operating system path>
log_directory_client=/oracle/network/log
LOG_DIRECTORY_SERVER | log_directory_server = <trace_level>
log_directory_server=/oracle/network/log
LOG_FILE_CLIENT | log_file_client = <file_name>
log_file_client=sqlnet.log
LOG_FILE_SERVER | log_file_server = <file_name>
log_file_server=sqlnet.log
TRACE_LEVEL_CLIENT | trace_level_client = <trace_level>
trace_level_client=16
TRACE_LEVEL_SERVER | trace_level_sever = <trace_level>
trace_level_server=16
TRACE_LEVEL_UNIQUE Avoid multiple sessions in a single trace file

trace_level_unique = <TRUE | FALSE>
trace_level_unique=TRUE
TRACE_DIRECTORY_CLIENT | The directory into which the trace file is written
trace_directory_client=c:\oracle\product\ora10\network\trace
Connection Manager Parameters
Control Utility | CMCTL
Administer | administer
CMCTL> administer
Current instance CMAN_perrito is not yet started
Connections refer to (ADDRESS=(PROTOCOL=TCP)(HOST=perrito)
(PORT=1521).
The command completed successfully.
CMCTL:CMAN_perrito
Close | close connections
CMCTL>
Exit | exit
CMCTL> exit
Help | help
CMCTL>
Quit
CMCTL>
Reload
CMCTL>
Resume
CMCTL>
Save Password | save_passwd
CMCTL>
Set
CMCTL>
Show
CMCTL>
Shutdown
CMCTL>
Sleep
CMCTL>
Startup | startup
CMCTL> startup
Suspend
CMCTL>
Listener Parameters
Control Utility | LSNRCTL
Change Password | change_password
LSNRCTL> change_password
Exit | exit
LSNRCTL> exit
Quit | quit
LSNRCTL> quit
Reload | reload
LSNRCTL> reload
Save Configuration | save_config
LSNRCTL> save_config
Services | services
LSNRCTL> services
Set set <current_listener | displaymode |
     inbound_connect_timeout | log_directory | log_file |
     log_status | password | rawmode | save_config_on_stop |
     startup_waittime | trc_directory | trc_file | trc_level>
LSNRCTL> set

or ... in SQLNET.ORA

#Timeout Parameters
SQLNET.INBOUND_CONNECT_TIMEOUT = 300
SQLNET.SEND_TIMEOUT = 300
SQLNET.RECV_TIMEOUT = 300
Show show <current_listener | displaymode |
      inbound_connect_timeout | log_directory | log_file |
      log_status | rawmode | rules | save_config_on_stop |
      snmp_visible | startup_waittime | trc_directory |
      trc_file | trc_level>
LSNRCTL> show
Start | start
LSNRCTL> start
Status | status
LSNRCTL> status
Stop | stop
LSNRCTL> stop
Trace | trace <1 | 2>
LSNRCTL> trace 1
Version | version
LSNRCTL> version
Directory Usage (LDAP) Parameters
Tracing Parameters
Other Related Topics
Profile


Oracle Numeric Functions

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
General
Note: Demos referencing the Oracle sample schemas such as oe and sh have been copied from the documentation at http://tahiti.oracle.com for our convenience. Examples too complex for this page are referenced back to the original source where links may or may not be maintained.

Credit for their development belongs to Francisco Abedrabbo and his team.
ABS
Returns the absolute value of a number | ABS(<value>)
SELECT ABS(-100) FROM dual;
ACOS
Returns the arc cosine of a number | ACOS(<value>)
SELECT ACOS(0.5) ARC_COSINE FROM dual;
ASIN
Returns the arc sin of a number | ASIN(<value>)
SELECT ASIN(0.5) ARC_SINE FROM dual;
ATAN
Returns the arc tanget of a number | ATAN(<value>)
SELECT ATAN(0.5) ARC_TANGENT FROM dual;
ATAN2
Arc tangent of the first value divided by the arc tangent of the second | ATAN2(<value>, <value>)
SELECT ATAN2(0.5, 0.4) ARC_TANGET_DIV FROM dual;
AVG
Returns the average of a column of numbers | AVG(<value>)
SELECT AVG(initial_extent) FROM user_tables;

SELECT AVG(DISTINCT initial_extent) FROM user_tables;
BITAND
Computes an AND operation on the bits of expr1 and expr2, both of which must resolve to nonnegative integers

Overload 1 		BITAND(LEFT IN PLS_INTEGER, RIGHT IN PLS_INTEGER) RETURN PLS_INTEGER
TBD

Overload 2 		BITAND(LEFT IN INTEGER, RIGHT IN INTEGER) RETURN INTEGER
conn oe/oe

SELECT order_id, customer_id,
 DECODE(BITAND(order_status,1),1, 'Warehouse','PostOffice')
 Location,
 DECODE(BITAND(order_status,2),2, 'Ground', 'Air') Method,
 DECODE(BITAND(order_status,4),4,'Insured','Certified') Receipt
FROM orders
WHERE order_status < 8;
CEIL
Smallest integer greater than or equal to a decimal value | CEIL(<value>)
SELECT CEIL(12345.67) FROM dual;
COALESCE

Returns the first non-null value 		COALESCE(<value>, <value>, ....)
CREATE TABLE test (
col1  NUMBER(3),
col2  NUMBER(3),
col3  NUMBER(3));

INSERT INTO test VALUES (1, NULL, NULL);
INSERT INTO test VALUES (NULL, 2, NULL);
INSERT INTO test VALUES (NULL, NULL, 3);
INSERT INTO test VALUES (1, NULL, 3);
INSERT INTO test VALUES (NULL, 2, 3);

SELECT * FROM test;

SELECT COALESCE(col1, col2, col3) FROM test;
CORR
Returns the coefficient of correlation of a set of number pairs | For information go to tahiti.oracle.com
CORR_K
Calculates the Pearson's correlation coefficient | For information go to tahiti.oracle.com
CORR_S
Calculates the Spearman's rho correlation coefficient | For information go to tahiti.oracle.com
COS
Returns the cosine of a number (an angle expressed in radians) | COS(<value>)
SELECT COS(180*3.1415926/180) COSINE FROM dual;
COSH
The hyperbolic cosine of a number | COSH(<value>)
SELECT COSH(0) HYPERBOLIC_COS FROM dual;
COUNT
The number of rows returned by a query | COUNT(<value>)
-- To create the all_objs table: Click Here

SELECT COUNT(*) FROM all_objs;
COVAR_POP

The population covariance of a set of number pairs 		COVAR_POP(<expression1>, <expression2>)
conn sh/sh

SELECT t.calendar_month_number,
COVAR_POP(s.amount_sold, s.amount_sold) AS CP,
COVAR_SAMP(s.amount_sold, s.amount_sold) AS CS
FROM sales s, times t
WHERE s.time_id = t.time_id
AND t.calendar_year = 1998
GROUP BY t.calendar_month_number;
COVAR_SAMP
The sample covariance of a set of number pairs | COVAR_POP(<expression1>, <expression2>)
See COVAR_POP demo.
CUME_DIST

Returns the cumulative distribution of a value in a group of values 		CUME_DIST(<value>)
conn oe/oe

SELECT CUME_DIST(15500, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) CUME_DIST_OF_15500
FROM employees;
DENSE_RANK
Computes the rank of a row in an ordered group of rows | DENSE_RANK(<value>)
conn oe/oe

SELECT DENSE_RANK(15500, .05) WITHIN GROUP
(ORDER BY salary DESC, commission_pct) DENSE_RANK_OF_15500
FROM employees;
DUMP
Returns | DUMP(<value>)
col drows format a30

SELECT table_name, num_rows, DUMP(num_rows) DROWS
FROM user_tables;
EXP

Returns e raised to to an exponential power 		EXP(<value>)
SELECT 2.71828183 * 2.71828183 FROM dual;

SELECT EXP(2) FROM dual;

SELECT 2.71828183 * 2.71828183 * 2.71828183 FROM dual;

SELECT EXP(3) FROM dual;
FIRST

Returns the row ranked first using DENSE_RANK 		SELECT <aggregate_function(column_name)> KEEP
(DENSE_RANK FIRST ORDER BY <column_name>)
FROM <table_name>
GROUP BY <column_name>;
conn oe/oe

SELECT department_id,
MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) WORST,
MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) BEST
FROM employees
GROUP BY department_id;
FLOOR
Returns the largest integer less than or equal to a decimal value | FLOOR(<string_or_column>)
SELECT FLOOR(12345.67) FROM dual;
GREATEST
Returns the largest of multiple values | GREATEST(<value>, <value>, .... )
SELECT GREATEST(9, 67.6, 10) FROM dual;
LAST
Returns the row ranked last using DENSE_RANK | See FIRST demo
LEAST
Returns the smallest of multiple values | LEAST(<value>, <value>, ....)
SELECT LEAST(9, 67.6, 10) FROM dual;
LENGTH
Returns length in characters | LENGTH(<value>)
SELECT bytes, LENGTH(bytes) FROM user_segments;
LENGTHB
Returns length in bytes | LENGTHB(<value>)
SELECT bytes, LENGTHB(bytes) FROM user_segments;
Note: Additional forms of LENGTH (LENGTHC, LENGTH2, and LENGTH4) are also available.
LN
Returns the natural log of a number | LN(<value>)
SELECT LN(2) NATURAL_LOG FROM dual;
LOG
Returns the logarithm, base m of n | LOG(<m_value>,<n_value>)
SELECT LOG(10,100) FROM dual;

SELECT LOG(100,10) FROM dual;
MAX
Returns the maximum value returned by a query | MAX(<column_name>)
SELECT MAX(initial_extent) FROM all_tables;
MEDIAN
Returns the middle value of a set | MEDIAN(<column_name>)
SELECT MEDIAN(initial_extent) FROM all_tables;
MIN
Returns the minimum value returned by a query | MIN(<column_name>)
SELECT MIN(initial_extent) FROM all_tables;
MOD
Returns the modulus of a number. Same as remainder except uses FLOOR | MOD(<m_value>, <n_value>)
SELECT MOD(3, 2) FROM dual;

SELECT MOD(6, 2) FROM dual;
NANVL

Returns Alternate Number If The Value Is Not A Number 		NANVL(<value_evaluated>, <value_returned>)
CREATE TABLE fpd (
dec_num    NUMBER(10,2),
bin_double BINARY_DOUBLE,
bin_float  BINARY_FLOAT);

INSERT INTO fpd VALUES (0, 'NaN', 'NaN');
COMMIT;

SELECT * FROM fpd;

SELECT bin_double, NANVL(bin_double, 0) FROM fpd;

SELECT bin_float, NANVL(bin_float, 0) FROM fpd;

INSERT INTO fpd VALUES ('NaN', 'NaN', 'NaN');
COMMIT;

SELECT bin_float, NANVL(dec_number, 0) FROM fpd;
NVL

Returns a Value if the Expression IS NULL 		NVL(<expression>, <return_value>)
set serveroutput on

DECLARE
 i PLS_INTEGER;
BEGIN
  SELECT NVL(i, 93)
  INTO i
  FROM dual;

  dbms_output.put_line('i1: ' || i);

  SELECT NVL(i, 39)
  INTO i
  FROM dual;

  dbms_output.put_line('i2: ' || i);
END;
/
NVL2

Returns First Value if NULL, Second Value if NOT NULL 		NVL2(<expression>, <return_if_value>, <return_if_not_null>)
CREATE TABLE t (
category  VARCHAR2(25),
outval    NUMBER(3),
inval     NUMBER(3));

INSERT INTO t VALUES ('Groceries', 10, NULL);
INSERT INTO t VALUES ('Payroll', NULL, 100);
INSERT INTO t VALUES ('Groceries', 20, NULL);
INSERT INTO t VALUES ('Payroll', NULL, 200);
INSERT INTO t VALUES ('Groceries', 30, NULL);

SELECT * FROM t;

SELECT category, SUM(NVL2(outval, -outval, inval)) NET
FROM t
GROUP BY category;
PERCENT_RANK
Calculates for a row r and a sort specification, the rank of row r minus 1 divided by the number of rows in the aggregate group PERCENT_RANK(<expression>) WITHIN GROUP
(ORDER BY <expression> <ASC | DESC> NULLS <FIRST | LAST>)
conn oe/oe

SELECT PERCENT_RANK(15000, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) "Percent-Rank"
FROM employees;
PERCENTILE_CONT
Takes a percentile value and a sort specification, and returns an interpolated value that would fall into that percentile value with respect to the sort specification PERCENTILE_CONT(<expression>) WITHIN GROUP
(ORDER BY <expression> <ASC | DESC> NULLS <FIRST | LAST>)
OVER (<query_partition_clause>);
conn oe/oe

SELECT department_id, PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY salary DESC) MEDIAN_CONT
FROM employees
GROUP BY department_id;
PERCENTILE_DISC

Takes a percentile value and a sort specification and returns an element from the set 		PERCENTILE_DISC(<expression>) WITHIN GROUP
(ORDER BY <expression> <ASC | DESC> NULLS <FIRST | LAST>)
OVER (<query_partition_clause>);
conn oe/oe

SELECT department_id, PERCENTILE_DISC(0.5)
WITHIN GROUP (ORDER BY salary DESC) MEDIAN_DISC
FROM employees
GROUP BY department_id;
POWER
Returns m_value raised to the n_value power | POWER(<m_value>, <n_value>)
SELECT 2*2*2 FROM dual;

SELECT POWER(2,3) FROM dual;
RANK
Calculates the rank of a value in a group of values | RANK(<column_name>) WITHIN GROUP
SELECT RANK(15500, .05) WITHIN GROUP
(ORDER BY salary, commission_pct) SAL_RANK
FROM employees;
REGR_ (Linear Regression) Functions
REGR_AVGX For more information go to http://tahiti.oracle.com

SELECT s.channel_id,
REGR_AVGX(s.quantity_sold, p.prod_list_price) AVGLISTP,
REGR_AVGY(s.quantity_sold, p.prod_list_price) AVGQSOLD,
REGR_COUNT(s.quantity_sold, p.prod_list_price) COUNT,
REGR_INTERCEPT(s.quantity_sold, p.prod_list_price) INTCPT,
REGR_R2(s.quantity_sold, p.prod_list_price) RSQR,
REGR_SLOPE(s.quantity_sold, p.prod_list_price) SLOPE
FROM sales s, products p
WHERE s.prod_id=p.prod_id
AND p.prod_category='Women'
AND s.time_id=to_DATE('10-OCT-2000')
GROUP BY s.channel_id;
REGR_AVGY
REGR_COUNT
REGR_INTERCEPT
REGR_R2
REGR_SLOPE
REGR_SXX
REGR_SXY
REGR_SYY
REMAINDER
Returns the modulus of a number (the remainder from dividing m by n. Same as mod except uses ROUND and doesn't use floor. | REMAINDER(<m_value>, <n_value>)
SELECT REMAINDER(2,3) FROM dual;
ROUND
Returns a value rounded to integer places | ROUND(<value>, <integer>)
SELECT ROUND(3.1415926, 4) FROM dual;
SIGN
Returns the sign of a number | SIGN(<value>)
SELECT SIGN(15) FROM dual;
SELECT SIGN(0) FROM dual;
SELECT SIGN(-5) FROM dual;
SIN
Returns the sine of a number | SIN(<value>)
SELECT SIN(2) SINE FROM dual;
SINH
Returns the hyperbolic sine of a number | SINH(<value>)
SELECT SINH(2) HYPERBOLIC_SINE FROM dual;
SQRT
Returns the square root of a number | SQRT(<value>)
SELECT SQRT(2) FROM dual;
STATS_ (Statistical) Functions
STATS_BINOMIAL_TEST For information go to tahiti.oracle.com
STATS_CROSSTAB
STATS_F_TEST
STATS_KS_TEST
STATS_MW_TEST
STATS_ONE_WAY_ANOVA
STATS_T_TEST
STATS_WSR_TEST
STDDEV_POP
STDDEV_SAMP
STATS_MODE

Returns the value that occurs with the greatest frequency 		STATS_MODE(<expression>)
conn oe/oe

SELECT department_id, STATS_MODE(salary)
FROM employees
GROUP BY department_id;

SELECT salary, COUNT(*)
FROM employees
WHERE department_id = 50
GROUP BY salary;
STDDEV

Sample standard deviation of an expression 		STDDEV(<expression>)
conn oe/oe

SELECT STDDEV(salary) AS DEVIATION FROM employees;
SUM
Computes the sum of an expression | SUM(<column_name>)
SELECT SUM(initial_extent) FROM all_tables;

SELECT SUM(DISTINCT initial_extent) FROM all_tables;
TAN
Tangent in radians | TAN(<value>)
SELECT TAN(135 * 3.14159265359/180) FROM dual;
TANH
Hyperbolic tangent | TANH(<value>) RETURN NUMBER;
SELECT TANH(135 * 3.14159265359/180) FROM dual;
TRUNC
Truncates a Number to the Specified Number of Decimal Places | TRUNC(<value>, <decimal_places>) RETURN NUMBER;
SELECT TRUNC(15.79, 1) FROM dual;

SELECT TRUNC(15.79, -1) FROM dual;
VAR_POP
Population Variance of a Set of Numbers | VAR_POP(<column_name>) RETURN NUMBER;
SELECT VAR_POP(data_length) FROM all_tab_cols;
VAR_SAMP
Sample Variance of a Set of Numbers | VAR_SAMP(<column_name>) RETURN NUMBER;
SELECT VAR_SAMP(data_length) FROM all_tab_cols;
VARIANCE
Variance of an Expression | VARIANCE(<value>)
SELECT VARIANCE(initial_extent) FROM user_tables;
VSIZE
Byte Size | VSIZE(e IN NUMBER) RETURN NUMBER
SELECT VSIZE(initial_extent) FROM all_tables;
WIDTH_BUCKET

Construct Equi-width Histograms

n+1 bucket is for overflow 		WIDTH_BUCKET(<value>, <min_value>, <max_value>, <number_of_buckets>);
conn oe/oe

SELECT customer_id, cust_last_name, credit_limit,
WIDTH_BUCKET(credit_limit, 100, 4000, 10) CREDIT_GRP
FROM customers
WHERE nls_territory = 'SWITZERLAND'
ORDER BY credit_grp;
Related Topics
Analytic Functions
CAST
Conversion Functions
Date Functions
Data Mining Functions
Miscellaneous Functions
String Functions
XML Functions


Oracle ORA_HASH HASH

Oracle ORA_HASH Function
Demo

Joining Tables Via A Hash 		ORA_HASH(<value>, <max_buckets>, <seed_value>)
CREATE TABLE t1 AS
SELECT owner, table_name, tablespace_name
FROM all_tables;

CREATE TABLE t2 AS
SELECT owner, table_name, tablespace_name
FROM all_indexes;

ALTER TABLE t1
ADD (hashcol NUMBER(38));

ALTER TABLE t2
ADD (hashcol NUMBER(38));

UPDATE t1
SET hashcol = ORA_HASH(owner || table_name ||  tablespace_name);

UPDATE t2
SET hashcol = ORA_HASH(owner || table_name ||  tablespace_name);

CREATE INDEX ix_t1_columns
ON t1 (owner, table_name, tablespace_name);

CREATE INDEX ix_t2_columns
ON t2 (owner, table_name, tablespace_name);

CREATE INDEX ix_t1_hash ON t1 (hashcol);

CREATE INDEX ix_t2_hash ON t2 (hashcol);

set linesize 121

SELECT * FROM t1
WHERE rownum < 101;

SELECT * FROM t2
WHERE rownum < 101;

--=========================================
set serveroutput on

DECLARE
 CURSOR rcur IS
 SELECT t1.table_name, t2.tablespace_name
 FROM t1, t2
 WHERE t1.table_name = t2.table_name
 AND t1.tablespace_name = t2.tablespace_name;

 CURSOR hcur IS
 SELECT t1.table_name, t2.tablespace_name
 FROM t1, t2
 WHERE t1.hashcol = t2.hashcol;

 n PLS_INTEGER;
BEGIN
  n := dbms_utility.get_time;
  FOR i IN 1..1000
  LOOP
    FOR rec IN rcur
    LOOP
      NULL;
    END LOOP;
  END LOOP;

  n := dbms_utility.get_time - n;
  dbms_output.put_line('w/o Hashing: ' || n);

  n := dbms_utility.get_time;
  FOR i IN 1..1000
  LOOP
    FOR rec IN hcur
    LOOP
      NULL;
    END LOOP;
  END LOOP;

  n := dbms_utility.get_time - n;
  dbms_output.put_line('w/ Hashing: ' || n);
END;
/
Sampling Data Via A Hash conn sh/sh

SELECT SUM(amount_sold) FROM sales
WHERE ORA_HASH(cust_id || prod_id, 99, 5) = 0;


Oracle Built-in Operators SQL PL/SQL

Oracle Built-in Operators
Arithmetic Operators
Addition | <numeric_value> + <numeric_value>
SELECT 100 + 10 FROM dual;
Subtraction | <numeric_value> - <numeric_value>
SELECT 100 - 10 FROM dual;
Multiplication | <numeric_value> * <numeric_value>
SELECT 100 * 10 FROM dual;
Division | <numeric_value> / <numeric_value>
SELECT 100 / 10 FROM dual;
Power (PL/SQL Only) | <numeric_value> ** <numeric_value>
set serveroutput on

BEGIN
  dbms_output.put_line('2 to the 5th is ' || TO_CHAR(2**5));
END;
/
Concatenation Operators
Concatenate | SELECT <string> || <string>
SELECT 'Daniel ' || 'Morgan' FROM dual;
Date Operators
Addition | SELECT <date_value> + <numeric_value>
SELECT SYSDATE + 10 FROM dual;
Subtraction | SELECT <date_value> - <date_value>
SELECT SYSDATE - 10 FROM dual;
Hierarchical Query Operators
CONNECT, CONNECT BY, CONNECT BY PRIOR, and CONNECT BY ROOT will be dealt with on a separate page on Hierarchical Queries
Multiset Operators - Combine the results of two nested tables into a single nested table
Multiset | CAST(MULTISET(<select statement> AS object_type)
See CAST page
Multiset Except <nested_table1> MULTISET
EXCEPT <ALL | DISTINCT <nested_table2>
SELECT customer_id, cust_address_ntab1
MULTISET EXCEPT DISTINCT cust_address_ntab2 RESULTS
FROM customer_demo;
Multiset Intersect <nested_table1> MULTISET
INTERSECT <ALL | DISTINCT <nested_table2>
SELECT customer_id, cust_address_ntab1
MULTISET INTERSECT DISTINCT cust_address_ntab2 RESULTS
FROM customer_demo;
Multiset Union <nested_table1> MULTISET
UNION <ALL | DISTINCT <nested_table2>
SELECT customer_id, cust_address_ntab1
MULTISET UNION DISTINCT cust_address_ntab2 RESULTS
FROM customer_demo;
Pivot Operators (new 11g)
Note: Traditional pivoting is done with DECODE and CASE so you may want to look at those demos on the DECODE page

Pivot / Unpivot Demo 1 		PIVOT [XML] (<aggregate function> (expression) [AS <alias>]
FOR (<column_list>)
IN <subquery>)

UNPIVOT [<INCLUDE | EXCLUDE> NULLS] (<column_list>) FOR (<column_list>)
IN (<column_list>) [AS (<constant_list>)])
conn oe/oe

CREATE TABLE pivot_table AS
SELECT * FROM (
  SELECT EXTRACT(YEAR FROM order_date) year, order_mode, order_total
  FROM orders)
PIVOT (SUM(order_total)
FOR order_mode
IN ('direct' AS Store, 'online' AS Internet));

desc pivot_table

SELECT * FROM pivot_table;

SELECT * FROM pivot_table
UNPIVOT (yearly_total FOR order_mode
IN (store AS 'direct', internet AS 'online'))
ORDER BY year, order_mode;

SELECT * FROM pivot_table
UNPIVOT INCLUDE NULLS (yearly_total FOR order_mode
IN (store AS 'direct', internet AS 'online'))
ORDER BY year, order_mode;

Pivot / Unpivot Demo 2 		SELECT * FROM (
  SELECT program_id, customer_id, 1 CNT
  FROM airplanes)
PIVOT (SUM(cnt)
FOR customer_id
IN ('AAL' AS AAL, 'DAL' AS DAL, 'ILC' AS ILC, 'NWO' AS NWO, 'SAL' AS SAL, 'SWA' AS SWA, 'USAF' AS USAF));

CREATE TABLE pivot_table AS
SELECT * FROM (
  SELECT program_id, customer_id, 1 CNT
  FROM airplanes)
PIVOT (SUM(cnt)
FOR customer_id
IN ('AAL' AS AAL, 'DAL' AS DAL, 'ILC' AS ILC, 'NWO' AS NWO, 'SAL' AS SAL, 'SWA' AS SWA, 'USAF' AS USAF));

desc pivot_table

SELECT * FROM pivot_table;

SELECT * FROM pivot_table
UNPIVOT (sumx FOR AAL IN (AAL AS 'AAL', DAL AS 'DAL', ILC AS 'ILC', NWO AS 'NWO', SAL AS 'SAL', SWA AS 'SWA', USAF AS 'USAF'))
ORDER BY 2,1;

Unpivot with GROUP BY 		SELECT *
FROM (
  SELECT ename, job, sal, comm
  FROM emp)
  UNPIVOT (income_component_value FOR income_component_type
  IN (sal, comm))
ORDER BY 1;

SELECT *
FROM emp
WHERE ename = 'ALLEN';

SELECT ename, job, SUM(income_component_value) income
FROM (
  SELECT ename, job, sal, comm
  FROM emp)
  UNPIVOT (income_component_value FOR income_component_type
  IN (sal, comm))
GROUP BY ename, job
ORDER BY 1;

SELECT *
FROM emp
WHERE ename = 'ALLEN';
Set Operators
INTERSECT | <expression> INTERSECT <expression>
SELECT DISTINCT table_name
FROM user_tables
INTERSECT
SELECT DISTINCT table_name
FROM user_indexes;
MINUS | <expression> MINUS <expression>
SELECT DISTINCT table_name
FROM user_tables
MINUS
 SELECT DISTINCT table_name
FROM user_indexes;
UNION ALL | <expression> UNION ALL <expression>
SELECT DISTINCT table_name
FROM user_tables
UNION ALL
SELECT DISTINCT table_name
FROM user_indexes;
UNION | <expression> UNION <expression>
SELECT DISTINCT table_name
FROM user_tables
UNION
SELECT DISTINCT table_name
FROM user_indexes;
Other Related Topics
Cast
Delete
Hierarchical Queries
Insert
Regular Expressions
Select
Update
User Defined Operators
Where Clause
Wildcards


Oracle Rank
Version 10.2
General
Calculates the rank of a value in a group of values. Rows with equal values for the ranking criteria receive the same rank. Oracle then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers.
Aggregation
As an aggregate function, RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. The arguments of the function must all evaluate to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments must be the same and their types must be compatible.
Single Column RANK as Aggregation Function RANK(<rank expression>) WITHIN GROUP
(ORDER BY <expression> <ASC|DESC> NULLS <FIRST|LAST>)
conn hr/hr

-- the following query returns the rank for a $15,500 salary

SELECT RANK(15500) WITHIN GROUP
(ORDER BY salary DESC NULLS LAST) SAL_RANK
FROM employees;
Multiple Column RANK as Aggregation Function RANK(<rank expression>) WITHIN GROUP
(ORDER BY <expression> <ASC|DESC> NULLS <FIRST|LAST>)
The following query returns the rank of a hypothetical employee with a salary of $15,500 and a commission of 3.6%

conn hr/hr

SELECT RANK(.36, 15500) WITHIN GROUP
(ORDER BY commission_pct, salary) RANK
FROM employees;
Multiple Column RANK as Aggregation Function RANK(<rank expression>) WITHIN GROUP
(ORDER BY <expression> <ASC|DESC> NULLS <FIRST|LAST>)
The following query returns the rank of a hypothetical employee with a salary of $15,500 and a commission of 3.6%

conn hr/hr

SELECT RANK(.36, 15500) WITHIN GROUP
(ORDER BY commission_pct NULLS FIRST, salary) RANK
FROM employees;
Analytic
As an analytic function, RANK computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the order_by_clause.
RANK Analytic Function | RANK() OVER (<order by clause>)
-- find the employee with the 2nd highest salary

conn hr/hr

SELECT *
FROM (
  SELECT employee_id, last_name, salary,
  RANK() OVER (ORDER BY salary DESC) EMPRANK
  FROM employees)
WHERE emprank = 2;

-- verify result
SELECT employee_id, last_name, salary,
RANK() OVER (ORDER BY salary DESC) EMPRANK
FROM employees;
-- find the 20 largest tables in a tablespace

conn / as sysdba

col segment_name format a30

SELECT * FROM (
SELECT segment_name, blocks, RANK() OVER(ORDER BY blocks DESC) SZ
FROM dba_segments
WHERE segment_type = 'TABLE'
AND TABLESPACE_NAME = 'UWDATA')
WHERE SZ < 21;
RANK Analytic Function | RANK() OVER (<query partition clause> <order by clause>)
SELECT department_id,last_name,salary,commission_pct,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC, commission_pct) RANK
FROM employees;

SELECT department_id,last_name,salary,commission_pct,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC, commission_pct) RANK
FROM employees
WHERE department_id = 80;
Other Related Topics
Numeric Functions


Oracle Ref Cursors
Version 10.2
Strongly Typed
Note: A REF CURSOR that specifies a specific return type.
Package Header CREATE OR REPLACE PACKAGE strongly_typed IS

TYPE return_cur IS REF CURSOR RETURN all_tables%ROWTYPE;
PROCEDURE child(p_return_rec OUT return_cur);
PROCEDURE parent(p_NumRecs PLS_INTEGER);

END strongly_typed;
/
Package Body CREATE OR REPLACE PACKAGE BODY strongly_typed IS
PROCEDURE child(p_return_rec OUT return_cur) IS

BEGIN
   OPEN p_return_rec FOR
   SELECT * FROM all_tables;
END child;
--==================================================
PROCEDURE parent (p_NumRecs PLS_INTEGER) IS
 p_retcur return_cur;
 at_rec   all_tables%ROWTYPE;
BEGIN
  child(p_retcur);

  FOR i IN 1 .. p_NumRecs
  LOOP
    FETCH p_retcur
    INTO at_rec;

    dbms_output.put_line(at_rec.table_name ||
    ' - ' || at_rec.tablespace_name ||
    ' - ' || TO_CHAR(at_rec.initial_extent) ||
    ' - ' || TO_CHAR(at_rec.next_extent));
  END LOOP;
END parent;
END strongly_typed;
/
To Run The Demo set serveroutput on

exec strongly_typed.parent(1)
exec strongly_typed.parent(8)
Weakly Typed
Note: A REF CURSOR that does not specify the return type such as SYS_REFCURSOR.
Child Procedure CREATE OR REPLACE PROCEDURE child (
 p_NumRecs IN PLS_INTEGER,
 p_return_cur OUT SYS_REFCURSOR)
IS

BEGIN
  OPEN p_return_cur FOR
  'SELECT * FROM all_tables WHERE rownum <= ' || p_NumRecs ;
END child;
/
Parent Procedure CREATE OR REPLACE PROCEDURE parent (pNumRecs VARCHAR2) IS
 p_retcur  SYS_REFCURSOR;
 at_rec    all_tables%ROWTYPE;
BEGIN
  child(pNumRecs, p_retcur);

  FOR i IN 1 .. pNumRecs
  LOOP
    FETCH p_retcur
    INTO at_rec;

    dbms_output.put_line(at_rec.table_name ||
    ' - ' || at_rec.tablespace_name ||
    ' - ' || TO_CHAR(at_rec.initial_extent) ||
    ' - ' || TO_CHAR(at_rec.next_extent));
  END LOOP;
END parent;
/
To Run The Demo set serveroutput on

exec parent(1)
exec parent(17)
Passing Ref Cursors
Ref Cursor Passing Demo CREATE TABLE employees (
empid   NUMBER(5),
empname VARCHAR2(30));

INSERT INTO employees (empid, empname) VALUES (1, 'Dan Morgan');
INSERT INTO employees (empid, empname) VALUES (2, 'Jack Cline');
INSERT INTO employees (empid, empname) VALUES (3, 'Caleb Small');
COMMIT;
CREATE OR REPLACE PROCEDURE pass_ref_cur(p_cursor SYS_REFCURSOR) IS

TYPE array_t IS TABLE OF VARCHAR2(4000)
INDEX BY BINARY_INTEGER;

rec_array array_t;

BEGIN
  FETCH p_cursor BULK COLLECT INTO rec_array;

  FOR i IN rec_array.FIRST .. rec_array.LAST
  LOOP
    dbms_output.put_line(rec_array(i));
  END LOOP;
END pass_ref_cur;
/

set serveroutput on

DECLARE
 rec_array SYS_REFCURSOR;
BEGIN
  OPEN rec_array FOR
  'SELECT empname FROM employees';

  pass_ref_cur(rec_array);
  CLOSE rec_array;
END;
/

Related Topics
Packages
Procedures
Types


Oracle Regular Expressions
Version 10.2
General Information
Anchoring Characters
Character Class | Description
^ | Anchor the expression to the start of a line
$ | Anchor the expression to the end of a line
Equivalence Classes
Character Class | Description
= = | Oracle supports the equivalence classes through the POSIX '[==]' syntax. A base letter and all of its accented versions constitute an equivalence class. For example, the equivalence class '[=a=]' matches � and �. The equivalence classes are valid only inside the bracketed expression
Match Options
Character Class | Description
c | Case sensitive matching
i | Case insensitive matching
m | Treat source string as multi-line activating Anchor chars
n | Allow the period (.) to match any newline character
Posix Characters
Character Class | Description
[:alnum:] | Alphanumeric characters
[:alpha:] | Alphabetic characters
[:blank:] | Blank Space Characters
[:cntrl:] | Control characters (nonprinting)
[:digit:] | Numeric digits
[:graph:] | Any [:punct:], [:upper:], [:lower:], and [:digit:] chars
[:lower:] | Lowercase alphabetic characters
[:print:] | Printable characters
[:punct:] | Punctuation characters
[:space:] | Space characters (nonprinting), such as carriage return, newline, vertical tab, and form feed
[:upper:] | Uppercase alphabetic characters
[:xdigit:] | Hexidecimal characters
Quantifier Characters
Character Class | Description
* | Match 0 or more times
? | Match 0 or 1 time
+ | Match 1 or more times
{m} | Match exactly m times
{m,} | Match at least m times
{m, n} | Match at least m times but no more than n times
\n | Cause the previous expression to be repeated n times
Alternative Matching And Grouping Characters
Character Class | Description
| | Separates alternates, often used with grouping operator ()
( ) | Groups subexpression into a unit for alternations, for quantifiers, or for backreferencing (see "Backreferences" section)
[char] | Indicates a character list; most metacharacters inside a character list are understood as literals, with the exception of character classes, and the ^ and - metacharacters
Demo Table CREATE TABLE test (
testcol VARCHAR2(50));

INSERT INTO test VALUES ('abcde');
INSERT INTO test VALUES ('12345');
INSERT INTO test VALUES ('1a4A5');
INSERT INTO test VALUES ('12a45');
INSERT INTO test VALUES ('12aBC');
INSERT INTO test VALUES ('12abc');
INSERT INTO test VALUES ('12ab5');
INSERT INTO test VALUES ('12aa5');
INSERT INTO test VALUES ('12AB5');
INSERT INTO test VALUES ('ABCDE');
INSERT INTO test VALUES ('123-5');
INSERT INTO test VALUES ('12.45');
INSERT INTO test VALUES ('1a4b5');
INSERT INTO test VALUES ('1 3 5');
INSERT INTO test VALUES ('1  45');
INSERT INTO test VALUES ('1   5');
INSERT INTO test VALUES ('a  b  c  d');
INSERT INTO test VALUES ('a b  c   d    e');
INSERT INTO test VALUES ('a              e');
INSERT INTO test VALUES ('Steven');
INSERT INTO test VALUES ('Stephen');
INSERT INTO test VALUES ('111.222.3333');
INSERT INTO test VALUES ('222.333.4444');
INSERT INTO test VALUES ('333.444.5555');
COMMIT;
REGEXP_INSTR
Syntax | REGEXP_INSTR(<source_string>, <pattern>, <start_position>, <occurrence>, <return_option>, <match_parameter>)
Find words beginning with 's' or 'r' or 'p' followed by any 4 alphabetic characters: case insensitive SELECT REGEXP_INSTR('500 Oracle Pkwy, Redwood Shores, CA', '[o][[:alpha:]]{3}', 1, 1, 0, 'i') RESULT
FROM dual;

SELECT REGEXP_INSTR('500 Oracle Pkwy, Redwood Shores, CA', '[o][[:alpha:]]{3}', 1, 1, 1, 'i') RESULT
FROM dual;

SELECT REGEXP_INSTR('500 Oracle Pkwy, Redwood Shores, CA', '[o][[:alpha:]]{3}', 1, 2, 0, 'i') RESULT
FROM dual;

SELECT REGEXP_INSTR('500 Oracle Pkwy, Redwood Shores, CA', '[o][[:alpha:]]{3}', 1, 2, 1, 'i') RESULT
FROM dual;
Find the postiion of try, trying, tried or tries SELECT REGEXP_INSTR('We are trying to make the subject easier.', 'tr(y(ing)?|(ied)|(ies))') RESULTNUM
FROM dual;
REGEXP_LIKE
Syntax | REGEXP_LIKE(<source_string>, <pattern>, <match_parameter>)
AlphaNumeric Characters SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alnum:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alnum:]]{3}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alnum:]]{5}');
Alphabetic Characters: SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alpha:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alpha:]]{3}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:alpha:]]{5}');
Control Characters INSERT INTO test VALUES ('zyx' || CHR(13) || 'wvu');
COMMIT;

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:cntrl:]]{1}');
Digits SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:digit:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:digit:]]{3}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:digit:]]{5}');
Lower Case SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:lower:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:lower:]]{2}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:lower:]]{3}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:lower:]]{5}');
Printable Characters SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:print:]]{5}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:print:]]{6}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:print:]]{7}');
Punctuation TRUNCATE TABLE test;

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:punct:]]');
Spaces SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:space:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:space:]]{2}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:space:]]{3}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:space:]]{5}');
Upper Case SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:upper:]]');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:upper:]]{2}');

SELECT *
FROM test
WHERE REGEXP_LIKE(testcol, '[[:upper:]]{3}');
Values Starting with 'a%b' SELECT testcol
FROM test
WHERE REGEXP_LIKE(testcol, '^ab*');
'a' is the third value SELECT testcol
FROM test
WHERE REGEXP_LIKE(testcol, '^..a.');
Contains two consecutive occurances of the letter 'a' or 'z' SELECT testcol
FROM test
WHERE REGEXP_LIKE(testcol, '([az])\1', 'i');
Begins with 'Ste' ends with 'en' and contains either 'v' or 'ph' in the center SELECT testcol
FROM test
WHERE REGEXP_LIKE(testcol, '^Ste(v|ph)en$');
Use a regular expression in a check constraint CREATE TABLE mytest (c1 VARCHAR2(20),
CHECK (REGEXP_LIKE(c1, '^[[:alpha:]]+$')));
Identify SSN

Thanks: Byron Bush HIOUG 		CREATE TABLE ssn_test (
ssn_col  VARCHAR2(20));

INSERT INTO ssn_test VALUES ('111-22-3333');
INSERT INTO ssn_test VALUES ('111=22-3333');
INSERT INTO ssn_test VALUES ('111-A2-3333');
INSERT INTO ssn_test VALUES ('111-22-33339');
INSERT INTO ssn_test VALUES ('111-2-23333');
INSERT INTO ssn_test VALUES ('987-65-4321');
COMMIT;

SELECT ssn_col
from ssn_test
WHERE regexp_like(ssn_col,'^[0-9]{3}-[0-9]{2}-[0-9]{4}$');
REGEXP_REPLACE
Syntax REGEXP_REPLACE(<source_string>, <pattern>,
<replace_string>, <position>, <occurrence>, <match_parameter>)
Looks for the pattern xxx.xxx.xxxx and reformats pattern to (xxx) xxx-xxxx col testcol format a15
col result format a15

SELECT testcol, REGEXP_REPLACE(testcol,
'([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',
'(\1) \2-\3') RESULT
FROM test
WHERE LENGTH(testcol) = 12;
Put a space after every character SELECT testcol, REGEXP_REPLACE(testcol, '(.)', '\1 ') RESULT
FROM test
WHERE testcol like 'S%';
Replace multiple spaces with a single space SELECT REGEXP_REPLACE('500    Oracle    Parkway, Redwood    Shores, CA', '( ){2,}', ' ') RESULT
FROM dual;
Insert a space between a lower case character followed by an upper case character SELECT REGEXP_REPLACE('George McGovern', '([[:lower:]])([[:upper:]])', '\1 \2') CITY
FROM dual;
Replace the period with a string (note use of '\') SELECT REGEXP_REPLACE('We are trying to make the subject easier.','\.',' for you.') REGEXT_SAMPLE
FROM dual;
REGEXP_SUBSTR
Syntax REGEXP_SUBSTR(source_string, pattern
[, position [, occurrence
[, match_parameter]]])
Searches for a comma followed by one or more occurrences of non-comma characters followed by a comma SELECT REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA', ',[^,]+,') RESULT
FROM dual;
Look for http:// followed by a substring of one or more alphanumeric characters and optionally, a period (.) col result format a50

SELECT REGEXP_SUBSTR('Go to http://www.oracle.com/products and click on database',
'http://([[:alnum:]]+\.?){3,4}/?') RESULT
FROM dual;
Extracts try, trying, tried or tries SELECT REGEXP_SUBSTR('We are trying to make the subject easier.','tr(y(ing)?|(ied)|(ies))')
FROM dual;
Extract the 3rd field treating ':' as a delimiter SELECT REGEXP_SUBSTR('system/pwd@orabase:1521:sidval',
'[^:]+', 1, 3) RESULT
FROM dual;

Extract from string with vertical bar delimiter 		CREATE TABLE regexp (
testcol VARCHAR2(50));

INSERT INTO regexp
(testcol)
VALUES
('One|Two|Three|Four|Five');

SELECT * FROM regexp;

SELECT REGEXP_SUBSTR(testcol,'[^|]+', 1, 3)
FROM regexp;
Equivalence classes SELECT REGEXP_SUBSTR('iSelfSchooling NOT ISelfSchooling', '[[=i=]]SelfSchooling') RESULT
FROM dual;
Related Topics
Substring-Instring
Translate-Replace


Oracle Rollup Cube

Oracle Rollup, Cube, and Grouping Sets
Version 10.2
General
Rollup Note: ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified group of dimensions. It also calculates a grand total. ROLLUP is a simple extension to the GROUP BY clause, so its syntax is extremely easy to use. The ROLLUP extension is highly efficient, adding minimal overhead to a query.

The action of ROLLUP is straight forward: it creates subtotals that roll up from the most detailed level to a grand total, following a grouping list specified in the ROLLUP clause. ROLLUP takes as its argument an ordered list of grouping columns. First, it calculates the standard aggregate values specified in the GROUP BY clause. Then, it creates progressively higher-level subtotals, moving from right to left through the list of grouping columns. Finally, it creates a grand total.

ROLLUP creates subtotals at n+1 levels, where n is the number of grouping columns. For instance, if a query specifies ROLLUP on grouping columns of time, region, and department (n=3), the result set will include rows at four aggregation levels.
Cube Note: CUBE takes a specified set of grouping columns and creates subtotals for all of their possible combinations. In terms of multidimensional analysis, CUBE generates all the subtotals that could be calculated for a data cube with the specified dimensions. If you have specified CUBE(time, region, department), the result set will include all the values that would be included in an equivalent ROLLUP statement plus additional combinations.

Consider Using CUBE in any situation requiring cross-tabular reports. The data needed for cross-tabular reports can be generated with a single SELECT using CUBE. Like ROLLUP, CUBE can be helpful in generating summary tables. Note that population of summary tables is even faster if the CUBE query executes in parallel.

CUBE is typically most suitable in queries that use columns from multiple dimensions rather than columns representing different levels of a single dimension. For instance, a commonly requested cross-tabulation might need subtotals for all the combinations of month, state, and product. These are three independent dimensions, and analysis of all possible subtotal combinations is commonplace. In contrast, a cross-tabulation showing all possible combinations of year, month, and day would have several values of limited interest, because there is a natural hierarchy in the time dimension. Subtotals such as profit by day of month summed across year would be unnecessary in most analyses.
Create demo schema @$ORACLE_HOME\demo\schema\sales_history\sh_main.sql
ROLLUP
Full Rollup Demo SQL Statement col country_name format a25

SELECT ch.channel_desc, t.calendar_month_desc, co.country_name,
TO_CHAR(SUM(s.amount_sold), '9,999,999,999') SALES$
FROM sales s, customers cu, times t, channels ch, countries co
WHERE s.time_id = t.time_id
AND s.cust_id = cu.cust_id
AND s.channel_id = ch.channel_id
AND cu.country_id = co.country_id
AND ch.channel_desc IN ('Direct Sales','Internet')
AND t.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_name LIKE 'U%'
GROUP BY ROLLUP(ch.channel_desc, t.calendar_month_desc, co.country_name);
Partial Rollup Demo SQL Statement SELECT ch.channel_desc, t.calendar_month_desc, co.country_name,
TO_CHAR(SUM(s.amount_sold), '9,999,999,999') SALES$
FROM sales s, customers cu, times t, channels ch, countries co
WHERE s.time_id = t.time_id
AND s.cust_id = cu.cust_id
AND s.channel_id = ch.channel_id
AND ch.channel_desc IN ('Direct Sales','Internet')
AND t.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_name LIKE 'U%'
GROUP BY ch.channel_desc, ROLLUP(t.calendar_month_desc, co.country_name);
GROUP_ID

The following demonstrates a GROUP BY with repeating values and their identification with the GROUP_ID() function 		GROUP_ID()
CREATE TABLE grp_rep (
person_id   NUMBER(3),
division    VARCHAR2(3),
commission  NUMBER(5));

INSERT INTO grp_rep VALUES (1,'SAM',1000);
INSERT INTO grp_rep VALUES (2,'EUR',1200);
INSERT INTO grp_rep VALUES (1,'EUR',1450);
INSERT INTO grp_rep VALUES (1,'EUR',700);
INSERT INTO grp_rep VALUES (2,'SEA',1000);
INSERT INTO grp_rep VALUES (2,'SEA',2000);
INSERT INTO grp_rep VALUES (1,'EUR',800);
COMMIT;

SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY person_id, division;

SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY person_id, ROLLUP (person_id, division);

SELECT person_id, division, SUM(commission), GROUP_ID() g
FROM grp_rep
GROUP BY person_id, ROLLUP (person_id, division);

SELECT person_id, division, SUM(commission), GROUP_ID() g
FROM grp_rep
GROUP BY person_id, ROLLUP (person_id, division)
HAVING GROUP_ID() = 0;
GROUPING
Distinguishes superaggregate rows from regular grouped rows.
Distinguish a null representing the set of all values in a superaggregate row from a null in a regular row. 		GROUPING(<expression>)
conn hr/hr

set linesize 121
col job format a10

SELECT DECODE(department_name, '1', 'All Departments',
department_name) AS DEPARTMENT,
DECODE(job_id, '1', 'All Jobs', job_id) AS job,
COUNT(*) "Total Empl", AVG(salary) * 12 "Average Sal"
FROM employees e, departments d
WHERE d.department_id = e.department_id
GROUP BY ROLLUP (department_name, job_id);

SELECT DECODE(GROUPING(department_name), '1', 'All Departments',
department_name) AS DEPARTMENT,
DECODE(GROUPING(job_id), '1', 'All Jobs', job_id) AS job,
COUNT(*) "Total Empl", AVG(salary) * 12 "Average Sal"
FROM employees e, departments d
WHERE d.department_id = e.department_id
GROUP BY ROLLUP (department_name, job_id);
GROUPING SETS
Demo from OTN conn sh/sh

SELECT channel_desc, calendar_month_desc, co.country_id,
TO_CHAR(SUM(amount_sold) , '9,999,999,999') SALES$
FROM sales, customers, times, channels, countries co
WHERE sales.time_id=times.time_id
AND sales.cust_id=customers.cust_id
AND sales.channel_id= channels.channel_id
AND customers.country_id = co.country_id
AND channels.channel_desc IN ('Direct Sales', 'Internet')
AND times.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_iso_code IN ('UK', 'US')
GROUP BY GROUPING SETS(
(channel_desc, calendar_month_desc, co.country_id),
(channel_desc, co.country_id),
(calendar_month_desc, co.country_id));

SELECT channel_desc, calendar_month_desc, co.country_id,
TO_CHAR(SUM(amount_sold) , '9,999,999,999') SALES$
FROM sales, customers, times, channels, countries co
WHERE sales.time_id=times.time_id
AND sales.cust_id=customers.cust_id
AND sales.channel_id= channels.channel_id
AND customers.country_id = co.country_id
AND channels.channel_desc IN ('Direct Sales', 'Internet')
AND times.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_iso_code IN ('UK', 'US')
GROUP BY CUBE(channel_desc, calendar_month_desc, co.country_id);
CUBE

Full Cube Rollup 		GROUP BY CUBE()
conn sh/sh

col sales$ format a20

SELECT ch.channel_desc, calendar_month_desc, co.country_name,
TO_CHAR(SUM(s.amount_sold), '9,999,999,999') SALES$
FROM sales s, customers cu, times t, channels ch, countries co
WHERE s.time_id = t.time_id
AND s.cust_id = cu.cust_id
AND s.channel_id = ch.channel_id
AND ch.channel_desc IN ('Direct Sales', 'Internet')
AND t.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_name LIKE 'U%'
GROUP BY CUBE(channel_desc, t.calendar_month_desc, co.country_name);

Partial Cube Rollup 		conn sh/sh

SELECT ch.channel_desc, calendar_month_desc, co.country_name,
TO_CHAR(SUM(s.amount_sold), '9,999,999,999') SALES$
FROM sales s, customers cu, times t, channels ch, countries co
WHERE s.time_id = t.time_id
AND s.cust_id = cu.cust_id
AND s.channel_id = ch.channel_id
AND ch.channel_desc IN ('Direct Sales', 'Internet')
AND t.calendar_month_desc IN ('2000-09', '2000-10')
AND co.country_name LIKE 'U%'
GROUP BY channel_desc, CUBE(t.calendar_month_desc, co.country_name);
GROUPING_ID
Returns a number corresponding to the GROUPING bit vector associated with a row.

In queries with many GROUP BY expressions, determining the GROUP BY level of a particular row requires many GROUPING functions, which leads to cumbersome SQL. GROUPING_ID is useful in these cases. 		GROUPING_ID(<expression>, <expression>, ..)
conn sh/sh

SELECT channel_id, promo_id, SUM(amount_sold) s_sales,
GROUPING(channel_id) gc,
GROUPING(promo_id) gp
FROM sales
WHERE promo_id > 496
GROUP BY CUBE(channel_id, promo_id);

SELECT channel_id, promo_id, SUM(amount_sold) s_sales,
GROUPING(channel_id) AS GC,
GROUPING(promo_id) AS GP,
GROUPING_ID(channel_id, promo_id) AS GCP,
GROUPING_ID(promo_id, channel_id) AS GPC
FROM sales
WHERE promo_id > 496
GROUP BY CUBE(channel_id, promo_id);
Related Topics
GROUP BY


Oracle Autonomous Transaction PRAGMA

Oracle SecureFiles
General
Related Data Dictionary Objects
ts$ dba_tablespaces dba_lobs gv$parameter

Manage securefile initialization parameter

Parameter Options:

  • FORCE
  • PERMITTED (default)
 conn uwclass/uwclass

set linesize 121
col name format a30
col value format a30

SELECT name, value
FROM gv$parameter
WHERE name LIKE '%secure%';

ALTER SYSTEM SET db_securefile = 'FORCE' SCOPE=MEMORY;

SELECT name, value
FROM gv$parameter
WHERE name LIKE '%secure%';

ALTER SYSTEM SET db_securefile = 'PERMITTED' SCOPE=BOTH;

Create Auto Management ASSM Tablespace 		conn / as sysdba

desc dba_tablespaces

SELECT tablespace_name, segment_space_management
FROM dba_tablespaces;

desc dba_data_files

SELECT file_name
FROM dba_data_files;

CREATE TABLESPACE securefiletbs
DATAFILE 'c:\temp\securefile01.dbf' SIZE 25M
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;

desc dba_tablespaces

SELECT tablespace_name, extent_management, allocation_type, segment_space_management
FROM dba_tablespaces
ORDER BY 1;

Allocate quota 		conn / as sysdba

ALTER USER uwclass QUOTA 23M ON securefiletbs;

SELECT username, max_bytes, max_blocks
FROM dba_ts_quotas
WHERE tablespace_name = 'SECUREFILETBS';

Create Wallet directory in operating system 		-- Note: This step is identical with the one performed with TRANSPARENT -- DATA ENCRYPTION. if a wallet already exists skip this step.

host

-- mkdir $ORACLE_BASE\admin\<SID>\wallet
mkdir $ORACLE_BASE\admin\orabase\wallet

exit

Alter SQLNET.ORA file 		-- Note: This step is identical with the one performed with TRANSPARENT -- DATA ENCRYPTION. if a wallet already exists skip this step.

SQLNET.AUTHENTICATION_SERVICES= (NTS)

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

ENCRYPTION_WALLET_LOCATION = (SOURCE = (METHOD=FILE) (METHOD_DATA = (DIRECTORY = c:\oracle\product\admin\orabase\wallet)))

-- Note: if you do not use this wallet location you will likely
-- receive ORA-28368: cannot auto-create wallet when setting the key

Set Encryption Key 		conn uwclass/uwclass

ALTER SYSTEM SET ENCRYPTION KEY AUTHENTICATED BY "N0way!";
At startup ... or if the Wallet is not open ALTER SYSTEM SET ENCRYPTION WALLET OPEN IDENTIFIED BY "N0way!";

Create table with LOB column in securefile tablespace 		conn uwclass/uwclass

CREATE TABLE secure_file_tab (
rid  NUMBER(5),
bcol BLOB)
LOB (bcol_lob) STORE AS SECUREFILE bcol (
TABLESPACE securefiletbs
RETENTION MIN 3600
KEEP_DUPLICATES NOCOMPRESS DECRYPT CACHE READS);
conn uwclass/uwclass

CREATE TABLE reg_tab (
rid  NUMBER(5),
bcol BLOB)
LOB (bcol)
STORE AS REGFILE (
TABLESPACE uwdata)
TABLESPACE uwdata;

CREATE TABLE sec_tab_kd (
rid  NUMBER(5),
bcol BLOB)
LOB (bcol)
STORE AS SECUREFILE bcol (
TABLESPACE securefiletbs
RETENTION MIN 3600
KEEP_DUPLICATES NOCOMPRESS DECRYPT CACHE READS)
TABLESPACE uwdata;

CREATE TABLE sec_tab_dd (
rid  NUMBER(5),
bcol BLOB)
LOB (bcol)
STORE AS SECUREFILE bcol2 (
TABLESPACE securefiletbs
RETENTION MIN 3600
COMPRESS ENCRYPT CACHE READS)
TABLESPACE uwdata;

SELECT table_name, tablespace_name
FROM user_tables
ORDER BY 1;

desc user_lobs

col table_name format a10
col column_name format a10

SELECT table_name, column_name, chunk, retention, cache, encrypt, compression, deduplication, in_row, format, securefile
FROM user_lobs;

Load BLOBs 		set linesize 121
col owner format a10
col directory_path format a70

SELECT *
FROM all_directories;

/*
conn / as sysdba

CREATE OR REPLACE DIRECTORY ctemp AS 'c:\temp';

GRANT read ON DIRECTORY ctemp TO uwclass;

conn uwclass/uwclass
*/

CREATE OR REPLACE PROCEDURE load_blob (filein IN VARCHAR2) IS
 src_file BFILE;
 dst_file BLOB;
 lgh_file BINARY_INTEGER;
BEGIN
  src_file := bfilename('CTEMP', filein);

  dbms_lob.fileopen(src_file, dbms_lob.file_readonly);
  lgh_file := dbms_lob.getlength(src_file);

  FOR i IN 1..3 LOOP
    INSERT INTO reg_tab
    (rid, bcol)
    VALUES
    (i, EMPTY_BLOB())
    RETURNING bcol INTO dst_file;

    SELECT bcol
    INTO dst_file
    FROM reg_tab
    WHERE rid = i
    FOR UPDATE;

    dbms_lob.loadfromfile(dst_file, src_file, lgh_file);

    UPDATE reg_tab
    SET bcol = dst_file
    WHERE rid = i;

    INSERT INTO sec_tab_kd
    (rid, bcol)
    VALUES
    (i, EMPTY_BLOB())
    RETURNING bcol INTO dst_file;

    SELECT bcol
    INTO dst_file
    FROM sec_tab_kd
    WHERE rid = i
    FOR UPDATE;

    dbms_lob.loadfromfile(dst_file, src_file, lgh_file);

    UPDATE sec_tab_kd
    SET bcol = dst_file
    WHERE rid = i;

    INSERT INTO sec_tab_dd
    (rid, bcol)
    VALUES
    (i, EMPTY_BLOB())
    RETURNING bcol INTO dst_file;

    SELECT bcol
    INTO dst_file
    FROM sec_tab_dd
    WHERE rid = i
    FOR UPDATE;

    dbms_lob.loadfromfile(dst_file, src_file, lgh_file);

    UPDATE sec_tab_dd
    SET bcol = dst_file
    WHERE rid = i;
  END LOOP;
  COMMIT;

  dbms_lob.fileclose(src_file);
END load_blob;
/

-- with an mpg file
exec load_blob('sphere.mpg');

SELECT COUNT(*)
FROM reg_tab;

SELECT COUNT(*)
FROM sec_tab_kd;

SELECT COUNT(*)
FROM sec_tab_dd;

SELECT dbms_lob.getlength(bcol) FROM reg_tab;

SELECT dbms_lob.getlength(bcol) FROM sec_tab_kd;

SELECT dbms_lob.getlength(bcol) FROM sec_tab_dd;

-- with a doc file
exec load_blob('sphere.html');

SELECT COUNT(*)
FROM reg_tab;

SELECT COUNT(*)
FROM sec_tab_kd;

SELECT COUNT(*)
FROM sec_tab_dd;

SELECT dbms_lob.getlength(bcol) FROM reg_tab;

SELECT dbms_lob.getlength(bcol) FROM sec_tab_kd;

SELECT dbms_lob.getlength(bcol) FROM sec_tab_dd;

Examine Results 		col segment_name format a30

SELECT segment_name, segment_type, tablespace_name, blocks
FROM user_segments
WHERE segment_name IN ('REG_TAB', 'SEC_TAB_KD', 'SEC_TAB_DD', 'BCOL', 'BCOL2', 'REGFILE');

set serveroutput on

DECLARE
 b    BOOLEAN;
 bvar BLOB;
BEGIN
  SELECT bcol
  INTO bvar
  FROM sec_tab2
  WHERE rownum = 1;

  b := dbms_lob.issecurefile(bvar);

  IF b THEN
    dbms_output.put_line('Stored in a securefile');
  ELSE
    dbms_output.put_line('Not stored in a securefile');
  END IF;
END;
/

DECLARE
 bvar BLOB;
BEGIN
  SELECT bcol
  INTO bvar
  FROM sec_tab_kd
  WHERE rownum = 1;

  dbms_output.put_line(dbms_lob.getoptions(bvar, 1));
  dbms_output.put_line(dbms_lob.getoptions(bvar, 3));
  dbms_output.put_line(dbms_lob.getoptions(bvar, 4));

  SELECT bcol
  INTO bvar
  FROM sec_tab_dd
  WHERE rownum = 1;

  dbms_output.put_line(dbms_lob.getoptions(bvar, 1));
  dbms_output.put_line(dbms_lob.getoptions(bvar, 3));
  dbms_output.put_line(dbms_lob.getoptions(bvar, 4));
END;
/
Related Topics
DBMS_LOB
Large Objects (LOBs)


Oracle Select Statement

Oracle Select Statements
Basic Select Statements
Select All Columns and All Records in a Single Table or View SELECT *
FROM <table_name>;
SELECT *
FROM all_tables;
Select Named Columns SELECT <column_name, column_name, ..., <column_name>
FROM <table_name>;
SELECT table_name, tablespace_name, num_rows
FROM all_tables;
Create Table As (CTAS)

Note: Redo only created when in ARCHIVE LOG mode 		CREATE TABLE <table_name> AS
SELECT <column_name, column_name, ..., <column_name>
FROM <table_name>;
CREATE TABLE t AS
SELECT *
FROM all_tables;
SELECTs can go anywhere SELECT DECODE((SELECT 'x' FROM DUAL), (SELECT 'x' FROM DUAL), (SELECT 'y' FROM dual)) AS  RESULT
FROM (SELECT 'm' FROM dual)
WHERE (SELECT 1 FROM dual) = (SELECT 1 FROM dual)
AND (SELECT 2 FROM dual) BETWEEN (SELECT 1 FROM dual) AND (SELECT 3 FROM dual)
AND NVL((SELECT NULL FROM dual ), (SELECT 'z' FROM dual)) = (SELECT 'z' FROM dual)
ORDER BY (SELECT 1 FROM dual);
Select Statement With SAMPLE Clause

Sample Clause Returning 1% Of Records 		SELECT *
FROM <table_name>
SAMPLE (1);
CREATE TABLE t AS
SELECT object_name
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W';

SELECT COUNT(*)
FROM t;

SELECT COUNT(*) * 0.1
FROM t;

SELECT *
FROM t
SAMPLE(1);

SELECT *
FROM t
SAMPLE(1);

SELECT *
FROM t
SAMPLE(1);
Select Statement With WHERE Clause

Sample Clause Returning 35% Of Records After Filtering With A WHERE Clause 		SELECT *
FROM <table_name>
SAMPLE (3.5)
WHERE ....
SELECT COUNT(*)
FROM t
WHERE object_name LIKE '%J%';

SELECT COUNT(*) * 0.35
FROM t
WHERE object_name LIKE '%J%';

SELECT *
FROM t
SAMPLE(35)
WHERE object_name LIKE '%J%';

SELECT *
FROM t
SAMPLE(35)
WHERE object_name LIKE '%J%';

SELECT *
FROM t
SAMPLE(35)
WHERE object_name LIKE '%J%';
Select Statement With GROUP BY Clause

Select with Group By Clause 		SELECT <column_name>, <aggregating_operation>
FROM <table_name>
GROUP BY <column_name>;
SELECT object_type, COUNT(*)
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W'
GROUP BY object_type;
Select Statement With HAVING Clause

Select With Having Clause 		SELECT <column_name>, <aggregating_operation>
FROM <table_name>
GROUP BY <column_name>
HAVING <aggregating_op_result> <condition> <value>;
SELECT object_type, COUNT(*)
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W'
GROUP BY object_type
HAVING COUNT(*) < 6;

SELECT object_type, COUNT(*)
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W'
GROUP BY object_type
HAVING COUNT(*) > 5;
Scalar Select
Select In Select Clause SELECT (
  SELECT <single_value
  FROM <table_name>
FROM <table_name>;
SELECT (SELECT 1 FROM dual) FROM dual;
Select Unique Values
Distinct SELECT DISTINCT <column_name_list>
FROM <table_name>;
SELECT DISTINCT object_type
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W';
Unique SELECT UNIQUE <column_name_list>
FROM <table_name>;
SELECT UNIQUE object_type
FROM all_objects
WHERE SUBSTR(object_name,1,1) BETWEEN 'A' AND 'W';
Select Statement Using Functions

Date Function Example 		SELECT <date_function(<column_name>))
FROM <table_name>;
desc all_objects

SELECT object_name, TO_DATE(timestamp, 'YYYY-MM-DD:HH24:MI:SS')
FROM all_objects
WHERE rownum < 11;

Numeric Function Example 		SELECT <numeric_function(<column_name>))
FROM <table_name>;
desc user_extents

SELECT SUM(bytes)/1024/1024 USED_MB
FROM user_extents;

SELECT segment_type, SUM(bytes)/1024/1024 USED_MB
FROM user_extents
GROUP BY segment_type;

String Function Example 		SELECT <string_function(<column_name>))
FROM <table_name>;
desc all_objects

SELECT object_name, LOWER(object_name) LOWER_ONAME
FROM all_objects
WHERE rownum < 11;
Select For Update

Lock Record(s) 		SELECT <column_name_list)
FROM <table_name_list>
FOR UPDATE;
CREATE TABLE parents (
pid  NUMBER(10),
cash NUMBER(10,2));

CREATE TABLE children
(cid NUMBER(10),
fid  NUMBER(10),
fin_level VARCHAR2(35));

DECLARE
 CURSOR x_cur IS
 SELECT pid
 FROM parents;

 x_rec x_cur%ROWTYPE;

 x NUMBER(10,2) := 18000.64;
 y NUMBER(10,2) := 100;

BEGIN
  DELETE FROM parents;
  DELETE FROM children;

  FOR i IN 1..25
  LOOP
    INSERT INTO parents
    VALUES (y, x);

    x := x+1235.31;
    y := y-1;
  END LOOP;

  y := 0;

  OPEN x_cur;
  LOOP
    FETCH x_cur INTO x_rec;
    EXIT WHEN x_cur%NOTFOUND;

    y := y+1;

    INSERT INTO children (cid, fid)
    VALUES (y, x_rec.pid);

    y := y+1;

    INSERT INTO children (cid, fid)
    VALUES (y, x_rec.pid);
  END LOOP;
  CLOSE x_cur;
  COMMIT;
END;
/

CREATE OR REPLACE PROCEDURE cursor_loop3 IS

CURSOR x_cur IS
SELECT pid, cash
FROM parents
WHERE cash < 35000
FOR UPDATE;

BEGIN
   FOR x_rec IN x_cur
   LOOP
      UPDATE parents
      SET cash = FLOOR(cash)
      WHERE CURRENT OF x_cur;
   END LOOP;
   COMMIT;
END cursor_loop3;
/
FOR UPDATE with NOWAIT | See Deadlocks Demo page
FOR UPDATE with WAIT | See Deadlocks Demo page
FOR UPDATE with SKIP LOCKED | See Deadlocks Demo page
Partition Select

Select From Named Partition 		SELECT DISTINCT <column_name_list>
FROM <table_name> PARTITION (<partition_name>);
CREATE TABLE pt (
deptno NUMBER(10),
state  VARCHAR2(2))
PARTITION BY LIST (state) (
PARTITION nw VALUES ('OR', 'WA'),
PARTITION sw VALUES ('AZ', 'CA', 'NM'));

INSERT INTO pt VALUES (1, 'WA');
INSERT INTO pt VALUES (1, 'OR');
INSERT INTO pt VALUES (1, 'CA');

SELECT COUNT(*) FROM pt;

SELECT COUNT(*) FROM pt PARTITION(nw);
SELECT COUNT(*) FROM pt PARTITION(sw);
Related Topics
Analytic Functions
Conditions
Conversion Functions
Date Functions
Deadlocks
Delete
Group By & Having Clause
Hints
Insert
Joins
Nested Tables
Numeric Functions
Order By
Partitions
Pivot
Pseudocolumns
String Functions
Types
Unpivot
Update
Where
Wildcards
With Clause


Morgans Library Setup

Oracle Set Up
General
Note This page is the setup for examples in Morgan's Library. It gives the syntax for creating the library's default tablespace and user.

For university of Washington students use
University of Washington Setup

Change Schema 		conn / as sysdba

CREATE TABLESPACE uwdata
DATAFILE 'C:\ORACLE\ORADATA\ORABASE\UWDATA01.DBF' SIZE 250M
LOGGING FORCE LOGGING ONLINE PERMANENT BLOCKSIZE 8192
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 256K
SEGMENT SPACE MANAGEMENT AUTO;

CREATE USER uwclass
IDENTIFIED BY uwclass
DEFAULT TABLESPACE uwdata
TEMPORARY TABLESPACE temp
QUOTA 0 ON SYSTEM
QUOTA 0 ON SYSAUX
QUOTA UNLIMITED ON uwdata;

GRANT create session TO uwclass;
GRANT create cluster TO uwclass;
GRANT create database link TO uwclass;
GRANT create operator TO uwclass;
GRANT create procedure TO uwclass;
GRANT create sequence TO uwclass;
GRANT create synonym TO uwclass;
GRANT create table TO uwclass;
GRANT create trigger TO uwclass;
GRANT create type TO uwclass;
GRANT create view TO uwclass;
GRANT select any dictionary TO uwclass;

conn uwclass/uwclass

Create Class Schema 		CREATE TABLE all_objs AS
SELECT * FROM all_objects;

Create the airplanes tables: Click Here

-- save this file as
c:\temp\airplanes.sql

Create the servers and serv_inst tables: Click Here

-- save this file as
c:\temp\servers.sql

Create the postal_code table: Click Here

-- save this file as
c:\temp\postal.sql

-- logged on as uwclass create the airplanes table
SQL> @c:\temp\airplanes.sql

-- logged on as uwclass create the servers and serv_inst tables
SQL> @c:\temp\servers.sql

-- logged on as uwclass create the postal_code table
SQL> @c:\temp\postal.sql

Demo Schema Access 		conn scott/tiger

-- if you get this message:
ORA-28000: the account is locked

Warning: You are no longer connected to ORACLE.
SQL>

then

conn / as sysdba

ALTER USER scott ACCOUNT UNLOCK IDENTIFIED BY tiger;

-- try the same thing with the other demo schemas we will use

conn hr/hr
conn oe/oe
conn pm/pm
conn sh/sh

-- if any fail use the appropriate command, that follows to unlock
-- the account and assign a password

ALTER USER hr ACCOUNT UNLOCK IDENTIFIED BY hr;
ALTER USER oe ACCOUNT UNLOCK IDENTIFIED BY oe;
ALTER USER pm ACCOUNT UNLOCK IDENTIFIED BY pm;
ALTER USER sh ACCOUNT UNLOCK IDENTIFIED BY sh;


Oracle String Functions

Would you like to learn Oracle from Ace Director Dan Morgan the author of this library?

If so the "Database Essentials" class will begin November 19, 2007 at SQL University ... Try the free Sample Courses and then check out the list of classes and topics. The first class covers materials in the library, including this page, with live demos in SQL*Plus.

The SQL University Registration Page will be active the first day of OpenWorld.

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
ASCII
Get The ASCII Value Of A Character | ASCII(ch VARCHAR2 CHARACTER SET ANY_CS) RETURN PLS_INTEGER;
SELECT ASCII('A') FROM dual;
SELECT ASCII('Z') FROM dual;
SELECT ASCII('a') FROM dual;
SELECT ASCII('z') FROM dual;
SELECT ASCII(' ') FROM dual;
CASE Related Functions
Upper Case UPPER(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT UPPER('Dan Morgan') FROM dual;
Lower Case LOWER(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT LOWER('Dan Morgan') FROM dual;
Initial Letter Upper Case INITCAP(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT INITCAP('DAN MORGAN') FROM dual;
NLS Upper Case | NLS_UPPER(<string_or_column>)
SELECT NLS_UPPER('Dan Morgan', 'NLS_SORT = XDanish')
FROM dual;
NLS Lower Case | NLS_LOWER(<string_or_column>)
SELECT NLS_LOWER('Dan Morgan', 'NLS_SORT = XFrench')
FROM dual;
NLS Initial Letter Upper Case | NLS_INITCAP(<string_or_column>)
SELECT NLS_INITCAP('DAN MORGAN', 'NLS_SORT = XGerman')
FROM dual;
CHR
Character | CHR(n PLS_INTEGER) RETURN VARCHAR2;
SELECT(CHR(68) || CHR(65) || CHR(78)) FROM dual;

SELECT(CHR(68) || CHR(97) || CHR(110)) FROM dual;
COALESCE

Returns the first non-null occurrence 		COALESCE(<value>, <value>, <value>, ...)
CREATE TABLE test (
col1  VARCHAR2(1),
col2  VARCHAR2(1),
col3  VARCHAR2(1));

INSERT INTO test VALUES (NULL, 'B', 'C');
INSERT INTO test VALUES ('A', NULL, 'C');
INSERT INTO test VALUES (NULL, NULL, 'C');
INSERT INTO test VALUES ('A', 'B', 'C');

SELECT COALESCE(col1, col2, col3) FROM test;
CONCAT
Concatenate

Overload 1

 CONCAT(left IN VARCHAR2, right IN VARCHAR2) RETURN VARCHAR2
SELECT CONCAT('Dan ', 'Morgan') FROM dual;

Concatenate

Overload 2 		CONCAT(left IN CLOB, right IN CLOB) RETURN CLOB
set serveroutput on

DECLARE
 c1 CLOB := TO_CLOB('Dan ');
 c2 CLOB := TO_CLOB('Morgan');
 c3 CLOB;
BEGIN
  SELECT CONCAT('Dan ', 'Morgan')
  INTO c3
  FROM dual;

  dbms_output.put_line(c3);
END;
/
CONVERT
Converts From One Character Set To Another CONVERT(<character>,<destination_character_set>,
<source_character_set>)
SELECT CONVERT('� � � � � A B C D E','US7ASCII','WE8ISO8859P1')
FROM dual;
DUMP

Returns The Number Of Bytes And Datatype Of A Value 		DUMP(<expression>, <return_format>, <start_position>, <length>);

8 | Octal
10 | Decimal
16 | Hexidecimal
17 | Single Characters
1008 | octal notation with the character set name
1010 | decimal notation with the character set name
1016 | hexadecimal notation with the character set name
1017 | single characters with the character set name
set linesize 121
col dmp format a50

SELECT table_name, DUMP(table_name) DMP FROM user_tables;

SELECT table_name, DUMP(table_name, 16) DMP FROM user_tables;

SELECT table_name, DUMP(table_name, 16, 7, 4) DMP FROM user_tables;
INSTR
See links at page bottom
INSTRB
Location of a string, within another string, in bytes INSTRB(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTRB('Dan Morgan', ' ', 1, 1) FROM dual;
INSTRC
Location of a string, within another string, in Unicode complete characters INSTRC(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTRC('Dan Morgan', ' ', 1, 1) FROM dual;
INSTR2
Location of a string, within another string, in UCS2 code points INSTR2(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTR2('Dan Morgan', ' ', 1, 1) FROM dual;
INSTR4
Location of a string, within another string, in UCS4 code points INSTR4(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTR4('Dan Morgan', ' ', 1, 1) FROM dual;
LENGTH
String Length | LENGTH(<string_or_column>)
SELECT LENGTH('Dan Morgan') FROM dual;
LENGTHB
Returns length in bytes | LENGTHB(<char_varchar2_or_clob_value>)
SELECT table_name, LENGTHB(table_name) FROM user_tables;
Note: Additional forms of LENGTH (LENGTHC, LENGTH2, and LENGTH4) are also available.
LPAD
Left Pad

Overload 1 		LPAD(
str1 VARCHAR2 CHARACTER SET ANY_CS,
len  PLS_INTEGER,
PAD  VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT LPAD('Dan Morgan', 25, 'x') FROM dual;
Overload 2 LPAD(
str1 VARCHAR2 CHARACTER SET ANY_CS,
len  PLS_INTEGER)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT LPAD('Dan Morgan', 25) FROM dual;
Overload 3 LPAD(
str1 CLOB CHARACTER SET ANY_CS,
len  NUMBER,
PAD  CLOB CHARACTER SET STR1%CHARSET)
RETURN CLOB CHARACTER SET STR1%CHARSET;
TBD
Overload 4 LPAD(
str1 CLOB CHARACTER SET ANY_CS,
len  INTEGER)
RETURN CLOB CHARACTER SET STR1%CHARSET;
TBD
LTRIM
Left Trim

Overload 1 		LTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ',
tset VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || LTRIM('   Dan Morgan   ') || '<-' FROM dual;
Overload 2 LTRIM(
STR1 VARCHAR2 CHARACTER SET ANY_CS := ' ')
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || LTRIM('xxx Dan Morgan   ') || '<-' FROM dual;

SELECT '->' || LTRIM('xxxDan Morgan   ', 'x') || '<-' FROM dual;
MAX
The Maximum String based on the current sort parameter | MAX(<character_string>)
SELECT MAX(table_name)
FROM user_tables;
MIN
The Minimum String based on the current sort parameter | MIN(<character_string>)
SELECT MIN(table_name)
FROM user_tables;
NLSSORT

Returns the string of bytes used to sort a string.

The string returned is of RAW data type 		NLSSORT(<column_name>, 'NLS_SORT = <NLS Parameter>);
CREATE TABLE test (name VARCHAR2(15));
INSERT INTO test VALUES ('Gaardiner');
INSERT INTO test VALUES ('Gaberd');
INSERT INTO test VALUES ('G�berd');
COMMIT;

SELECT * FROM test ORDER BY name;

SELECT * FROM test
ORDER BY NLSSORT(name, 'NLS_SORT = XDanish');

SELECT * FROM test
ORDER BY NLSSORT(name, 'NLS_SORT = BINARY_CI');
Quote Delimiters

q used to define a quote delimiter for PL/SQL 		q'<delimiter><string><delimiter>';
set serveroutput on

DECLARE
 s1 VARCHAR2(20);
 s2 VARCHAR2(20);
 s3 VARCHAR2(20);
BEGIN
  s1 := q'[Isn't this cool]';
  s2 := q'"Isn't this cool"';
  s3 := q'|Isn't this cool|';

  dbms_output.put_line(s1);
  dbms_output.put_line(s2);
  dbms_output.put_line(s3);
END;
/
REPLACE
See links at page bottom
REVERSE
Reverse | REVERSE(<string_or_column>)
SELECT REVERSE('Dan Morgan') FROM dual;

SELECT DUMP('Dan Morgan') FROM dual;
SELECT DUMP(REVERSE('Dan Morgan')) FROM dual;
RPAD
Right Pad

Overload 1 		RPAD(str1 VARCHAR2 CHARACTER SET ANY_CS, len PLS_INTEGER,
pad VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT RPAD('Dan Morgan', 25, 'x') FROM dual;
Overload 2 RPAD(str1 VARCHAR2 CHARACTER SET ANY_CS, len PLS_INTEGER)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT RPAD('Dan Morgan', 25) ||'<-' FROM dual;
RTRIM
Right Trim

Overload 1 		RTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ',
tset VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || RTRIM('   Dan Morganxxx') || '<-' FROM dual;
SELECT '->' || RTRIM('   Dan Morganxxx', 'xxx') || '<-' FROM dual;
Overload 2 RTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ')
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || RTRIM('   Dan Morgan   ') || '<-' FROM dual;
SOUNDEX

Returns Character String Containing The Phonetic Representation Of Another String 		Rules:
  • Retain the first letter of the string and remove all other occurrences of the following letters: a, e, h, i, o, u, w, y
  • Assign numbers to the remaining letters (after the first) as
    follows:
    b, f, p, v = 1
    c, g, j, k, q, s, x, z = 2
    d, t = 3
    l = 4
    m, n = 5
    r = 6
  • If two or more letters with the same number were adjacent in the original name (before step 1), or adjacent except for any intervening h and w, then omit all but the first.
  • Return the first four bytes padded with 0.

SOUNDEX(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;

CREATE TABLE test (
namecol VARCHAR2(15));

INSERT INTO test (namecol) VALUES ('Smith');
INSERT INTO test (namecol) VALUES ('Smyth');
INSERT INTO test (namecol) VALUES ('Smythe');
INSERT INTO test (namecol) VALUES ('Smither');
INSERT INTO test (namecol) VALUES ('Smidt');
INSERT INTO test (namecol) VALUES ('Smick');
INSERT INTO test (namecol) VALUES ('Smiff');
COMMIT;

SELECT name, SOUNDEX(namecol) FROM test;
-- Thanks Frank van Bortel for the idea for the above

SELECT *
FROM test
WHERE SOUNDEX(namecol) = SOUNDEX('SMITH');
SUBSTR
See links at page bottom
SUBSTRB
Returns a substring counting bytes rather than characters SUBSTRB(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
SUBSTRC
Returns a substring within another string, using Unicode code points SUBSTRC(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
SUBSTR2
Returns a substring within another string, using UCS2 code points SUBSTR2(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
SUBSTR4
Returns a substring within another string, using UCS4 code points SUBSTR4(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
TRANSLATE
See links at page bottom
TREAT
Changes The Declared Type Of An Expression | TREAT (<expression> AS REF schema.type))
SELECT name, TREAT(VALUE(p) AS employee_t).salary SALARY
FROM persons p;
TRIM (variations are LTRIM and RTRIM)
Trim Spaces | TRIM(<string_or_column>)
SELECT '   Dan Morgan    ' FROM dual;

SELECT TRIM('   Dan Morgan   ') FROM dual;
Trim Other Characters | TRIM(<character_to_trim> FROM <string_or_column>)
SELECT TRIM('D' FROM 'Dan Morgan') FROM dual;
Trim By CHR value | TRIM(<string_or_column>)
SELECT ASCII(SUBSTR('Dan Morgan',1,1)) FROM dual;

SELECT TRIM(CHR(68) FROM 'Dan Morgan') FROM dual;
Vertical Bars
Also known as Pipes | <first_string> || <second_string>
SELECT 'Dan' || ' ' || 'Morgan' FROM dual;

with alias

SELECT 'Dan' || ' ' || 'Morgan' NAME FROM dual;
or
SELECT 'Dan' || ' ' || 'Morgan' AS NAME FROM dual;
VSIZE
Byte Size | VSIZE(e IN VARCHAR2) RETURN NUMBER
SELECT VSIZE('Dan Morgan') FROM dual;
Related Topics
CASE
DBMS_LOB
Decode
Instring
Miscellaneous Functions
Operators (Built-in)
Regular Expressions
Replace
Substring
Translate
XML Functions


Oracle Substring & Instring Functions Substr Instr

Oracle SUBSTR & INSTR Functions
SUBSTR (Substring) Built-in String Function
SUBSTR (overload 1) SUBSTR(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SUBSTR (overload 2) SUBSTR(
STR1 CLOB CHARACTER SET ANY_CS,
POS  NUMBER,                -- starting position
LEN  NUMBER := 2147483647)  -- number of characters
RETURN CLOB CHARACTER SET STR1%CHARSET;
Substring Beginning Of String SELECT SUBSTR(<value>, 1, <number_of_characters>)
FROM dual;
SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR
FROM dual;
Substring Middle Of String SELECT SUBSTR(<value>, <starting_position>, <number_of_characters>)
FROM dual.
SELECT SUBSTR('Take the first four characters', 16, 4) MIDDLE_FOUR
FROM dual;
Substring End of String SELECT SUBSTR(<value>, <starting_position>)
FROM dual;
SELECT SUBSTR('Take the first four characters', 16) SIXTEEN_TO_END
FROM dual;
INSTR (Instring) Built-in String Function
INSTR (overload 1) INSTR(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
INSTR (overload 2) INSTR(
STR1 CLOB CHARACTER SET ANY_CS,            -- test string
STR2 CLOB CHARACTER SET STR1%CHARSET,      -- string to locate
POS  INTEGER := 1,                         -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN INTEGER;
Instring For Matching First Value Found SELECT INSTR(<value>, <value_to_match>, <direction>, <instance>
FROM dual;
SELECT INSTR('Take the first four characters', 'a', 1, 1) FOUND_1
FROM dual;
Instring If No Matching Second Value Found SELECT INSTR('Take the first four characters', 'a', 1, 2) FOUND_2
FROM dual;
Instring For Multiple
Characters 		SELECT INSTR('Take the first four characters', 'four', 1, 1) MCHARS
FROM dual;
Reverse Direction Search SELECT INSTR('Take the first four characters', 'a', -1, 1) REV_SRCH
FROM dual;
Reverse Direction Search Second Match SELECT INSTR('Take the first four characters', 'a', -1, 2) REV_TWO
FROM dual;
String Parsing By Combining SUBSTR And INSTR Built-in String Functions
List parsing first value

Take up to the character before the first comma 		SELECT SUBSTR('abc,def,ghi', 1 ,INSTR('abc,def,ghi', ',', 1, 1)-1)
FROM dual;
List parsing center value

Take the value between the commas 		SELECT SUBSTR('abc,def,ghi', INSTR('abc,def,ghi',',', 1, 1)+1,
INSTR('abc,def,ghi',',',1,2)-INSTR('abc,def,ghi',',',1,1)-1)
FROM dual;
List parsing last value

Take the value after the last comma 		SELECT SUBSTR('abc,def,ghi', INSTR('abc,def,ghi',',', 1, 2)+1)
FROM dual;
Related Topics
DBMS_LOB Built-in Package
Regular Expressions
String Functions


Oracle SYS_CONTEXT Function
Actions As SYS
Note: USERENV is an Oracle provided namespace that describes the current session.
Syntax SELECT sys_context('<namespace>', '<parameter>', <length>);
FROM dual;
Attribute | Return Value
ACTION | Identifies the position in the module (application name) and is set through the DBMS_APPLICATION_INFO package or OCI.
SELECT sys_context('USERENV', 'ACTION') FROM dual;

exec dbms_application_info.set_action('INSERTING');

SELECT sys_context('USERENV', 'ACTION') FROM dual;
AUDITED_CURSORID | Returns the cursor ID of the SQL that triggered the audit. This parameter is not valid in a fine-grained auditing environment. If you specify it in such an environment, Oracle Database always returns NULL.
AUTHENTICATED_IDENTITY Returns the identity used in authentication. In the list that follows, the type of user is followed by the value returned:
  • Kerberos-authenticated enterprise user: kerberos principal name
  • Kerberos-authenticated external user : kerberos principal name; same as the schema name
  • SSL-authenticated enterprise user: the DN in the user's PKI certificate
  • SSL-authenticated external user: the DN in the user's PKI certificate
  • Password-authenticated enterprise user: nickname; same as the login name
  • Password-authenticated database user: the database username; same as the schema name
  • OS-authenticated external user: the external operating system user name
  • Radius/DCE-authenticated external user: the schema name
  • Proxy with DN : Oracle Internet Directory DN of the client
  • Proxy with certificate: certificate DN of the client
  • Proxy with username: database user name if client is a local database user; nickname if client is an enterprise user
  • SYSDBA/SYSOPER using Password File: login name
  • SYSDBA/SYSOPER using OS authentication: operating system user name
AUTHENTICATION_DATA Data being used to authenticate the login user. For X.503 certificate authenticated sessions, this field returns the context of the certificate in HEX2 format.

Note: You can change the return value of the AUTHENTICATION_DATA attribute using the length parameter of the syntax. Values of up to 4000 are accepted. This is the only attribute of USERENV for which Oracle implements such a change.
AUTHENTICATION_METHOD Returns the method of authentication. In the list that follows, the type of user is followed by the method returned.
  • Password-authenticated enterprise user, local database user, or SYSDBA/SYSOPER using Password File; proxy with username using password: PASSWORD
  • Kerberos-authenticated enterprise or external user: KERBEROS
  • SSL-authenticated enterprise or external user: SSL
  • Radius-authenticated external user: RADIUS
  • OS-authenticated external user or SYSDBA/SYSOPER: OS
  • DCE-authenticated external user: DCE
  • Proxy with certificate, DN, or username without using password: NONE
BG_JOB_ID | Job ID of the current session if it was established by an Oracle background process. Null if the session was not established by a background process.
CLIENT_IDENTIFIER | Returns an identifier that is set by the application through the DBMS_SESSION.SET_IDENTIFIER procedure, the OCI attribute OCI_ATTR_CLIENT_IDENTIFIER, or the Java class Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is used by various database components to identify lightweight application users who authenticate as the same user.
SELECT sys_context('USERENV', 'CLIENT_IDENTIFIER') FROM dual;

exec dbms_session.set_identifier(USER || ' ' || SYSTIMESTAMP);

SELECT sys_context('USERENV', 'CLIENT_IDENTIFIER') FROM dual;
CLIENT_INFO | Returns user session information that can be stored by an application using the DBMS_APPLICATION_INFO package.
SELECT sys_context('USERENV', 'CLIENT_INFO') FROM dual;

exec dbms_application_info.set_client_info('TEST');

SELECT sys_context('USERENV', 'CLIENT_INFO') FROM dual;
CURRENT_BIND | The bind variables for fine-grained auditing
CURRENT_EDITION_ID | The name of the current edition
SELECT sys_context('USERENV', 'CURRENT_EDITION_ID') FROM dual;
CURRENT_EDITION_NAME | The name of the current edition
SELECT sys_context('USERENV', 'CURRENT_EDITION_NAME') FROM dual;
CURRENT_SCHEMA | Name of the default schema being used in the current schema. This value can be changed during the session with an ALTER SESSION SET CURRENT_SCHEMA statement.
SELECT sys_context('USERENV', 'CURRENT_SCHEMA') FROM dual;
CURRENT_SCHEMAID | Identifier of the default schema being used in the current session.
SELECT sys_context('USERENV', 'CURRENT_SCHEMAID') FROM dual;

SELECT user#
FROM sys.user$
WHERE name = USER;
CURRENT_SQL | Returns the first 4K bytes of the current SQL that triggered the fine-grained auditing event.
CURRENT_SQLn | CURRENT_SQLn attributes return subsequent 4K-byte increments, where n can be an integer from 1 to 7, inclusive. CURRENT_SQL1 returns bytes 4K to 8K; CURRENT_SQL2 returns bytes 8K to 12K, and so forth. You can specify these attributes only inside the event handler for the fine-grained auditing feature.
CURRENT_SQL_LENGTH | The length of the current SQL statement that triggers fine-grained audit or row-level security (RLS) policy functions or event handlers. Valid only inside the function or event handler.
DB_DOMAIN | Domain of the database as specified in the DB_DOMAIN initialization parameter.
SELECT sys_context('USERENV', 'DB_DOMAIN') FROM dual;
DB_NAME | Name of the database as specified in the DB_NAME initialization parameter.
SELECT sys_context('USERENV', 'DB_NAME') FROM dual;

SELECT name, value
FROM gv$parameter
where name LIKE 'db%name';
DB_UNIQUE NAME | Name of the database as specified in the DB_UNIQUE_NAME initialization parameter.
SELECT sys_context('USERENV', 'DB_UNIQUE_NAME') FROM dual;

SELECT name, value
FROM gv$parameter
where name LIKE 'db%name';
ENTRYID | The available auditing entry identifier. You cannot use this option in distributed SQL statements. To use this keyword in USERENV, the initialization parameter AUDIT_TRAIL must be set to true.
ENTERPRISE_IDENTITY Returns the user's enterprise-wide identity:
  • For enterprise users: the Oracle Internet Directory DN.
  • For external users: the external identity (Kerberos principal name, Radius and DCE schema names, OS user name, Certificate DN).
  • For local users and SYSDBA/SYSOPER logins: NULL.

The value of the attribute differs by proxy method:

  • For a proxy with DN: the Oracle Internet Directory DN of the client
  • For a proxy with certificate: the certificate DN of the client for external users; the Oracle Internet Directory DN for global users
  • For a proxy with username: the Oracle Internet Directory DN if the client is an enterprise users; NULL if the client is a local database user.
FG_JOB_ID | Job ID of the current session if it was established by a client foreground process. Null if the session was not established by a foreground process.
GLOBAL_CONTEXT_MEMORY | The number used in the System Global Area by the globally accessed context.
SELECT sys_context('USERENV', 'GLOBAL_CONTEXT_MEMORY') FROM dual;
GLOBAL_UID | Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) logins; returns null for all other logins.
HOST | Name of the host machine from which the client has connected.
SELECT sys_context('USERENV', 'HOST') FROM dual;
IDENTIFICATION_TYPE Returns the way the user's schema was created in the database. Specifically, it reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that follows, the syntax used during schema creation is followed by the identification type returned:
  • IDENTIFIED BY password: LOCAL
  • IDENTIFIED EXTERNALLY: EXTERNAL
  • IDENTIFIED GLOBALLY: GLOBAL SHARED
  • IDENTIFIED GLOBALLY AS DN: GLOBAL PRIVATE
SELECT sys_context('USERENV', 'IDENTIFICATION_TYPE') FROM dual;
INSTANCE | The instance identification number of the current instance.
SELECT sys_context('USERENV', 'INSTANCE') FROM dual;
INSTANCE_NAME | The name of the instance.
SELECT sys_context('USERENV', 'INSTANCE_NAME') FROM dual;
IP_ADDRESS | IP address of the machine from which the client is connected.
ISDBA | TRUE if the session is SYS
SELECT sys_context('USERENV', 'ISDBA') FROM dual;
LANG | The ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter.
SELECT sys_context('USERENV', 'LANG') FROM dual;
LANGUAGE The language and territory currently used by your session, along with the database character set, in the form:

language_territory.characterset.
SELECT sys_context('USERENV', 'LANGUAGE') FROM dual;
MODULE | The application name (module) set through the DBMS_APPLICATION_INFO package or OCI.
SELECT sys_context('USERENV', 'MODULE') FROM dual;
NETWORK_PROTOCOL | Network protocol being used for communication, as specified in the 'PROTOCOL=protocol' portion of the connect string.
NLS_CALENDAR | The current calendar of the current session.
SELECT sys_context('USERENV', 'NLS_CALENDAR') FROM dual;
NLS_CURRENCY | The currency of the current session.
SELECT sys_context('USERENV', 'NLS_CURRENCY') FROM dual;
NLS_DATE_FORMAT | The date format for the session.
SELECT sys_context('USERENV', 'NLS_DATE_FORMAT') FROM dual;
NLS_DATE_LANGUAGE | The language used for expressing dates.
SELECT sys_context('USERENV', 'NLS_DATE_LANGUAGE') FROM dual;
NLS_SORT | BINARY or the linguistic sort basis.
SELECT sys_context('USERENV', 'NLS_SORT') FROM dual;
NLS_TERRITORY | The territory of the current session.
SELECT sys_context('USERENV', 'NLS_TERRITORY') FROM dual;
OS_USER | Operating system username of the client process that initiated the database session.
SELECT sys_context('USERENV', 'OS_USER') FROM dual;
POLICY_INVOKER | The invoker of row-level security (RLS) policy functions.
PROXY_ENTERPRISE_IDENTITY | Returns the Oracle Internet Directory DN when the proxy user is an enterprise user.
PROXY_GLOBAL_UID | Returns the global user ID from Oracle Internet Directory for Enterprise User Security (EUS) proxy users; returns NULL for all other proxy users.
PROXY_USER | Name of the database user who opened the current session on behalf of SESSION_USER.
PROXY_USERID | Identifier of the database user who opened the current session on behalf of SESSION_USER.
SERVER_HOST | The host name of the machine on which the instance is running.
SELECT sys_context('USERENV', 'SERVER_HOST') FROM dual;
SERVICE_NAME | The name of the service to which a given session is connected.
SELECT sys_context('USERENV', 'SERVICE_NAME') FROM dual;
SESSION_USER | Database user name by which the current user is authenticated. This value remains the same throughout the duration of the session.
SELECT sys_context('USERENV', 'SESSION_USER') FROM dual;
SESSION_USERID | Identifier of the database user name by which the current user is authenticated.
SELECT sys_context('USERENV', 'SESSION_USERID') FROM dual;
SESSIONID | The auditing session identifier. You cannot use this option in distributed SQL statements. This is the equivalent to the AUDSID column in gv$session.
SELECT sys_context('USERENV', 'SESSIONID') FROM dual;
SID | The session number (different from the session ID).
SELECT sys_context('USERENV', 'SID') FROM dual;
STATEMENTID | The auditing statement identifier. STATEMENTID represents the number of SQL statements audited in a given session.
TERMINAL | The operating system identifier for the client of the current session. In distributed SQL statements, this option returns the identifier for your local session. In a distributed environment, this is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations. (The return length of this parameter may vary by operating system.)
SELECT sys_context('USERENV', 'TERMINAL') FROM dual;
Context Demo

User Created Contexts 		CREATE OR REPLACE CONTEXT App_Ctx using My_pkg
ACCESSED GLOBALLY;

CREATE OR REPLACE PACKAGE my_pkg IS

PROCEDURE set_session_id(p_session_id NUMBER);
PROCEDURE set_ctx(p_name VARCHAR2, p_value VARCHAR2);
PROCEDURE close_session(p_session_id NUMBER);

END;
/

CREATE OR REPLACE PACKAGE BODY my_pkg IS

g_session_id NUMBER;

PROCEDURE set_session_id(p_session_id NUMBER) IS
BEGIN
  g_session_id := p_session_id;
  dbms_session.set_identifier(p_session_id);
end set_session_id;
--===============================================
PROCEDURE set_ctx(p_name VARCHAR2, p_value VARCHAR2) IS
BEGIN
  dbms_session.set_context('App_Ctx',p_name,p_value,USER,g_session_id);
END set_ctx;
--===============================================
PROCEDURE close_session(p_session_id NUMBER) IS
BEGIN
  dbms_session.set_identifier(p_session_id);
  dbms_session.clear_identifier;
END close_session;
--===============================================
END;
/

col var1 format a10
col var2 format a10

exec my_pkg.set_session_id(1234);
exec my_pkg.set_ctx('Var1', 'Val1');
exec my_pkg.set_ctx('Var2', 'Val2');

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;

-- Now we'll log out/log in
-- At first, the context is empty-but we rejoin the session & there it is

disconnect
connect uwclass/uwclass

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;

exec my_pkg.set_session_id(1234);

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;

-- Now we'll show that this context is tied to our user (we specified
-- USER above, if we used null anyone can join this session).

grant execute on my_pkg to scott;

conn scott/tiger

exec uwclass.my_pkg.set_session_id(1234);

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;

-- Return to the set context again and clear it

conn uwclass/uwclass

exec my_pkg.set_session_id(1234);

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;

exec my_pkg.close_session(1234);

SELECT sys_context('app_ctx', 'var1') var1,
sys_context('app_ctx', 'var2') var2
FROM dual;
Related Topics
Context
DDL Triggers
DBMS_SESSION
Row Level Security
System Triggers
USERENV


Oracle System Events
General
Source {ORACLE_HOME}/rdbms/admin/dbmstrig.sql

Event Table DDL 		CREATE TABLE event_log (
database_name  VARCHAR2(50),
client_ipadd   VARCHAR2(15),
encrypt_pwd    VARCHAR2(100),
obj_name       VARCHAR2(30),
obj_owner      VARCHAR2(30),
obj_type       VARCHAR2(20),
instance_num   NUMBER);

CREATE TABLE parent (
person_id NUMBER(5),
last_name VARCHAR2(20));
ORA_CLIENT_IP_ADDRESS

Client IP address when protocol is TCP/IP

May not work on single Windows machine: Thus the NVL 		create or replace function client_ip_address
return varchar2 is
begin
  return dbms_standard.client_ip_address;
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER LOGON
ON DATABASE

BEGIN
  IF (ora_sysevent='LOGON') THEN
    INSERT INTO event_log
    (client_ipadd)
    VALUES
    (NVL(ora_client_ip_address, 'N/A'));
  END IF;
END sysevent_trig;
/

SELECT * FROM event_log;

conn uwclass/uwclass

SELECT * FROM event_log;
ORA_DATABASE_NAME

Database name

Returns a VARCHAR2(50) 		create or replace function database_name return varchar2 is
begin
  return dbms_standard.database_name;
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER LOGON
ON DATABASE

BEGIN
  INSERT INTO event_log
  (database_name)
  VALUES
  (ora_database_name);
END sysevent_trig;
/

SELECT * FROM event_log;

conn uwclass/uwclass

SELECT * FROM event_log;
ORA_DES_ENCRYPTED_PASSWORD

The DES encrypted password of the user being created or altered 		create or replace function des_encrypted_password (user varchar2 default NULL)
return varchar2 is
begin
  return dbms_standard.des_encrypted_password(user);
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER ALTER
ON DATABASE

BEGIN
  INSERT INTO event_log
  (encrypt_pwd)
  VALUES
  (ora_des_encrypted_password);
END sysevent_trig;
/

SELECT * FROM event_log;

ALTER USER uwclass
IDENTIFIED BY sowhat;

ALTER USER uwclass
IDENTIFIED BY uwclass;

SELECT * FROM event_log;
ORA_DICT_OBJ_NAME

Name of the dictionary object on which the DDL operation occurred

Returns a VARCHAR2(30) 		create or replace function dictionary_obj_name return varchar2 is
begin
  return dbms_standard.dictionary_obj_name;
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER ALTER
ON SCHEMA

BEGIN
  INSERT INTO event_log
  (obj_name)
  VALUES
  (ora_dict_obj_name);
END sysevent_trig;
/

desc parent

ALTER TABLE parent
ADD (event_when TIMESTAMP(9));

SELECT * FROM event_log;
ORA_DICT_OBJ_NAME_LIST

Return the list of object names of objects being modified by the event 		create or replace function dictionary_obj_name_list
(object_list out ora_name_list_t)
return binary_integer is
begin
  return dbms_standard.dictionary_obj_name_list(object_list);
end;
/

ora_dict_obj_name_list is a synonym for dictionary_obj_name_list.
DECLARE
 x       PLS_INTEGER;
 nlist_t ora_name_list_t;
BEGIN
  IF ora_sysevent='ASSOCIATE STATISTICS' THEN
    x := ora_dict_obj_name_list(nlist_t);
  END IF;

  FOR i IN 1 .. x
  LOOP
    dbms_output.put_line(nlist_t(i));
  END LOOP;
END;
/
ORA_DICT_OBJ_OWNER

Owner of the dictionary object on which the DDL operation occurred

Returns a VARCHAR2(30) 		create or replace function dictionary_obj_owner return varchar2 IS
BEGIN
  return dbms_standard.dictionary_obj_owner;
END;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER ALTER
ON SCHEMA

BEGIN
  INSERT INTO event_log
  (obj_owner)
  VALUES
  (ora_dict_obj_owner);
END sysevent_trig;
/

desc parent

ALTER TABLE parent
MODIFY (event_when TIMESTAMP(6));

SELECT * FROM event_log;
ORA_DICT_OBJ_OWNER_LIST

Return the list of object owners of objects being modified by the event 		create or replace function dictionary_obj_owner_list
(owner_list out ora_name_list_t)
return binary_integer is
begin
  return dbms_standard.dictionary_obj_owner_list(owner_list);
end;
/

ora_dict_obj_name_list is a synonym for dictionary_obj_name_list.
DECLARE
 x        PLS_INTEGER;
 olist_t  ora_name_list_t; <- verify this for function
BEGIN
  IF ora_sysevent = 'ASSOCIATE STATISTICS' THEN
    x := ora_dict_obj_owner_list(olist_t);
  END IF;

  FOR i IN 1 .. x
  LOOP
    dbms_output.put_line(olist_t(i));
  END LOOP;
END;
/
ORA_DICT_OBJ_TYPE

Type of the dictionary object on which the DDL operation occurred

Returns a VARCHAR2(20) 		create or replace function dictionary_obj_type return varchar2 is
begin
return dbms_standard.dictionary_obj_type;
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER ALTER
ON SCHEMA

BEGIN
  INSERT INTO event_log
  (obj_type)
  VALUES
  (ora_dict_obj_type);
END sysevent_trig;
/

desc parent

ALTER TABLE parent
MODIFY (event_when DATE);

SELECT * FROM event_log;
ORA_GRANTEE

Return the grantees of a grant event 		create or replace function grantee (user_list out ora_name_list_t)
return binary_integer is
begin
  return dbms_standard.grantee(user_list);
end;
/

ora_dict_obj_name_list is a synonym for dictionary_obj_name_list.
DECLARE
 x        PLS_INTEGER;
 glist_t  ora_name_list_t; -- verify this for function
BEGIN
  IF ora_sysevent = 'GRANT' THEN
    num_users := ora_grantee(glist_t);
  END IF;

  FOR i IN 1 .. x
  LOOP
    dbms_output.put_line(glist_t(i));
  END LOOP;
END;
/
ORA_INSTANCE_NUM

Instance number 		create or replace function instance_num return binary_integer is
begin
  return dbms_standard.instance_num;
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
AFTER LOGON
ON DATABASE

BEGIN
  INSERT INTO event_log
  (instance_num)
  VALUES
  (ora_instance_num);
END sysevent_trig;
/

conn uwclass/uwclass

SELECT * FROM event_log;
ORA_IS_ALTER_COLUMN

Returns true if the specified column is altered 		create or replace function is_alter_column (column_name varchar2)
return boolean is
begin
  return dbms_standard.is_alter_column(column_name);
end;
/
CREATE OR REPLACE TRIGGER sysevent_trig
BEFORE ALTER
ON SCHEMA

BEGIN
  IF ora_is_alter_column('PERSON_ID') THEN
    RAISE_APPLICATION_ERROR(-20001,
    'Primary Key Column Can Not Be
    Altered');
  END IF;
END sysevent_trig;
/

ALTER TABLE parent
MODIFY (last_name VARCHAR2(25));

ALTER TABLE parent
MODIFY (person_id NUMBER(6));
ORA_IS_CREATING_NESTED_TABLE

Returns true if the current event is creating a nested table 		create or replace function is_creating_nested_table
return boolean is
begin
  return dbms_standard.is_creating_nested_table;
end;
/
IF (ora_sysevent = 'CREATE'
AND ora_dict_obj_type = 'TABLE'
AND ora_is_creating_nested_table) THEN
  INSERT INTO event_tab
  (
  VALUES
  ('A nested table is created');
END IF;
ORA_IS_DROP_COLUMN

Returns true if the specified column is dropped 		create or replace function is_drop_column(column_name varchar2)
return boolean is
begin
  return dbms_standard.is_drop_column(column_name);
end;
/
IF (ora_sysevent = 'ALTER'
AND ora_dict_obj_type = 'TABLE') THEN
  drop_column := ora_is_drop_column('FOO');
END IF;
ORA_IS_SERVERERROR

Returns TRUE if given error is on error stack 		create or replace function is_servererror(errno binary_integer)
return boolean is
begin
  return dbms_standard.is_servererror(errno);
end;
/
IF ora_is_servererror(error_number) THEN
  INSERT INTO event_table
  ()
  VALUES
  ('Server error!!');
END IF;
ORA_LOGIN_USER

Login user name 		create or replace function login_user return varchar2 is
begin
  return dbms_standard.login_user;
end;
/
SELECT ora_login_user
FROM dual;
ORA_PARTITION_POS

In an INSTEAD OF trigger for CREATE TABLE, the position within the SQL text where you could insert a PARTITION clause. 		create or replace function partition_pos
return binary_integer is
begin
  return dbms_standard.partition_pos;
end;
/
-- Retrieve ora_sql_txt into
-- sql_text variable first.

n := ora_partition_pos;
new_stmt := SUBSTR(sql_text, 1, n-1) ||
' ' || my_partition_clause ||
' ' || SUBSTR(sql_text, n));
ORA_PRIVILEGE_LIST

Returns the list of privileges being granted by the grantee or the list of privileges revoked from the revokee in the OUT parameter; returns the number of privileges in the return value. 		create or replace function privilege_list (priv_list out ora_name_list_t)
return binary_integer is
begin
  return dbms_standard.privilege_list(priv_list);
end;
/
IF (ora_sysevent = 'GRANT'
OR ora_sysevent = 'REVOKE') THEN
  numpriv := ora_privilege_list(priv_list);
END IF;
ORA_REVOKEE

Returns the revokees of a revoke event in the OUT parameter; returns the number of revokees in the return value. 		create or replace function revokee (user_list out ora_name_list_t) return binary_integer is
begin
  return dbms_standard.revokee(user_list);
end;
/
IF (ora_sysevent = 'REVOKE') THEN
  num_of_users := ora_revokee(user_list);
END IF;
ORA_SERVER_ERROR

Given a position (1 for top of stack), it returns the error number at that position on error stack 		create or replace function server_error (position binary_integer) return binary_integer is
begin
  return dbms_standard.server_error(position);
end;
/
INSERT INTO event_table
(?)
VALUES
('1st error ' || ora_server_error(1));
ORA_SERVER_ERROR_DEPTH
Returns the total number of error messages on the error stack create or replace function server_error_depth
return binary_integer is
begin
  return dbms_standard.server_error_depth;
end;
/
n := ora_server_error_depth;
ORA_SERVER_ERROR_MSG

Given a position (1 for top of stack), it returns the error message at that position on error stack 		create or replace function server_error_msg (position in binary_integer) return varchar2 is
begin
  return dbms_standard.server_error_msg(position);
end;
/
INSERT INTO event_table
(?)
VALUES
('1st err msg' || ora_server_error_msg(1));
ORA_SERVER_ERROR_NUM_PARAMS
Given a position (1 for top of stack), it returns the number of strings that have been substituted into the error message using a format like "%s". create or replace function server_error_num_params (position in binary_integer) return binary_integer is
begin
  return dbms_standard.server_error_num_params(position);
end;
/
n := ora_server_error_num_params(1);
ORA_SERVER_ERROR_PARAM
Given a position (1 for top of stack) and a parameter number, returns the matching substitution value (%s, %d, and so on) in the error message. create or replace function server_error_param (position in binary_integer, param in binary_integer) return varchar2 is
begin
  return dbms_standard.server_error_param(position, param);
end;
/
-- For example, the second %s in a
-- message: "Expected %s, found %s"
param := ora_server_error_param(1,2);
ORA_SQL_TXT

Returns the SQL text of the triggering statement in the OUT parameter. If the statement is long, it is broken into multiple PL/SQL table elements. The function return value shows the number of elements are in the PL/SQL table. 		create or replace function sql_txt (sql_text out ora_name_list_t)
return binary_integer is
begin
  return dbms_standard.sql_txt(sql_text);
end;
/
DECLARE
 sql_text ora_name_list_t;
 v_stmt   VARCHAR2(2000);
BEGIN
  n := ora_sql_txt(sql_text);
  FOR i IN 1..n
  LOOP
    v_stmt := v_stmt || sql_text(i);
  END LOOP;

  INSERT INTO event_table
  (?)
  VALUES
  ('text of triggering statement: '
|| v_stmt);
  COMMIT;
END;
/
ORA_SYSEVENT
System event firing the trigger: Event name is same as that in the syntax.

Returns a VARCHAR2(20) 		create or replace function sysevent return varchar2 is
begin
  return dbms_standard.sysevent;
end;
/
See Undocumented Oracle Reference
ORA_WITH_GRANT_OPTION

Returns true if the privileges are granted with grant option. 		create or replace function with_grant_option return boolean is
begin
  return dbms_standard.with_grant_option;
end;
/
IF (ora_sysevent = 'GRANT'
AND ora_with_grant_option = TRUE) THEN
  INSERT INTO event_table
  (?)
  VALUES
  ('with grant option');
END IF;
SPACE_ERROR_INFO

Returns true if the error is related to an out-of-space condition, and fills in the OUT parameters with information about the object that caused the error. 		space_error_info(
error_number     OUT NUMBER,
error_type       OUT VARCHAR2,
object_owner     OUT VARCHAR2,
table_space_name OUT VARCHAR2,
object_name      OUT VARCHAR2,
sub_object_name  OUT VARCHAR2)
IF (space_error_info(eno,typ,owner,ts,obj,
subobj) = TRUE) THEN
  dbms_output.put_line=('The object '|| obj
  || ' owned by ' || owner || ' has run out
  of space.');
END IF;
Related Topics
DDL Triggers
Exception Handling
Resumable Transactions
SYSTEM_Triggers
Undocumented Oracle


Oracle System Triggers

Oracle System Event Triggers
General
Data Dictionary Objects
dba_triggers all_triggers user_triggers trigger$
Related System Privileges administer database trigger
alter any trigger
create trigger
create any trigger
drop any trigger
System Event Trigger Types AFTER STARTUP
BEFORE SHUTDOWN

AFTER LOGON
BEFORE LOGOFF

AFTER DB_ROLE_CHANGE -- for Data Guard failover and switchover
AFTER SUSPEND
AFTER SERVERERROR (does not trap
Exceptions not trapped by AFTER SERVERERROR
  • ORA-01403: no data found (this is in the Oracle docs but does not seem to be correct)
  • ORA-01422: exact fetch returns more than requested number of rows
  • ORA-01423: error encountered while checking for extra rows in exact fetch
  • ORA-01034: ORACLE not available
  • ORA-04030: out of process memory when trying to allocate string bytes (string, string)

Disabling System Triggers 		If there is an error in a system trigger, for example an AFTER STARTUP trigger, it may be impossible to start the database. The following is the method for disabling system triggers.
/ as sysdba

set linesize 150
col NAME format a30
col VALUE format a20
col DESCRIPTION format a60

SELECT x.ksppinm NAME, y.ksppstvl VALUE, ksppdesc DESCRIPTION
FROM x$ksppi x, x$ksppcv y
WHERE x.inst_id = userenv('Instance')
AND y.inst_id = userenv('Instance')
AND x.indx = y.indx
AND x.ksppinm = '_system_trig_enabled';

ALTER SYSTEM SET "_system_trig_enabled" = TRUE SCOPE=BOTH;
Create SYSTEM EVENT TRIGGER

System Trigger Demo

Demo table and the logproc procedure (below) must be built before the trigger will compile 		CREATE OR REPLACE TRIGGER <trigger_name>
<trigger_type> ON DATABASE
CALL <procedure_name>
/
CREATE TABLE connection_audit (
login_date DATE,
user_name  VARCHAR2(30));

CREATE OR REPLACE PROCEDURE logproc IS
BEGIN
  INSERT INTO log_logons
  (login_date, user_name)
  VALUES
  (user || ' - ' || TO_CHAR(SYSDATE));
END logproc;
/

CREATE OR REPLACE TRIGGER logintrig
AFTER LOGON ON DATABASE
CALL logproc
/

conn sh/sh
conn scott/tiger
conn uwclass/uwclass

SELECT *
FROM connection_audit;

Demo Application To Log Logon Attempts ... Both Successful And Failed 		CREATE OR REPLACE TRIGGER <trigger_name>
<trigger_type> ON DATABASE
  <trigger_code>
END <trigger_name>;
/
conn uwclass/uwclass

truncate table connection_audit;

-- trigger to trap successful logons
CREATE OR REPLACE TRIGGER logon_audit
AFTER LOGON ON DATABASE
BEGIN
  INSERT INTO connection_audit
  (login_date, username)
  VALUES
  (SYSDATE, USER);
END logon_audit;
/

conn scott/tiger
conn sh/sh
conn / as sysdba
conn uwclass/uwclass

SELECT *
FROM connection_audit;

-- trigger to trap unsuccessful logons
CREATE OR REPLACE TRIGGER logon_failures
AFTER SERVERERROR
ON DATABASE

BEGIN
  IF (IS_SERVERERROR(1017)) THEN
    INSERT INTO connection_audit
    (login_date, username)
    VALUES
    (SYSDATE, 'ORA-1017');
  END IF;
END logon_failures;
/

conn scott/tigre
conn abc/def
conn test/test

conn uwclass/uwclass

SELECT *
FROM connection_audit;

/*
other errors that could be trapped include:
ORA-01004 - default username feature not supported
ORA-01005 - null password given
ORA-01035 - Oracle only available to users with restricted session priv
ORA-01045 - create session privilege not granted
*/

Demo To Log System Errors 		CREATE TABLE servererror_log (
error_datetime  TIMESTAMP,
error_user      VARCHAR2(30),
db_name         VARCHAR2(9),
error_stack     VARCHAR2(2000),
captured_sql    VARCHAR2(1000));

CREATE OR REPLACE TRIGGER log_server_errors
AFTER SERVERERROR
ON DATABASE

DECLARE
 captured_sql VARCHAR2(1000);
BEGIN
  SELECT q.sql_text
  INTO captured_sql
  FROM gv$sql q, gv$sql_cursor c, gv$session s
  WHERE s.audsid = audsid
  AND s.prev_sql_addr = q.address
  AND q.address = c.parent_handle;

  INSERT INTO servererror_log
  (error_datetime, error_user, db_name,
   error_stack, captured_sql)
  VALUES
  (systimestamp, sys.login_user, sys.database_name,
  dbms_utility.format_error_stack, captured_sql);
END log_server_errors;
/

After Logon Trigger for Tracing 		CREATE OR REPLACE TRIGGER trace_trig
AFTER LOGON
ON DATABASE
DECLARE
 sqlstr := 'ALTER SESSION SET EVENTS ''10046 TRACE NAME CONTEXT FOREVER, LEVEL 4''';
BEGIN
  IF (USER = 'UWCLASS') THEN
    execute immediate sqlstr;
  END IF;
END trace_trig;
/

After Logon Trigger for Outlines 		CREATE OR REPLACE TRIGGER trace_trig
AFTER LOGON
ON DATABASE
BEGIN
  IF (USER = 'UWCLASS') THEN
    'alter session set use_stored_outlines = uw_outlines';
  END IF;
END trace_trig;
/
Drop SYSTEM EVENT TRIGGER
Drop Trigger DROP TRIGGER <trigger_name>;
DROP TRIGGER l

DROP TRIGGER logon_failures;
Related Topics
DDL Triggers
Instead Of Trigger
SYS_CONTEXT Function
Table Triggers


Oracle Timestamp Data Type

Oracle Timestamps
General
List of Time Zones set linesize 121
col tzname format a30
col tzabbrev format a30

SELECT *
FROM gv$timezone_names;
CURRENT_TIMESTAMP
Current Timestamp | CURRENT_TIMESTAMP
SELECT CURRENT_TIMESTAMP FROM dual;
DBTIMEZONE

Current Time Zone 		DBTIMEZONE
ALTER SESSION SET time_zone = local;

SELECT DBTIMEZONE FROM dual;

SELECT CURRENT_TIMESTAMP FROM dual;

ALTER SESSION SET TIME_ZONE = '-5:0';

SELECT DBTIMEZONE FROM dual;

SELECT CURRENT_TIMESTAMP FROM dual;

ALTER SESSION SET time_zone = local;
DUMP
Returns the number of bytes and datatype of a value | DUMP(<value>)
SELECT DUMP(SYSTIMESTAMP) FROM dual;
EXTRACT

Extracts and returns the value of a specified datetime field from a datetime or interval value expression 		Values That Can Be Extracted:

YEAR
MONTH
DAY
HOUR
MINUTE
SECOND
TIMEZONE_HOUR
TIMEZONE_MINUTE
TIMEZONE_REGION
TIMEZONE_ABBR

EXTRACT (<type> FROM <datetime | interval>)
SELECT EXTRACT(YEAR FROM DATE '2007-04-01') FROM dual;
FROM_TZ
Converts a timestamp value at a time zone to a TIMESTAMP WITH TIME ZONE value | FROM_TZ(<timestamp> <timestamp>)
SELECT FROM_TZ(TIMESTAMP '2007-11-20 08:00:00', '3:00')
FROM dual;

SELECT FROM_TZ(TIMESTAMP '2007-11-20 19:30:00', '3:00')
FROM dual;
LOCALTIMESTAMP

Current date and time in the session time zone in a value of data type TIMESTAMP. The difference between this function and CURRENT_TIMESTAMP is that LOCALTIMESTAMP returns a TIMESTAMP value while CURRENT_TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value 		LOCALTIMESTAMP
ALTER SESSION SET TIME_ZONE = '-5:00';

SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM dual;

ALTER SESSION SET TIME_ZONE = '-8:00';

SELECT CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM dual;

CREATE TABLE local_test (col1 TIMESTAMP WITH LOCAL TIME ZONE);

-- The following statement fails because the mask does not include
-- the TIME ZONE portion of the return type of the function:
INSERT INTO local_test VALUES
(TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF'));

-- The following statement uses the correct format mask
-- to match the return type of LOCALTIMESTAMP:
INSERT INTO local_test VALUES
(TO_TIMESTAMP(LOCALTIMESTAMP, 'DD-MON-RR HH.MI.SSXFF PM'));

SELECT * FROM local_test;
SESSIONTIMEZONE
Returns the value of the current session's time zone | SESSIONTIMEZONE
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;

ALTER SESSION SET TIME_ZONE = '-5:00';

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;

ALTER SESSION SET time_zone = local;
SYS_EXTRACT_UTC
Returns Coordinated Universal Time (UTC, formerly Greenwich Mean Time) from a Timestamp | SYS_EXTRACT_UTC(<date_time with timezone)
SELECT SYS_EXTRACT_UTC(TIMESTAMP '2004-03-28 11:30:00.00 -08:00')
FROM dual;
SYSTIMESTAMP
Current Date Time as a Timestamp | SYSTIMESTAMP
SELECT SYSTIMESTAMP FROM dual;
TRUNC
Returns the date only | TRUNC(<value>)
SELECT TO_CHAR(SYSTIMESTAMP) FROM dual;

SELECT TO_CHAR(TRUNC(SYSTIMESTAMP)) FROM dual;
TZ_OFFSET
Returns the Time Zone Offset | TZ_OFFSET(<time_zone>)
SELECT TZ_OFFSET('US/Eastern') FROM dual;
Timestamp Data Type Demos

Timestamp (Without Time Zone) 		CREATE TABLE ts_test (
x TIMESTAMP,
y TIMESTAMP(0),
z TIMESTAMP(9));

desc ts_test

INSERT INTO ts_test
(x, y, z)
VALUES
(timestamp'2007-08-08 09:00:00.123456789',
timestamp'2007-08-08 09:00:00.123456789',
timestamp'2007-08-08 09:00:00.123456789');

set linesize 121
col x format a30
col y format a21
col z format a31

SELECT * FROM ts_test;

INSERT INTO ts_test
(x, y, z)
VALUES
(localtimestamp, localtimestamp, localtimestamp);

SELECT * FROM ts_test;

SELECT VSIZE(x), VSIZE(y), VSIZE(z)
FROM ts_test;

Table With Time Zone 		CREATE TABLE tswtz_test (
msg VARCHAR2(40),
x   TIMESTAMP WITH TIME ZONE);

desc tswtz_test

ALTER SESSION SET TIME_ZONE = '-6:00';

col x foramt a35

INSERT INTO tswtz_test
(msg, x)
VALUES
('literal TS without TZ', timestamp'2004-08-08 09:00:00.123456789');

INSERT INTO tswtz_test
(msg, x)
VALUES
('SysTimeStamp (has TZ from DB)', systimestamp);

INSERT INTO tswtz_test
(msg, x)
VALUES
('LocalTimeStamp (has NO TZ)', LocalTimeStamp);

INSERT INTO tswtz_test
(msg, x)
VALUES
('Current_Timestamp (has TZ from client)', Current_Timestamp);

SELECT * FROM tswtz_test;

/* Lastly, notice the behavior of CURRENT_DATE and SYSDATE Current_Date (new with 9i) is a lot like SYSDATE but is timezone sensitive. */

SELECT TO_CHAR(CURRENT_DATE, 'dd-mon-yyyy hh24:mi:ss'),
TO_CHAR(sysdate, 'dd-mon-yyyy hh24:mi:ss')
FROM dual;

ALTER SESSION SET time_zone = local;

SELECT TO_CHAR(CURRENT_DATE, 'dd-mon-yyyy hh24:mi:ss'),
TO_CHAR(sysdate, 'dd-mon-yyyy hh24:mi:ss')
FROM dual;

Extract Timestamp Components 		col TR format a10

SELECT
EXTRACT(year FROM systimestamp) EY,
EXTRACT(month FROM systimestamp) EM,
EXTRACT(day FROM systimestamp) ED,
EXTRACT(hour FROM systimestamp) EH,
EXTRACT(minute FROM systimestamp) EM,
EXTRACT(second FROM systimestamp) ES,
EXTRACT(timezone_hour FROM systimestamp) TH,
EXTRACT(timezone_minute FROM systimestamp) TM,
EXTRACT(timezone_region FROM systimestamp) TR,
EXTRACT(timezone_abbr FROM systimestamp) TA
FROM dual;

Extract Current Timestamp Components 		col TR format a10

SELECT
EXTRACT(year FROM current_timestamp) EY,
EXTRACT(month FROM current_timestamp) EM,
EXTRACT(day FROM current_timestamp) ED,
EXTRACT(hour FROM current_timestamp) EH,
EXTRACT(minute FROM current_timestamp) EM,
EXTRACT(second FROM current_timestamp) ES,
EXTRACT(timezone_hour FROM current_timestamp) TH,
EXTRACT(timezone_minute FROM current_timestamp) TM,
EXTRACT(timezone_region FROM current_timestamp) TR,
EXTRACT(timezone_abbr FROM current_timestamp) TA
FROM dual;

Extract Current Timestamp Components after altering the time zone 		col TR format a10

ALTER SESSION SET time_zone = 'US/Eastern';

SELECT
EXTRACT(year FROM current_timestamp) EY,
EXTRACT(month FROM current_timestamp) EM,
EXTRACT(day FROM current_timestamp) ED,
EXTRACT(hour FROM current_timestamp) EH,
EXTRACT(minute FROM current_timestamp) EM,
EXTRACT(second FROM current_timestamp) ES,
EXTRACT(timezone_hour FROM current_timestamp) TH,
EXTRACT(timezone_minute FROM current_timestamp) TM,
EXTRACT(timezone_region FROM current_timestamp) TR,
EXTRACT(timezone_abbr FROM current_timestamp ) TA
FROM dual;

set serveroutput on

DECLARE
 t TIMESTAMP WITH TIME ZONE:=timestamp'2005-01-01 01:01:01 US/Pacific';
BEGIN
  dbms_output.put_line(extract(timezone_abbr from t));
  dbms_output.put_line(extract(timezone_region from t));
END;
/

ALTER SESSION SET time_zone = local;
Interval

Interval Demo 		CREATE TABLE tint_test (
msg        VARCHAR2(25),
start_date TIMESTAMP WITH TIME ZONE,
end_date   TIMESTAMP WITH TIME ZONE,
duration_1 INTERVAL DAY(5) TO SECOND,
duration_2 INTERVAL YEAR TO MONTH);

INSERT INTO tint_test
(msg, start_date, end_date)
VALUES
('my plane ride',
timestamp'2004-08-08 17:02:32.212 US/Eastern',
timestamp'2004-08-08 19:10:12.235 US/Pacific');

INSERT INTO tint_test
(msg, start_date, end_date)
VALUES
('my vacation',
timestamp'2004-07-27 06:00:00',
timestamp'2004-08-04 18:00:00');

INSERT INTO tint_test
(msg, start_date, end_date)
VALUES
('my life', timestamp'1950-01-15 02:00:00', current_timestamp);

SELECT * FROM tint_test;

UPDATE tint_test
SET duration_1 = (end_date - start_date) DAY(5) TO SECOND,
duration_2 = (end_date - start_date) YEAR TO MONTH;

SELECT msg, duration_1, duration_2 FROM tint_test;

SELECT t.*, end_date - start_date FROM tint_test t;
Time Math

Time Math Demo 		SELECT current_timestamp + INTERVAL '5' year(1)
FROM dual;

SELECT current_timestamp + INTERVAL '10:30' MINUTE TO SECOND
FROM dual;

-- this will fail ... there is no Feb. 29th in 2005
SELECT timestamp'2004-02-29 00:00:00' + INTERVAL '1' year(1)
FROM dual;

SELECT timestamp'2004-02-28 00:00:00' + INTERVAL '1' year(1)
FROM dual;

SELECT add_months(timestamp'2004-02-29 00:00:00',12)
FROM dual;

-- math with intervals
SELECT a.duration_1 + b.duration_1 + c.duration_1
FROM tint_test a, tint_test b ,tint_test c
WHERE a.msg = 'my plane ride'
AND b.msg LIKE '%vacat%'
AND c.msg like '%life';

-- but not aggregations
SELECT SUM(duration_1)
FROM tint_test;
Related Topics
Conversion Functions
Date Functions
Miscellaneous Functions
Numeric Functions
String Functions


Oracle Translate & Replace
Note: Translate and replace are very similar in their appearance but can produce very different results. Translate replaces by position, the first character of the list to match is replaced by the first character of the replacement list. The second character with the second, and if there are characters in the list to match that do not have positional equivalents in the replacements list they are dropped.

Replace replaces the string to match with the replacement string. The replacement of a single character is the same as that of TRANSLATE.
Syntax TRANSLATE(
str1 VARCHAR2 CHARACTER SET ANY_CS,
src  VARCHAR2 CHARACTER SET STR1%CHARSET,
dest VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
Translate Built-in String Function
Single Character
Replacement 		TRANSLATE(<string>, <'list_to_match'>,<'replacements_list'>)

This demo replaces all commas with vertical bars.
SELECT TRANSLATE('comma,delimited,list', ',', '|')
FROM dual;
Multiple Character
Replacement 		The following takes a DNA sequence and returns its complement
SELECT TRANSLATE('CAG-TTT-GAC-ACA-TGG-ATC', 'ACGT', 'GATC') DNA
FROM dual;
Character Replacement
And Elimination 		The a is replaced with an e, the h has no complement and is dropped.
SELECT TRANSLATE('So What', 'ah', 'e')
FROM dual;
Eliminating Double
Quotes 		Capital A is replaced with capital A. The double quote is eliminated because there is no match.
SELECT TRANSLATE('"Darn double quotes "', 'A"', 'A')
FROM dual;
Encryption / Decryption | In this demo a string is first encrypted then decrypted
SELECT TRANSLATE('this is a secret',
'abcdefghijklmnopqrstuvxyz', '0123456789qwertyuiop[kjhbv')
FROM dual;

SELECT TRANSLATE('p78o 8o 0 o42i4p',
'0123456789qwertyuiop[kjhbv', 'abcdefghijklmnopqrstuvxyz')
FROM dual;
Counting Vowels | In this demo the number of vowels in the string is counted
WITH data AS (SELECT 'Whose line is it anyway' line FROM dual)
SELECT LENGTH(line)-LENGTH(TRANSLATE(line,'xaeiou','x')) nbVowels
FROM data;
Replace Built-in String Function
REPLACE (overload 1) REPLACE(
srcstr VARCHAR2 CHARACTER SET ANY_CS,
oldsub VARCHAR2 CHARACTER SET SRCSTR%CHARSET,
newsub VARCHAR2 CHARACTER SET SRCSTR%CHARSET := NULL)
RETURN VARCHAR2 CHARACTER SET SRCSTR%CHARSET;
REPLACE (overload 2) REPLACE(
srcstr CLOB CHARACTER SET ANY_CS,
oldsub CLOB CHARACTER SET SRCSTR%CHARSET,
newsub CLOB CHARACTER SET SRCSTR%CHARSET := NULL)
RETURN CLOB CHARACTER SET SRCSTR%CHARSET;
Single Character
Replacement 		REPLACE(<string>, <'string_to_match'>,<'replacements_string'>)
SELECT REPLACE('So What', 'o', 'ay')
FROM dual;
Multiple Character
Replacement 		Replacement of a single character with a phrase
SELECT REPLACE('An idea that is not dangerous is unworthy of being called an idea at all.', 'n idea', ' software program') TRUTH
FROM dual;
Related Topics
Built-in Functions
String Functions


Oracle Types User Defined

Oracle Types
Version 10.2
General Information
Object types and other user-defined types allow for the definition of data types that model the structure and behavior of the data in an application.
Related Data Dictionary Objects collection$
source$
type$

dba_coll_types | all_coll_types | user_coll_types
dba_dependencies | all_dependencies | user_dependencies
dba_source | all_source | user_source
dba_types | all_types | user_types
dba_varrays | all_varrays | user_varrays
System Privileges Related To Types CREATE TYPE
CREATE ANY TYPE
DROP ANY TYPE
Create Type Header

Single Column Object Declaration 		CREATE OR REPLACE TYPE <type_name>
AUTHID <CURRENT USER | DEFINER>
AS OBJECT (
<attribute> <attribute data_type>,
<inheritance clause>,
<subprogram spec>)
<FINAL | NOT FINAL> <INSTANTIABLE | NOT INSTANTIABLE>;
/
CREATE OR REPLACE TYPE ssn_t AS OBJECT (
ssn_type CHAR(11));
/

-- examine type definition
SELECT *
FROM user_source
WHERE name = 'SSN_T';

CREATE TABLE ssn (
per_id NUMBER(10),
per_ssn ssn_t);

desc SSN

-- examine table columns
SELECT column_name, data_type
FROM user_tab_cols
WHERE table_name = 'SSN';

INSERT INTO ssn VALUES (1, '123-45-6789');

INSERT INTO ssn VALUES (1, ssn_t('123-45-6789'));

SELECT * FROM ssn;

UPDATE ssn
SET per_ssn = ssn_t('111-22-3333');

SELECT * FROM ssn;

INSERT INTO ssn VALUES (1, ssn_t('999-88-7777'));

SELECT * FROM ssn;

UPDATE ssn
SET per_ssn = ssn_t('456-56-0841')
WHERE per_ssn = ssn_t('111-22-3333');

SELECT * FROM ssn;

Multicolumn Object Declaration 		CREATE OR REPLACE TYPE <type_name> AS OBJECT (
<column_name> <data_type>,
...,
<column_name> <data_type>);
/
CREATE OR REPLACE TYPE phone_t AS OBJECT (
a_code   CHAR(3),
p_number CHAR(8));
/

-- examine type definition
SELECT *
FROM user_source
WHERE name = 'PHONE_T';

CREATE TABLE phone (
per_id    NUMBER(10),
per_phone phone_t);

set describe depth all

desc phone

-- examine table columns
col data_type format a15
col data_type_owner format a15

SELECT column_name, data_type, data_type_mod, data_type_owner
FROM user_tab_cols
WHERE table_name = 'PHONE';

INSERT INTO phone
(per_id, per_phone)
VALUES
(1, phone_t('206', '555-1212'));

INSERT INTO phone
(per_id, per_phone)
VALUES
(2, phone_t('212', '123-4567'));

SELECT * FROM phone;

SELECT per_id FROM phone;

SELECT per_id, per_phone
FROM phone;

-- selective select
SELECT *
FROM phone p
WHERE p.per_phone.a_code = '206';

SELECT p.per_phone.p_number
FROM phone p
WHERE p.per_phone.a_code = '206';

-- selective update
UPDATE phone p
SET p.per_id = 9
WHERE p.per_id = 1;

SELECT * FROM phone;

UPDATE phone p
SET p.per_phone.a_code = '303'
WHERE p.per_phone.a_code = '206';

SELECT * FROM phone;

-- selective delete
DELETE FROM phone p
WHERE p.per_id = 2;

SELECT * FROM phone;

DELETE FROM phone p
WHERE p.per_phone.a_code = '206';

SELECT * FROM phone;
Create Subtype

Subtype Creation 		CREATE OR REPLACE TYPE <type_name>
AUTHID <CURRENT USER | DEFINER>
UNDER <supertype_name>,
<attribute> <data_type>,
<inheritance clause> <subprogram spec>, <pragma clause>)
<FINAL | NOT FINAL> <INSTANTIABLE | NOT INSTANTIABLE>;
/
-- create object supertype
CREATE OR REPLACE TYPE person_typ AS OBJECT (
ssn NUMBER(9), name VARCHAR2(30), address VARCHAR2(100))
NOT FINAL;
/

-- derive collection type from supertype
CREATE OR REPLACE TYPE person_tab_typ AS TABLE OF person_typ;
/

-- derive object subtype from object supertype
CREATE OR REPLACE TYPE student_typ UNDER person_typ (
deptid NUMBER, major VARCHAR2(30))
NOT FINAL;
/

-- derive collection type from subtype
CREATE OR REPLACE TYPE student_tab_typ AS TABLE OF student_typ;
/

-- create nested table from the two collection
CREATE TABLE test (
regular_field       DATE,
person_nested_tab   person_tab_typ,
student_nested_tab  student_tab_typ)
NESTED TABLE person_nested_tab STORE AS per_tab
NESTED TABLE student_nested_tab STORE AS stu_tab;

desc test
desc per_tab
desc stu_tab
Create Type Body

Create A Collection From An Object
CREATE OR REPLACE TYPE people_typ AS OBJECT (
last_name     VARCHAR2(25),
department_id NUMBER(4),
salary        NUMBER(8,2));
/

CREATE OR REPLACE TYPE people_tab_typ AS TABLE OF people_typ;
/

CREATE TABLE hr_info (
department_id NUMBER(4),
location_id   NUMBER(4),
manager_id    NUMBER(6),
people        people_tab_typ)
NESTED TABLE people STORE AS people_stor_tab;

DESC hr_info

INSERT INTO hr_info
VALUES
(100, 1800, 999, people_tab_typ());

INSERT INTO hr_info
VALUES
(200, 2000, 881, people_tab_typ());

SELECT * FROM hr_info;
Create Type As Variable
Create Type As Variable In Package Header
Row Data Type Declaration
Array Data Type Declaration
TYPE ARRAY IS TABLE OF all_objects%ROWTYPE;
l_data ARRAY;
Create Type Header As Database Object

Type Collection Of A User Defined Object Data Type 		CREATE OR REPLACE TYPE <type_name> AS TABLE OF  <user_defined_data_type>;
/
CREATE OR REPLACE TYPE phones_tab_t AS TABLE OF phone_t;
/

SELECT object_name, object_type
FROM user_objects;

SELECT type_name, typecode
FROM user_types;

SELECT type_name, coll_type
FROM user_coll_types;

Heap Table Of A User Defined Data Object Type 		CREATE TABLE <table_name>
column_name <user_defined_data_type);
CREATE TABLE test (
person_id   NUMBER(10),
per_phones  phone_t);

desc test

COL data_type FORMAT a40

SELECT column_name, data_type
FROM user_tab_cols
WHERE table_name = 'TEST';

Heap Table Of With A User Defined Data Object Type As A Nested Table 		CREATE TABLE <table_name> (
column_name   <user_defined_data_type>)
NESTED TABLE <column_name> STORE AS <name_of_nested_table>;
CREATE TABLE person (
person_id     NUMBER(10),
first_name    VARCHAR2(25),
middle_inits  VARCHAR2(4),
last_name     VARCHAR2(25),
name_suffix   VARCHAR2(5),
title_1       VARCHAR2(5),
title_2       VARCHAR2(5),
dob           DATE,
ssn           VARCHAR2(11),
address_id    NUMBER(10),
person_phones phones_tab_t,
email_address VARCHAR2(30),
ok_to_mail    VARCHAR2(1),
active_flag   VARCHAR2(1))
NESTED TABLE person_phones STORE AS phones_tab
TABLESPACE uwdata;

desc person

COL table_name FORMAT a30
COL table_type_name FORMAT a20
COL parent_table_column FORMAT a25

SELECT table_name, table_type_name, parent_table_column
FROM user_nested_tables;

Insert Into Parent And Nested Table 		INSERT INTO <table_name>
(<column_name_list>)
VALUES
(<list_of_column_values>, <table_type_constructor>(<type_constructor(<type_values>)));
INSERT INTO person
(person_id, last_name, person_phones)
VALUES
(1, 'Morgan', phones_tab_t(phone_t('C', '206-555-1212')));

INSERT INTO person
(person_id, last_name, person_phones)
VALUES
(2, 'Cline', phones_tab_t(phone_t('C', '425-555-1212')));

Insert Into Nested Table 		INSERT INTO TABLE (
SELECT <nested_table_column_name>
FROM <table_name>
WHERE <column_name> <condition <value>)
VALUES
(<column_value>, <column_value>);
INSERT INTO TABLE(
SELECT person_phones
FROM person
WHERE person_id = 1)
VALUES
('H','206-987-6543');

SELECT t1.person_id, last_name, t2.*
FROM person t1, TABLE(t1.person_phones) t2;
Select From Nested Table | SELECT <column_name_list> FROM <table_name>;
SELECT * FROM person;
Select From Nested Table With TABLE Function SELECT <column_name_list, <tested_table_column_list>
FROM <table> <alias>, TABLE (<alias.nested_table_name> <alias>;
SELECT person_id, last_name, t2.*
FROM person t1, TABLE(t1.person_phones) t2;

Update All Nested Table Rows 		UPDATE person
SET person_phones =   <table_constructor>(<type_constructor(<column_values>));
UPDATE person
SET person_phones = phones_tab_t(phone_t('H', '360-555-1212'))
WHERE person_id = 2;

Update Selected Nested Table Rows 		UPDATE TABLE (
<nested_select_statment>) <alias>
SET <nested_column> = <value>
WHERE <alias.nested_column_name> <condition> <value>;
UPDATE TABLE (
SELECT person_phones
FROM person
WHERE person_id = 1) p
SET p.phone_type = 'W'
WHERE p.phone_number = '206-987-6543';

SELECT t1.person_id, last_name, t2.*
FROM person t1, TABLE(t1.person_phones) t2;

Delete From Nested Table 		DELETE TABLE (
<nested_select_statment>) <alias>
WHERE <alias.nested_column_name> <condition> <value>;
DELETE TABLE (
SELECT person_phones
FROM person
WHERE person_id = 1) p
WHERE p.phone_number = '206-987-6543';
SELECT a_code FROM TABLE (
SELECT per_phone
FROM phone h) p
WHERE 1=1;
Create Type Header As Database Varray

User Defined Object Data Type 		-- same as above

CREATE OR REPLACE TYPE <type_name> AS OBJECT (
<column_name> <data_type>);
/
CREATE OR REPLACE TYPE title_t AS OBJECT (
title_name VARCHAR2(5));
/

SELECT type_name, typecode
FROM user_types;

Define VARRAY Of Object Type 		CREATE TYPE TitleList AS VARRAY(<integer>) OF <data_type>;
/

SELECT type_name, typecode
FROM user_types;
CREATE TYPE TitleList AS VARRAY(3) OF title_t;
/

SELECT type_name, typecode
FROM user_types;

Heap Table With Nested Varray 		CREATE TABLE <table_name> (
column_name  varray_name);
DROP TABLE person;

CREATE TABLE person (
person_id     NUMBER(10),
first_name    VARCHAR2(25),
middle_inits  VARCHAR2(4),
last_name     VARCHAR2(25),
name_suffix   VARCHAR2(5),
person_titles title_t,
dob           DATE,
ssn           VARCHAR2(11),
address_id    NUMBER(10),
person_phones phones_tab_t,
email_address VARCHAR2(30),
ok_to_mail    VARCHAR2(1),
active_flag   VARCHAR2(1))
NESTED TABLE person_phones STORE AS phones_tab
TABLESPACE uwdata;

desc person

COL parent_table_column FORMAT a30

SELECT parent_table_name, parent_table_column, type_name
FROM user_varrays;
 -- note there is no record

Insert Into Parent, Varray, And Nested Table 		INSERT INTO <table_name>
(<column_name_list>)
VALUES
(<list_of_column_values>,
<varray_constructor>(<varray_values>) <table_type_constructor>(<type_constructor(<type_values>)));
INSERT INTO person
(person_id, last_name, person_titles, person_phones)
VALUES
(1, 'Morgan', title_t('PhD'),
phones_tab_t(phone_t('C', '206-555-1212')));

INSERT INTO person
(person_id, last_name, person_titles, person_phones)
VALUES
(2, 'Cline', title_t('MD'),
phones_tab_t(phone_t('C', '425-555-1212')));

Insert Into Nested Varray

COL person_titles FORMAT a20

SELECT t1.person_id, last_name, person_titles, t2.*
FROM person t1, TABLE(t1.person_phones) t2;
Select From Nested Table | SELECT <column_name_list> FROM <table_name>;
SELECT person_id, last_name, person_titles, person_phones
FROM person;
Select From Nested Table With TABLE Function SELECT <column_name_list, <tested_table_column_list>
FROM <table> <alias>, TABLE (<alias.nested_table_name> <alias>
SELECT person_id, last_name, t2.*
FROM person t1,
TABLE(t1.person_phones) t2;

Update All Nested Table Rows 		UPDATE person
SET person_phones =   <table_constructor>(<type_constructor(<column_values>));
UPDATE person
SET person_phones = phones_tab_t(phone_t('H', '360-555-1212'))
WHERE person_id = 2;

Update Selected Nested Table Rows 		UPDATE TABLE (
<nested_select_statment>) <alias>
SET <nested_column> = <value>
WHERE <nested_column_name> <condition> <value>
UPDATE TABLE (
SELECT person_phones
FROM person
WHERE person_id = 1) p
SET p.phone_type = 'W'
WHERE p.phone_number = '206-987-6543';

SELECT t1.person_id, last_name, t2.*
FROM person t1, TABLE(t1.person_phones) t2;

Delete From Nested Table 		DELETE TABLE (
<nested_select_statment>) <alias>
DELETE TABLE (
SELECT person_phones
FROM person
WHERE person_id = 1) p
WHERE p.phone_number = '206-987-6543';
Create Type Body (always as a database object)
Create Type CREATE OR REPLACE TYPE ssn AS OBJECT (
ssn_type CHAR(11));
/
Create Type Specification (Header) CREATE OR REPLACE TYPE ssn AS OBJECT (
n_ CHAR(11),
CONSTRUCTOR FUNCTION ssn(n IN VARCHAR2)
RETURN self AS result,
MEMBER FUNCTION get_ssn RETURN CHAR);
/

Create Type Body 		CREATE OR REPLACE TYPE BODY ssn IS

CONSTRUCTOR FUNCTION ssn(ssn_in IN VARCHAR2)
RETURN self AS RESULT IS

BEGIN
  IF TRANSLATE(ssn_in, 'A0123456789', 'BAAAAAAAAAA') =
    'AAA-AA-AAAA' THEN
    n_ := ssn_in;
    RETURN;
  ELSE
    RAISE_APPLICATION_ERROR(-20001, 'INVALID SSN');
  END IF;
END;

MEMBER FUNCTION get_ssn RETURN CHAR IS

BEGIN
   RETURN n_;
END;

END;
/
Create Object Table CREATE TABLE person (
per_name VARCHAR2(20),
per_ssn  SSN);

Test SSN Data Type 		DECLARE

myssn ssn;

BEGIN
   myssn := ssn(n=>'232-22-5678');
   INSERT INTO person VALUES ('Morgan', myssn);

-- myssn := ssn(n=>'444=55-6789');
-- INSERT INTO person VALUES ('Morgan', myssn);

   myssn := ssn(n=>'123-45-6789');
   INSERT INTO person VALUES ('Cline', myssn);
   COMMIT;
END;
/
Alter Type

Alter Type Demo 		ALTER TYPE <type name> ADD ATTRIBUTE (<atribute name> <data type>) CASCADE;
CREATE OR REPLACE TYPE phone_t AS OBJECT (
a_code   CHAR(3),
p_number CHAR(8)) NOT FINAL;
/

desc phone_t

CREATE OR REPLACE TYPE phone_t_tab AS TABLE OF phone_t;
/

desc phone_t_tab

--produces an error
CREATE OR REPLACE TYPE phone_t AS OBJECT (
country_code CHAR(3),
area_code    CHAR(3),
phone_number CHAR(8));
/

ALTER TYPE phone_t ADD ATTRIBUTE (country_code CHAR(3)) CASCADE;

desc phone_t
Drop Type
Dropping a Type | DROP TYPE <type_name>
DROP TABLE person;

DROP TYPE phones_tab_t;
DROP TYPE phone_t;
Type Inheritance
Create Supertype CREATE OR REPLACE TYPE person_typ AS OBJECT (
ssn NUMBER(9), name VARCHAR2(30), address VARCHAR2(100))
NOT FINAL;
/
Create Type From Subtype CREATE OR REPLACE TYPE person_tab_typ AS TABLE OF person_typ;
/
Create Subtype CREATE OR REPLACE TYPE student_typ UNDER person_typ (
deptid NUMBER, major VARCHAR2(30))
NOT FINAL;
/
Create Type From Subtype CREATE OR REPLACE TYPE student_tab_typ
AS TABLE OF student_typ;
/

Create Table With Two
Nested Tables 		CREATE TABLE test (
regular_field       DATE,
person_nested_tab   person_tab_typ,
student_nested_tab  student_tab_typ)
NESTED TABLE person_nested_tab STORE AS per_tab
NESTED TABLE student_nested_tab STORE AS stu_tab;

desc test
desc per_tab
desc stu_tab

Insert A Row 		INSERT INTO test
VALUES
(SYSDATE, person_tab_typ(), student_tab_typ(student_typ(987654321, 'Cline', 'PO Box 0', 101, 'Computer Science')));

INSERT INTO test
VALUES
(SYSDATE, person_tab_typ(), student_tab_typ(student_typ(987654321, 'Cline', 'PO Box 0', 101, 'Computer Science'),
student_typ(12345, 'Starr', '123 Main St', 102, 'Agricultureal Science')));

INSERT INTO test
VALUES
(TRUNC(SYSDATE), person_tab_typ(), student_tab_typ());

SELECT * FROM test;

INSERT INTO TABLE (
SELECT person_nested_tab
FROM test
WHERE regular_field = TRUNC(SYSDATE))
VALUES (111223456, 'Morgan', '123 Main Street');

SELECT * FROM test;

INSERT INTO TABLE (
SELECT student_nested_tab
FROM test
WHERE regular_field = TRUNC(SYSDATE))
VALUES (987654321, 'Cline', 'PO Box 123', 101, 'Frontal Lobotomy Can Be Fun' );

INSERT INTO TABLE (
SELECT student_nested_tab
FROM test
WHERE regular_field = TRUNC(SYSDATE))
VALUES (987654321, 'Cline', 'PO Box 123', 299, 'Advanced Basket Weaving');

SELECT * FROM test;

SET HEAD OFF

SELECT t1.*, t2.*, t3.*
FROM test t1,
     TABLE(person_nested_tab) t2,
     TABLE(student_nested_tab) t3;
Hold

Constructor for a Nested Table 		In the following example, you pass multiple elements to the constructor CourseList(), which returns a nested table  containing those elements:

DECLARE

TYPE CourseList IS TABLE OF VARCHAR2(16);
my_courses CourseList;

BEGIN
my_courses := CourseList('Econ 2010','Acct 3401','Mgmt 3100');
END;
/

Because a PL/SQL table does not have a declared maximum size, you can put as many elements in the constructor as necessary.

DECLARE

TYPE CourseList IS TABLE OF VARCHAR2(16);
my_courses CourseList;

BEGIN
  my_courses := CourseList('Econ 2010','Acct 3401','Mgmt 3100');
  my_courses := CourseList('Math 2022','Acct 3431','Mgmt 3100');
  my_courses := CourseList('Phys 2299','Chem 9876');
  my_courses := CourseList('Food 9999');
  my_courses := CourseList('Orcl 3456','Math 3434','Hist 1040');
END;
/
Defining a Type as a database object CREATE OR REPLACE TYPE CourseList AS TABLE OF VARCHAR2(64);
/

Defining Types in a package header 		CREATE OR REPLACE PACKAGE xyz IS

TYPE CourseList IS TABLE OF VARCHAR2(64);

TYPE PartNum IS TABLE OF parent.part_num%TYPE
INDEX BY BINARY_INTEGER;

END;
/
set serveroutput on

DECLARE
 TYPE demo IS TABLE OF VARCHAR2(32767);
 x demo;
BEGIN
  x := demo(RPAD('X', 32766, 'Z'));
  dbms_output.put_line(x(1));
END;
/
CREATE TYPE data_typ AS OBJECT
(year NUMBER, MEMBER FUNCTION prod(invent NUMBER) RETURN NUMBER);

CREATE TYPE BODY data_typ IS

MEMBER FUNCTION prod (invent NUMBER) RETURN NUMBER IS
BEGIN
    RETURN (year + invent);
END;

END;
/
CREATE TYPE person_t AS OBJECT (name VARCHAR2(100), ssn NUMBER)
NOT FINAL;

CREATE TYPE employee_t UNDER person_t
(department_id NUMBER, salary NUMBER) NOT FINAL;

CREATE TYPE part_time_emp_t UNDER employee_t (num_hrs NUMBER);
CREATE OR REPLACE TYPE emp_type  AS OBJECT (
eno NUMBER, ename CHAR(31) , eaddr addr_t);
CREATE OR REPLACE TYPE phone_t AS OBJECT (
a_code   CHAR(3),
p_number  CHAR(8));
/
-- user defined data type for use by function
CREATE OR REPLACE TYPE InStrTab IS TABLE OF VARCHAR2(4000);
/

CREATE OR REPLACE FUNCTION contains_all (useridin dms_user.id%TYPE, stringin VARCHAR2, checkint INTEGER) RETURN INTEGER IS

 i BINARY_INTEGER;
 my_table dbms_utility.uncl_array;
 stringary InStrTab;

BEGIN
  -- convert stringin of domain ids into a PL/SQL table
  dbms_utility.comma_to_table(stringin, i, my_table);
  -- initialize a collection
  stringary := InStrTab('');
  -- extend the collection to the size of the PL/SQL table
  stringary.EXTEND(my_table.COUNT);

  -- for each element in the PL/SQL table
  FOR j IN 1 .. my_table.COUNT LOOP
    -- remove the double-quotes
    my_table(j) := TRANSLATE(my_table(j), 'A"', 'A');
    -- assign it to an element in the array
    stringary(j) := my_table(j);
  END LOOP;

  -- check the count of array elements found in the user_domain_map table
  SELECT COUNT(*)
  INTO i
  FROM zuser_domain_map
  WHERE user_id = useridin
  AND domain_id IN (
    SELECT column_value
    FROM TABLE(CAST(stringary AS InStrTab)));

  -- compare the number found agains the checksum
  IF i >= checkint THEN
    RETURN 1;
  ELSE
    RETURN 0;
  END IF;
END contains_all;
/

-- How to test:

SELECT contains_all(121, '"200","201","207"',3)
FROM dual;
Related Topics
Collections
Nested Tables
REF Cursors
VArrays


Undocumented Oracle
ADJ_DATE
Undocumented

Appears to cast a timestamp to a date 		adj_date(<expression> IN DATE) RETURN DATE
CREATE TABLE t(
dcol TIMESTAMP);

INSERT INTO t VALUES (SYSTIMESTAMP);

SELECT dump(adj_date(dcol)), dump(dcol), dump(SYSTIMESTAMP)
FROM t;
CSCONVERT

Undocumented

Appears to be related to Character Set conversion 		csconvert
CREATE TABLE t (
vchar VARCHAR2(20),
nchar NVARCHAR2(20));

INSERT INTO t VALUES ('??', n'??');

SELECT * FROM t;

set linesize 121
col a format a25
col b format a25
col c format a25
col d format a25

SELECT dump(vchar) a, dump(csconvert(vchar,'NCHAR_CS'),16) b,dump(vchar,16) c, dump(nchar,16) d
FROM t;

SELECT dump(csconvert(vchar,'CHAR_CS'),16) a,dump(vchar,16) b,dump(nchar,16) c, dump(nchar,16) d
FROM t;

SELECT dump(csconvert(nchar,'NCHAR_CS'),16) a,dump(vchar,16) b,dump(nchar,16) c, dump(nchar,16) d
FROM t;

SELECT dump(csconvert(nchar,'CHAR_CS'),16) a,dump(vchar,16) b,dump(nchar,16) c, dump(nchar,16) d
FROM t;
CURRENTV
Related to the Model Clause | CURRENTV(<arg>)
SELECT currentv(1) FROM dual;
       *
ERROR at line 1:
ORA-32644: this function is not allowed outside of MODEL clause
DENSE_RANKM
Undocumented
Introduced in 9i 		DENSE_RANKM(
SELECT dense_rankm(1,1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments
FIRSTM
Undocumented
Introduced in 9i 		FIRSTM(
SELECT firstm(1,1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments
MAKEXML
Undocumented
Introduced in 9i 		MAKEXML(<arg>)
-- Found on the internet: Source

SELECT EXTRACT(VALUE(j),'/n-document').getclobval() res
FROM jnl_docs j
WHERE (EXTRACTVALUE(SYS_MAKEXML("XMLDATA"),'/n-document/@guid') = 'I0050092942E540D0BD4B898F70448E97') OR
(EXTRACTVALUE(SYS_MAKEXML("XMLDATA"),'/n-document/n-docbody/metadata/cit-wlde') = 'WLDE2001-0005938');
MERGE$ACTIONS

Undocumented
Introduced in 8i

Returns a string with 'B' in position n if arg1[n] <> arg2[n], otherwise returns the matched character. 		MERGE$ACTIONS(<arg1> IN VARCHAR2, <arg2> IN VARCHAR2) RETURN VARCHAR2
SELECT merge$actions('ABC', 'ABD') FROM dual;

SELECT merge$actions('ABC', 'ABC') FROM dual;

SELECT merge$actions('ABCDDD', 'ABCEDD') FROM dual;

SELECT merge$actions(1234, 1264) FROM dual;

SELECT merge$actions(SYSDATE, SYSDATE+35) FROM dual;
ORA_NAME_LIST_T

ORA_NAME_LIST_T

ORA_SQL_TXT retrieves
the SQL text of the triggering statement 		ora_name_list_t & oora_sql_txt
CREATE OR REPLACE TRIGGER det_grant
AFTER grant
ON schema

DECLARE
 priv_list ora_name_list_t;
 user_list ora_name_list_t;

 l_str VARCHAR2(255);
 l_job NUMBER;
BEGIN
  IF ora_sysevent = 'GRANT'
  AND ora_privilege_list(priv_list) > 0
  AND ora_dict_obj_type = 'OBJECT PRIVILEGE' THEN
    FOR i IN 1 .. ora_grantee(user_list)
    LOOP
      IF (user_list(i) = 'PUBLIC') THEN
        l_str := 'execute immediate "revoke all on ' ||
        ora_dict_obj_name || ' from public";';

        dbms_job.submit(l_job, replace(l_str,'"',''''));

        l_str := 'execute immediate "grant select, insert,
        delete, update on ' || ora_dict_obj_name || ' to
        my_role";';

        dbms_job.submit(l_job, replace(l_str,'"',''''));
      END IF;
    END LOOP;
  END IF;
END det_grant;
/

GRANT select, update, delete ON servers TO scott;
PERCENT_RANKM
Undocumented
Introduced in 9i 		PERCENT_RANKM(
SELECT percent_rankm(1,1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments
RANKM
Undocumented
Introduced in 9i 		RANKM(
SELECT rankm(1,1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments
SYS_CHECKACL

Used as part of the EXPLAIN PLAN output for a query on an XMLType table created as a result of calling PL/SQL procedure DBMS_XMLSCHEMA

SYS_CHECKACL()
3 - filter(SYS_CHECKACL("ACLOID","OWNERID",xmltype(''<privilege
xmlns="http://xmlns.oracle.com/xdb/acl.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.oracle.com/xdb/acl.xsd
http://xmlns.oracle.com/xdb/acl.xsd
DAV:http://xmlns.oracle.com/xdb/dav.xsd">
 <read-properties/><read-contents/></privilege>''))=1)
SYS_DOM_COMPARE
Undocumented
Introduced in 9i 		SYS_DOM_COMPARE(<arg1>, <arg2>)
SELECT sys_dom_compare(1,1) FROM dual;
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got -
SYS_ET_BFILE_TO_RAW
Undocumented
Introduced in 10.1 		SYS_ET_BFILE_TO_RAW(arg IN bfile);
conn pm/pm

SELECT sys_et_bfile_to_raw(ad_graphic)
FROM print_media;
SYS_ET_BLOB_TO_IMAGE
Undocumented
Introduced in 10.1 		SYS_ET_BLOB_TO_IMAGE(<blob arg>, arg2, arg3);
conn pm/pm

SELECT sys_et_blob_to_image(ad_photo, ad_composite, 'TEST')
FROM print_media;
                                      *
ERROR at line 1:
ORA-30175: invalid type given for an argument
SYS_ET_IMAGE_TO_BLOB
Undocumented
Introduced in 10.1 		SYS_ET_IMAGE_TO_BLOB(<blob arg>, arg2, arg3);
conn pm/pm

SELECT sys_et_image_to_blob(ad_photo)
FROM print_media;
                            *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got BLOB
SYS_ET_RAW_TO_BFILE
Undocumented
Introduced in 10.1 		SYS_ET_RAW_TO_BFILE
SELECT sys_et_raw_to_bfile(utl_raw.cast_to_raw( '00094D454449415F44495200096D6F64656D2E6A7067')) FROM dual;
                  *
ERROR at line 1:
ORA-22298: length of directory alias name or file name too long
SYS_FBT_INSDEL
Undocumented | SYS_FBT_INSDEL
SELECT sys_fbt_insdel FROM dual;
SYS_OP_BL2R
Undocumented
Introduced in 9.2

Appears to converts BLOB to RAW 		SYS_OP_CL2C(<arg> IN CLOB)
conn pm/pm

SELECT sys_op_bl2r(ad_photo)
FROM print_media;
SELECT sys_op_bl2r(ad_photo)
       *
ERROR at line 1:
ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion (actual: 5482, maximum: 2000)
SYS_OP_CEG

Undocumented
Introduced in 9.2

SYS_OP_CEG
SELECT sys_op_ceg(1) FROM dual;
       *
ERROR at line 1:
ORA-00938: not enough arguments for function

SELECT sys_op_ceg('A',1) FROM dual;
                   *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected UDT got CHAR
SYS_OP_CL2C
Undocumented
Introduced in 9.2

Appears to converts CLOB to CHAR 		SYS_OP_CL2C(<arg> IN CLOB)
conn pm/pm

SELECT sys_op_cl2c(ad_finaltext)
FROM print_media;
SYS_OP_CONVERT
Undocumented
Introduced in 9.2 		SYS_OP_CONVERT(<arg1>, <arg2>)
SELECT dump('Morgan'), dump(sys_op_convert('Morgan', 'IS8PC861', 'RU8PC866'))
FROM dual;
SYS_OP_COUNTCHG

Undocumented 		SYS_OP_COUNTCHG(rowid, integer_between_1_and_255)
SELECT COUNT(DISTINCT dbms_rowid.rowid_block_number(rowid))
FROM airplanes;

SELECT sys_op_countchg(SUBSTRB(ROWIDTOCHAR("AIRPLANES".ROWID),1,15),1)
FROM airplanes;

EXPLAIN PLAN FOR
SELECT COUNT(DISTINCT dbms_rowid.rowid_block_number(rowid))
FROM airplanes;

SELECT * FROM TABLE(dbms_xplan.display);

EXPLAIN PLAN FOR
SELECT sys_op_countchg(SUBSTRB(ROWIDTOCHAR("AIRPLANES".ROWID),1,15),1)
FROM airplanes;

SELECT * FROM TABLE(dbms_xplan.display);

-- note difference between SORT GROUP BY and SORT AGGREGATE
SYS_OP_C2C
Undocumented
Introduced in 10.1 		SYS_OP_C2C(<arg> INTEGER);
SELECT sys_op_c2c(67) FROM dual;

SELECT sys_op_c2c(97) FROM dual;
SYS_OP_DESCEND
Descending Index /*
 An internal function that takes a value and returns the form that would be stored for that value in a descending index. Essentially doing a one's complement on the bytes and appending an 0xFF byte
*/

SYS_OP_DESCEND(<expression> IN VARCHAR2);
SELECT sys_op_descend('0A')
FROM dual;

SELECT sys_op_descend('Dan Morgan')
FROM dual;
SYS_OP_DISTINCT

Undocumented

Returns 0 if the columns are identical in value, 1 if they are not

Overload 1 		SYS_OP_DISTINCT(col1 IN NUMBER, col2 IN NUMBER);
CREATE TABLE t (
col1 NUMBER(3),
col2 NUMBER(3));

INSERT INTO t VALUES (1,1);
INSERT INTO t VALUES (1,2);
INSERT INTO t VALUES (2,1);
INSERT INTO t VALUES (2,2);
INSERT INTO t VALUES (1,NULL);

SELECT * FROM t;

SELECT sys_op_distinct(col1, col2)
FROM t;

Overload 2 		SYS_OP_DISTINCT(col1 IN VARCHAR2, col2 IN VARCHAR2);
CREATE TABLE t (
col1 VARCHAR2(3),
col2 VARCHAR2(3));

INSERT INTO t VALUES ('a','a');
INSERT INTO t VALUES ('a','b');
INSERT INTO t VALUES ('b','a');
INSERT INTO t VALUES ('b','b');
INSERT INTO t VALUES ('a',NULL);

SELECT * FROM t;

SELECT sys_op_distinct(col1, col2)
FROM t;

Overload 3 		SYS_OP_DISTINCT(col1 IN DATE, col2 IN DATE);
CREATE TABLE t (
col1 DATE,
col2 DATE);

INSERT INTO t VALUES (SYSDATE,SYSDATE);
INSERT INTO t VALUES (SYSDATE,SYSDATE+1);
INSERT INTO t VALUES (SYSDATE+1,SYSDATE);
INSERT INTO t VALUES (SYSDATE+1,SYSDATE+1);
INSERT INTO t VALUES (SYSDATE,NULL);
COMMIT;

SELECT sys_op_distinct(col1, col2)
FROM t;
SYS_OP_DUMP
Undocumented | SYS_OP_DUMP(<arg> IN UDT)
SELECT sys_op_dump(1) FROM dual;
                    *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected UDT got NUMBER
SYS_OP_GROUPING
Undocumented
Introduced in 9i 		SYS_OP_GROUPING(
SELECT sys_op_grouping(1,1,1,1) FROM dual;
ERROR:
ORA-00932: inconsistent datatypes: expected CHAR got B4

no rows selected
SYS_OP_GUID
Undocumented | SYS_OP_GUID()
SELECT sys_guid()
FROM dual;

SELECT sys_op_guid()
FROM dual;
SYS_OP_IIX

Undocumented
Introduced in 9.2 		SYS_OP_IIX(<arg1>, <arg2>)
SELECT sys_op_iix(1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments

SELECT sys_op_iix('A',1) FROM dual;
                   *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected UDT got CHAR
SYS_OP_ITR

Undocumented
Introduced in 10.1 		sys_op_itr(... unknown data type ...)
SELECT sys_op_itr(1) FROM dual;
                   *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got NUMBER
SYS_OP_LBID

Leaf Block ID Scanning 		/*
 Has many functional variations, but the point is to scan through index leaf blocks and calculate a measure of the quality of the index. The way it is counted, and the thing being counted, depends on the type of index (viz: bitmap, simple b-tree, local/global index, IOT, or secondary on IOT, cluster).
*/

SYS_OP_LBID(<object_id>, <block_type>, <table_name.rowid>);
CREATE INDEX ix_serv_inst
ON serv_inst(srvr_id);

SELECT object_id
FROM user_objects
WHERE object_name = 'IX_SERV_INST';

SELECT rows_per_block, count(*) blocks
FROM (
  SELECT /*+ cursor_sharing_exact
             dynamic_sampling(0)
             no_monitoring
             no_expand
             index_ffs(serv_inst,ix_serv_inst)
             noparallel_index(serv_inst,ix_serv_inst)
         */
    sys_op_lbid(69854, 'L', serv_inst.rowid) block_id,
    COUNT(*) rows_per_block
  FROM serv_inst -- t1 sample block (100)
  WHERE srvr_id IS NOT NULL
  GROUP BY sys_op_lbid(69854, 'L', serv_inst.rowid))
GROUP BY rows_per_block;
SYS_OP_LVL

Undocumented but Introduced 9.2 		sys_op_lvl(<arg1>, ...)
SELECT '-' || sys_op_lvl(5) || '-' FROM dual;

SELECT sys_op_lvl(1, 1, 2) FROM dual;

SELECT sys_op_lvl(1, 1, 2, 3, 4, 5, 7) FROM dual;
SYS_OP_MAKEOID

Undocumented 		sys_op_makeoid(<arg1>, <arg2>, <arg3>)
CREATE OR REPLACE TYPE o_type AS OBJECT (n NUMBER, v VARCHAR2(20));
/

CREATE OR REPLACE TYPE t_type AS TABLE OF o_type;
/

CREATE OR REPLACE TYPE m_type AS OBJECT (id NUMBER, t o_type);
/

CREATE TABLE som_demo (
n  NUMBER,
v  VARCHAR2(20),
id NUMBER);

CREATE VIEW v_som_demo OF m_type WITH OBJECT identifier(id) AS
SELECT id, o_type(n, v)
FROM som_demo;

INSERT INTO som_demo VALUES (1,'one',1);

SELECT sys_op_makeoid(v_som_demo, id)
FROM v_som_demo;
SYS_OP_MAP_NONNULL

Returns hex from row for comparison

First introduce in 8i 		sys_op_map_nonnull(value IN VARCHAR2) RETURN VARCHAR2
sys_op_map_nonnull(value IN NUMBER) RETURN VARCHAR2
sys_op_map_nonnull(value IN DATE) RETURN VARCHAR2
sys_op_map_nonnull(value IN TIMESTAMP) RETURN VARCHAR2
-- likely will handle any SQL data type
conn scott/tiger

set linesize 121

SELECT * FROM emp;

SELECT comm, sys_op_map_nonnull(comm)
FROM emp;

conn uwclass/uwclass

CREATE TABLE t (
col1  VARCHAR2(20),
col2  VARCHAR2(20),
col3  VARCHAR2(20));

INSERT INTO t VALUES ('ABC', 'ABC', NULL);
INSERT INTO t VALUES ('ABC', 'ABc', NULL);
INSERT INTO t VALUES ('123', NULL, 'ABC');
INSERT INTO t VALUES ('TRUE', 'FALSE', NULL);
INSERT INTO t VALUES (NULL, NULL, 'ABC');
COMMIT;

SELECT *
FROM t
WHERE sys_op_map_nonnull(col1) = sys_op_map_nonnull(col2);
SYS_OP_NII

Undocumented 		sys_op_nii(<arg1>, <arg2>);
SELECT sys_op_nii(1) FROM dual;
       *
ERROR at line 1:
ORA-00909: invalid number of arguments

SELECT sys_op_nii('A',2) FROM dual;
                   *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got NUMBER
SYS_OP_NOEXPAND

Undocumented 		sys_op_noexpand(<arg1>, <arg2>);
SELECT sys_op_noexpand('A') FROM dual;

SELECT sys_op_noexpand(srvr_id) FROM servers;
SYS_OP_OIDVALUE
Undocumented

May related to object views 		sys_op_oidvalue(<... unknown data type ...> ...
SELECT sys_op_oidvalue('TAB$', 1) FROM dual;
                       *
ERROR at line 1:
ORA-00903: invalid table name
SYS_OP_PAR

Undocumented but relates to the OLAP API
Introduced 9.2 		sys_op_par(<agr1>, <arg2>, <arg3>)
CREATE TABLE t (
x NUMBER(10),
y NUMBER(10));

INSERT INTO t
SELECT object_id, data_object_id
FROM all_objs;
COMMIT;

SELECT xx, yy, TO_CHAR(sys_op_par(0, GROUPING_ID(xx, yy), xx, yy))
FROM (
  SELECT t1.x xx, t2.x yy
  FROM t t1, t t2
  WHERE t1.x =t2.y)
GROUP BY xx, ROLLUP(yy)
HAVING GROUPING_ID(xx,yy) =1;
SYS_OP_PARGID

Undocumented but Introduced 9.2 		sys_op_pargid(<agr1>, <arg2>)
SELECT sys_op_pargid(1, 99) FROM dual;

SELECT sys_op_pargid(1, 4, 1, 1) FROM dual;

SELECT sys_op_pargid(1, 4, 2, 1, 99, 99, 99, 99, 99) FROM dual;
SYS_OP_RAWTONUM

Undocumented 		sys_op_rawtonum(<expression> IN VARCHAR2) RETURN INTEGER
SELECT sys_op_rawtonum('0A')
FROM dual;

SELECT sys_op_rawtonum('FF')
FROM dual;
SYS_OP_RPB

Returns the row number in the block given a rowid 		SYS_OP_RPB(rowid IN ROWID) RETURN INTEGER
SELECT rowid, srvr_id
FROM servers
WHERE rownum < 11;

SELECT rowid, sys_op_rpb(rowid), srvr_id
FROM servers
WHERE rownum < 11;

SELECT MAX(sys_op_rpb(rowid))
from servers;
SYS_OP_R2O

Undocumented 		SYS_OP_R2O(<arg> IN REF)
conn oe/oe

SELECT sys_op_r2o(CUSTOMER_REF)
FROM oc_orders
WHERE rownum = 1;
SYS_OP_TOSETID

Undocumented 		sys_op_tosetid(<nested_table_column_name>) RETURN VARCHAR2
CREATE OR REPLACE TYPE o_type AS OBJECT (n number, v VARCHAR2(20));
/

CREATE OR REPLACE TYPE t_type AS TABLE OF o_type;
/

CREATE TABLE t (
rid  NUMBER(5),
col  t_type)
NESTED TABLE col STORE AS nested_tab;

desc t

set describe depth all

 INSERT INTO t
(rid, col)
VALUES
(100, t_type(o_type(1, 'Daniel Morgan'), o_type(2, 'Jack Cline')));

SELECT rid, col
FROM t;

SELECT sys_op_tosetid(col)
FROM t;
SYS_OP_TRTB
Undocumented
Introduced in 8i

Reportedly related to trimming and padding strings 		sys_op_trtb(<arg> IN VARCHAR2, <arg> IN INTEGER) RETURN VARCHAR2
SELECT sys_op_trtb('A', 2) FROM dual;

SELECT LENGTH(sys_op_trtb('A', 2)) FROM dual;

SELECT '-' || sys_op_trtb('A', 3) || '-' FROM dual;

SELECT LENGTH(sys_op_trtb('A', 3)) FROM dual;
SYS_OP_UNDESCEND
Undocumented
Introduced in 10.1 		SYS_OP_UNDESCEND(unknown BINARY)
SELECT sys_op_undescend('10')
FROM dual;

SELECT sys_op_undescend('00')
FROM dual;
SYS_OP_VECAND
Undocumented but likely based on Vector and XAND SYS_OP_VECAND(<expression> IN VARCHAR2, <expression> IN VARCHAR2)
RETURN VARCHAR2
SELECT sys_op_vecand('ff','10')
FROM dual;
SYS_OP_VECBIT
Undocumented SYS_OP_VECAND(<expression> IN VARCHAR2, <expression> IN NUMBER)
RETURN BINARY_INTEGER
SELECT sys_op_vecbit('3',0), sys_op_vecbit('3',1), sys_op_vecbit('3',2)
FROM dual;
SYS_OP_VECOR
Undocumented but likely based on Vector and OR SYS_OP_VECOR(<expression> IN VARCHAR2, <expression> IN VARCHAR2)
RETURN VARCHAR2
SELECT sys_op_vecor('ff','10')
FROM dual;
SYS_OP_VECXOR
Undocumented but likely based on Vector and XOR SYS_OP_VECXOR(<expression> IN VARCHAR2, <expression> IN VARCHAR2)
RETURN VARCHAR2
SELECT sys_op_vecxor('ff','10')
FROM dual;
SYS_OP_XPTHATG
Undocumented
Introduced in 10.1 		SYS_OP_XPTHATG(
SELECT sys_op_xpthatg(1) FROM dual;
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got -
SYS_OP_XPTHIDX
Undocumented
Introduced in 10.1 		SYS_OP_XPTHIDX(
SELECT sys_op_xpthidx(1) FROM dual;
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got -
SYS_OP_XPTHOP
Undocumented
Introduced in 10.1 		SYS_OP_XPTHOP(
SELECT sys_op_xpthop(1) FROM dual;
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got -
SYS_OP_XTXT2SQLT

Undocumented
Introduced in 10.1 		SYS_OP_XTXT2SQLT(?)
SELECT sys_op_xtxt2sqlt(1) FROM dual;
       *
ERROR at line 1:
ORA-00938: not enough arguments for function

SELECT sys_op_xtxt2sqlt(1,2) FROM dual
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected - got -
SYS_OP_VVD
Undocumented
Introduced in 9i 		SYS_OP_VVD(
SELECT sys_op_vvd('T_TYPE',1) FROM dual;
       *
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected UDT got CHAR
SYS_XMLCONTAINS

Undocumented
Introduced in 10.1 		SYS_XMLCONTAINS(<arg1>, <arg2>)
SELECT sys_xmlcontains(1) FROM dual;
       *
ERROR at line 1:
ORA-00938: not enough arguments for function

SELECT sys_xmlcontains(1,2) FROM dual;
SYS_XMLCONV
Undocumented
Introduced in 9i 		SYS_XMLCONV(<arg1>, <arg2>, <arg3>, <arg4>, <arg5>, <arg6>, <arg7>, <arg8>)
3 - filter("SYS_NC_TYPEID$" IS NOT NULL AND
CAST(sys_xmlconv("SYS_NTrm0uwhm2Suu6WBsZ4N+t8w=="."SYS_NC00007$", 1, 259, 10333, '4C784CAE38274EF9A15A0334F643A6B5',0,0,1) AS VARCHAR2(3))='010')
Related Topics
Functions
Indexes
SKIP LOCKED
System Events


Oracle Globalization Toolkit UTL_GDK

Oracle UTL_GDK
Version 10.2
General Information
Note: GDK stands for Globalization Developer's Kit. GDK is a set of services that can help monolingual application developer to create similar multilingual applications with minimual knowledge about internationalization issues. GDK includes two major components, internet globalization services and Oracle globalization services. GDK includes two major components, internet globalization services and Oracle globalization services. Internet global services can hide the complexity of globalization to support multi-user with different locale. Oracle globalization services provide developer a set of consistent, high performance and easy to use tools in middle-tier as database client.
Source | {ORACLE_HOME}/rdbms/admin/utlgdk.sql
First Availability | 9.2
Constants ORACLE_TO_IANA   CONSTANT PLS_INTEGER := 1;
IANA_TO_ORACLE   CONSTANT PLS_INTEGER := 2;
ORACLE_TO_ISO    CONSTANT PLS_INTEGER := 3;
ISO_TO_ORACLE    CONSTANT PLS_INTEGER := 4;
ORACLE_TO_ISO_A3 CONSTANT PLS_INTEGER := 5;
ISO_A3_TO_ORACLE CONSTANT PLS_INTEGER := 6;
Dependencies
DBMS_XDBT UTL_GDK_LIB
Globalization Codes
Language | Abbreviation
AMERICAN | US
ARABIC | AR
BENGALI | BN
BRAZILIAN PORTUGESE | PTB
BULGARIAN | BG
CANADIAN FRENCH | FRC
CATALAN | CA
CROATIAN | HR
CZECH | CS
DANISH | DK
DUTCH | NL
EGYPTIAN | EG
ENGLISH | GB
ESTONIAN | ET
FINISH | SF
GERMAN | DE
HEBREW | HR
HUNGARIAN | HU
ISLANDIC | IS
POLISH | PL
SLOVAK | SK
THAI | TH
TURKISH | TR
UKRANIAN | UK
VIETNAMESE | VN
Charset_Map
Charset Map Function utl_gdk.charset_map(
charset IN VARCHAR2,
flag    IN BINARY_INTEGER)
RETURN VARCHAR2
SELECT utl_gdk.charset_map('WE8ISO8859P1', 1)
FROM dual;

SELECT utl_gdk.charset_map('ISO-8859-1', 2)
FROM dual;
Language_Map
LanguageMap Function utl_gdk.language_map(
language IN VARCHAR2,
flag     IN BINARY_INTEGER)
RETURN VARCHAR2
SELECT utl_gdk.language_map('English', 3) FROM dual;
SELECT utl_gdk.language_map('en', 4) FROM dual;

SELECT utl_gdk.language_map('French', 3) FROM dual;
SELECT utl_gdk.language_map('fr', 4) FROM dual;

SELECT utl_gdk.language_map('German', 3) FROM dual;
SELECT utl_gdk.language_map('de', 4) FROM dual;

SELECT utl_gdk.language_map('Japanese', 3) FROM dual;
SELECT utl_gdk.language_map('ja', 4) FROM dual;

SELECT utl_gdk.language_map('Arabic') FROM dual;
SELECT utl_gdk.language_map('Finnish') FROM dual;
SELECT utl_gdk.language_map('Korean') FROM dual;
SELECT utl_gdk.language_map('Russian') FROM dual;
SELECT utl_gdk.language_map('Slovak') FROM dual;
SELECT utl_gdk.language_map('Spanish') FROM dual;
SELECT utl_gdk.language_map('Thai') FROM dual;
Territory_Map
Territory Map Function utl_gdk.territory_map (
territory IN VARCHAR2,
flag      IN BINARY_INTEGER)
RETURN VARCHAR2
SELECT utl_gdk.territory_map('AMERICA', 3) FROM dual;
SELECT utl_gdk.territory_map('US', 4) FROM dual;
SELECT utl_gdk.territory_map('AMERICA', 5) FROM dual;
SELECT utl_gdk.territory_map('USA', 6) FROM dual;

SELECT utl_gdk.territory_map('SPAIN', 3) FROM dual;
SELECT utl_gdk.territory_map('ES', 4) FROM dual;
SELECT utl_gdk.territory_map('SPAIN', 5) FROM dual;
SELECT utl_gdk.territory_map('ESP', 6) FROM dual;

SELECT utl_gdk.territory_map('GERMANY', 3) FROM dual;
SELECT utl_gdk.territory_map('DE', 4) FROM dual;
Character Set Related Queries
Character Sets set serveroutput on

BEGIN
  FOR i IN 1..401
  LOOP
    dbms_output.put_line(TO_CHAR(i) || ' ' || nls_charset_name(i));
  END LOOP;
END;
/
Database Installed Language SELECT name, value
FROM gv$parameter
WHERE name LIKE '%nls%';

col parameter format a40
col value format a40
set linesize 120

SELECT *
FROM gv_$nls_parameters;

SELECT *
FROM nls_database_parameters
WHERE parameter ='NLS_CHARACTERSET';
Related Topics
Character Sets
Character Set Functions


Oracle DBMS_I18N Globalization

Oracle DBMS_I18N
General Information
Note | Internationalization is often abbreviated as I18N (or i18n or I18n) where the number 18 refers to the number of letters omitted.
Source | {ORACLE_HOME}/rdbms/admin/utli18n.sql
Constants
Name | Description | Data Type | Value
SHIFT_IN | Used with shift_status. Must be set the first time it is called in piecewise conversion. | PLS_INTEGER | 0
SHIFT_OUT |  | PLS_INTEGER | 1
Defined Data Type TYPE string_array IS TABLE of VARCHAR2(32767)
INDEX BY BINARY_INTEGER;
Dependencies
DECRYPT | ENCRYPT_STRING | UTL_I18_LIB | V$NLS_VALID_VALUES
ENCRYPT | GET_ENC_VAL | UTL_RAW |
Encode SQL-XML Function Constants
Name | Data Type | Value
XMLTAG_TO_SQLNAME | PLS_INTEGER | 0
SQLNAME_TO_XMLTAG | PLS_INTEGER | 1
Exceptions
Error Code | Reason
01722 | invalid number: escaping format is invalid
03001 | Unsupported Transliteration
27102 | out of memory
Locale-Mapping Flags
Name | Description | Data Type | Value
GENERIC_CONTEXT | Returns the default character set for general cases. | PLS_INTEGER | 0
IANA_TO_ORACLE | Map from an IANA character set name to an Oracle character set name. | PLS_INTEGER | 1
MAIL_CONTEXT | The mapping is between an Oracle character set name and an email safe character set name. | PLS_INTEGER | 1
MAIL_GENERIC | Map from an Oracle character set name to an email safe character set name on a non-Windows platform. | PLS_INTEGER | 0
MAIL_WINDOWS | Map from an Oracle character set name to an email safe character set name on a Windows platform. | PLS_INTEGER | 1
ORACLE_TO_IANA | Map from an Oracle character set name to an IANA character set name. | PLS_INTEGER | 0
Translation Flags
Name | Data Type | Value
LANGUAGE_TRANS | PLS_INTEGER | 0
TERRITORY_TRANS | PLS_INTEGER | 1
LANGUAGE_TERRITORY_TRANS | PLS_INTEGER | 2
Transliteration Constants
Name | Data Type | Value
KANA_FWKATAKANA | VARCHAR2(30) | 'kana_fwkatakana'
KANA_HWKATAKANA | VARCHAR2(30) | 'kana_hwkatakana'
KANA_HIRAGANA | VARCHAR2(30) | 'kana_hiragana'
FWKATAKANA_HWKATAKANA | VARCHAR2(30) | 'fwkatakana_hwkatakana'
FWKATAKANA_HIRAGANA | VARCHAR2(30) | 'fwkatakana_hiragana'
HWKATAKANA_FWKATAKANA | VARCHAR2(30) | 'hwkatakana_fwkatakana'
HWKATAKANA_HIRAGANA | VARCHAR2(30) | 'hwkatakana_hiragana'
HIRAGANA_FWKATAKANA | VARCHAR2(30) | hiragana_fwkatakana'
HIRAGANA_HWKATAKANA | VARCHAR2(30) | 'hiragana_hwkatakana'
Object Privileges | grant execute on utl_18n to <schema_name>;
grant execute on utl_18n to uwclass;
ENCODE_SQL_XML
Converts between XML name and a SQL identifier utl_i18n.encode_sql_xml(
name IN VARCHAR2 CHARACTER SET ANY_CS,
flag IN PLS_INTEGER default XMLTAG_TO_SQLNAME)
RETURN VARCHAR2 CHARACTER SET name%CHARSET;
SELECT utl_i18n.encode_sql_xml('_xFFFF_',1)
FROM dual;

SELECT utl_i18n.encode_sql_xml('_xHHHHHHHH_',1)
FROM dual;
ESCAPE_REFERENCE
Converts a given text string to its character reference counterparts, for characters that fall outside the document character set utl_i18n.escape_reference(
str          IN VARCHAR2 CHARACTER SET ANY_CS,
page_cs_name IN VARCHAR2 DEFAULT NULL)
RETURN VARCHAR2 CHARACTER SET str%CHARSET;
SELECT utl_i18n.escape_reference('UW' || CHR(150),'US7ASCII')
FROM dual;
GET_COMMON_TIME_ZONES

Returns the list of common time zone IDs that are independent of the locales 		utl_i18n.get_common_time_zones RETURN string_array;
set serveroutput on

DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_common_time_zones;
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST-retval.FIRST+1);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/
GET_DEFAULT_CHARSET
Returns the default Oracle character set name or the default e-mail safe character set name from an Oracle language name utl_i18n.get_default_charset(
language  IN VARCHAR2,
context   IN PLS_INTEGER DEFAULT GENERIC_CONTEXT,
iswindows IN BOOLEAN DEFAULT FALSE)
RETURN VARCHAR2;
SELECT utl_i18n.get_default_charset('English', 0)
FROM dual;

SELECT utl_i18n.get_default_charset('Japanese', 0)
FROM dual;
GET_DEFAULT_ISO_CURRENCY
Returns the default ISO 4217 currency code for the specified territory utl_i18n.get_default_iso_currency(territory IN VARCHAR2 )
RETURN VARCHAR2;
SELECT utl_i18n.get_default_iso_currency('America')
FROM dual;

SELECT utl_i18n.get_default_iso_currency('Japan')
FROM dual;
GET_DEFAULT_LINGUISTIC_SORT
Returns the default linguistic sort name for the specified language utl_i18n.get_default_linguistic_sort(language IN VARCHAR2)
RETURN VARCHAR2;
SELECT utl_i18n.get_default_linguistic_sort('German')
FROM dual;
GET_LOCAL_LANGUAGES

Returns the local language names for the specified territory 		utl_i18n.get_local_languages(language IN VARCHAR2)
RETURN string_array;
set serveroutput on

DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_local_languages('SWITZERLAND');
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/
GET_LOCAL_LINGUISTIC_SORTS

Returns the local linguistic sort names for the specified language

Thank you Michel Cadot for multiple corrections on this page. 		utl_i18n.get_local_linguistic_sorts(language IN VARCHAR2)
RETURN string_array;
DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_local_linguistic_sorts('American');
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST-retval.FIRST+1);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/

DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_local_linguistic_sorts('Japanese');
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST-retval.FIRST+1);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/
GET_LOCAL_TERRITORIES

Returns the local territory names for the specified language 		utl_i18n.get_local_territories(
language IN VARCHAR2 CHARACTER SET ANY_CS)
RETURN string_array;
set serveroutput on

DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_local_territories('ENGLISH');
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST-retval.FIRST+1);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/
GET_LOCAL_TIME_ZONES

Returns the local time zone IDs for the specified territory 		utl_i18n.get_local_time_zones(territory IN VARCHAR2)
RETURN string_array;
set serveroutput on

DECLARE
 retval utl_i18n.string_array;
 cnt    PLS_INTEGER;
BEGIN
  retval := utl_i18n.get_local_time_zones('AMERICA');
  dbms_output.put('Count = ');
  dbms_output.put_line(retval.LAST-retval.FIRST+1);
  cnt := retval.FIRST;

  WHILE cnt IS NOT NULL LOOP
    dbms_output.put_line(retval(cnt));
    cnt := retval.NEXT(cnt);
  END LOOP;
END;
/
GET_TRANSLATION

Returns the translation of the language and territory name in the specified translation language 		utl_i18n.get_translation(
param1         IN VARCHAR2 CHARACTER SET ANY_CS,
trans_language IN VARCHAR2 DEFAULT 'AMERICAN',
flag           IN PLS_INTEGER DEFAULT LANGUAGE_TRANS)
RETURN VARCHAR2 CHARACTER SET param1%CHARSET;
set linesize 121
col parameter format a20
col value format a20

SELECT * FROM gv$nls_valid_values;

SELECT utl_i18n.get_translation('AMERICAN', 'ITALIAN')
FROM dual;

SELECT utl_i18n.get_translation('AMERICAN', 'SPANISH')
FROM dual;

SELECT utl_i18n.get_translation('AMERICAN', 'GERMAN')
FROM dual;

SELECT utl_i18n.get_translation('AMERICAN', 'SWEDISH')
FROM dual;

SELECT utl_i18n.get_translation('AMERICAN', 'DANISH')
FROM dual;
MAP_CHARSET
Maps an Oracle character set name to an IANA character set name

Maps an IANA character set name to an Oracle character set name

Maps an Oracle character set to an e-mail safe character set name 		utl_i18n.map_charset(
charset IN VARCHAR2,
context IN PLS_INTEGER DEFAULT GENERIC_CONTEXT,
flag    IN PLS_INTEGER DEFAULT ORACLE_TO_IANA)
RETURN VARCHAR2;
SELECT utl_i18n.map_charset('iso-8859-1', 0, 1)
FROM dual;

SELECT utl_i18n.map_charset('iso-8859-1', 1, 0)
FROM dual;
MAP_FROM_SHORT_LANGUAGE
Maps an Oracle short language name to its full language name utl_i18n.map_territory_from_short_language(language IN VARCHAR2)
RETURN VARCHAR2;
SELECT utl_i18n.map_from_short_language('GB')
FROM dual;
MAP_LANGUAGE_FROM_ISO
Returns an Oracle language name from an ISO locale name | utl_i18n.map_language_from_iso(isolocale IN VARCHAR2) RETURN VARCHAR2;
SELECT utl_i18n.map_language_from_iso('en_US')
FROM dual;
MAP_LOCALE_TO_ISO
Returns an ISO locale name from an Oracle language name and an Oracle territory name utl_i18n.map_locale_to_iso(
ora_language  IN VARCHAR2,
ora_territory IN VARCHAR2)
RETURN VARCHAR2;
SELECT utl_i18n.map_locale_to_iso('American', 'America')
FROM dual;
MAP_TERRITORY_FROM_ISO
Returns an Oracle territory name from an ISO locale | utl_i18n.map_territory_from_iso(isolocale IN VARCHAR2) RETURN VARCHAR2;
SELECT utl_i18n.map_territory_from_iso('en_US')
FROM dual;
MAP_TO_SHORT_LANGUAGE
Maps an Oracle full language name to short language name utl_i18n.map_territory_to_short_language(language IN VARCHAR2)
RETURN VARCHAR2;
SELECT utl_i18n.map_to_short_language('ENGLISH')
FROM dual;
RAW_TO_CHAR
Convert RAW to a string of type CHAR

Overload 1 		utl_i18n.raw_to_char(
data        IN RAW,
src_charset IN VARCHAR2 DEFAULT NULL)
RETURN VARCHAR2;
SELECT utl_i18n.raw_to_char('44616E204D6F7267616E','AL32UTF8')
FROM dual;
Overload 2 utl_i18n.raw_to_char(data IN RAW,
src_charset     IN     VARCHAR2 DEFAULT NULL,
scanned_length     OUT PLS_INTEGER,
shift_status    IN OUT PLS_INTEGER)
RETURN VARCHAR2;
TBD
RAW_TO_NCHAR
Convert RAW to a string of type NCHAR

Overload 1 		utl_i18n.raw_to_nchar(
data        IN RAW,
src_charset IN VARCHAR2 DEFAULT NULL)
RETURN NVARCHAR2;
SELECT utl_i18n.raw_to_nchar('44616E204D6F7267616E','AL32UTF8')
FROM dual;
Overload 2 utl_i18n.raw_to_nchar(
data           IN     RAW,
src_charset    IN     VARCHAR2 DEFAULT NULL,
scanned_length    OUT PLS_INTEGER,
shift_status   IN OUT PLS_INTEGER)
RETURN NVARCHAR2;
TBD
STRING_TO_RAW
Convert a string to RAW utl_i18n.string_to_raw(
data        IN VARCHAR2 CHARACTER SET ANY_CS,
dst_charset IN VARCHAR2 DEFAULT NULL)
RETURN RAW;
SELECT utl_i18n.string_to_raw('Dan Morgan','AL32UTF8')
FROM dual;
TRANSLITERATE

Transliterates between Japanese hiragana and katakana 		utl_i18n.transliterate (
data IN VARCHAR2 CHARACTER SET ANY_CS,
name IN VARCHAR2)
RETURN VARCHAR2 CHARACTER SET data%CHARSET;
set serveroutput on

DECLARE
 name japanese_emp.ename%TYPE;
 eno  CONSTANT NUMBER(4) := 1;
BEGIN
  SELECT ename
  INTO name
  FROM japanese_emp
  WHERE enumber = eno;

  name := utl_i18n.transliterate(name, utl_i18n.kana_hiragana);

  dbms_output.put_line(name);
EXCEPTION
  WHEN utl_i18n.unsupported_transliteration THEN
    dbms_output.put_line('transliteration not supported');
END;
/
UNESCAPE_REFERENCE
Converts an input string that contains character references to a text string utl_i18n.unescape_reference(str IN VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET str%CHARSET;
SELECT utl_i18n.unescape_reference('UW&#x2013;')
FROM dual;
VALIDATE_SQLNAME

Validates an oracle object name 		utl_i18n.validate_sqlname(name VARCHAR2 CHARACTER SET ANY_CS)
RETURN PLS_INTEGER;
set define off

SELECT utl_i18n.validate_sqlname('&')
FROM dual;
Related Topics
DBMS_CRYPTO


Oracle UTL_RAW
General Information
Source | {ORACLE_HOME}/rdbms/admin/utlraw.sql
First Available | 7.3.4
Constants
Name | Data Type | Value
big_endian | PLS_INTEGER | 1
little_endian | PLS_INTEGER | 2
machine_endian | PLS_INTEGER | 3
Dependencies 179 objects

SELECT name FROM dba_dependencies
WHERE referenced_name = 'UTL_RAW'
UNION
SELECT referenced_name FROM dba_dependencies
WHERE name = 'UTL_RAW';
Exceptions
Error # | Name | Description
VALUE_ERROR | ORA-6502 | An arithmetic, conversion, truncation, or size-constraint error. Usually raised by trying to cram a 6 character string into a VARCHAR2(5).
Required Object Privileges | GRANT execute on UTL_RAW
GRANT execute ON utl_raw TO UWCLASS;
BIT_AND
Perform bitwise logical "and" of the values in raw r1 with raw r2 and return the "anded" result raw | utl_raw.bit_and(r1 IN RAW, r2 IN RAW) RETURN RAW;
SELECT utl_raw.bit_and('0102F3', 'F30201')
FROM dual;
BIT_COMPLEMENT
Perform bitwise logical "complement" of the values in raw and return the "complement'ed" result raw | utl_raw.bit_complement(r IN RAW) RETURN RAW;
SELECT utl_raw.bit_complement('0102F3')
FROM dual;
BIT_OR
Perform bitwise logical "or" of the values in raw r1 with raw r2 and return the "or'd" result raw | utl_raw.bit_or(r1 IN RAW, r2 IN RAW) RETURN RAW;
SELECT utl_raw.bit_or('0102F3', 'F30201')
FROM dual;
BIT_XOR
Perform bitwise logical "exclusive or" of the values in raw r1 with raw r2 and return the "xor'd" result raw | utl_raw.bit_xor(r1 IN RAW, r2 IN RAW) RETURN RAW;
SELECT utl_raw.bit_xor('0102F3', 'F30201')
FROM dual;
CAST_FROM_BINARY_DOUBLE
Return the RAW representation of a binary_double value utl_raw.cast_from_binary_double(n IN BINARY_DOUBLE,
endianess IN PLS_INTEGER DEFAULT 1) RETURN RAW;
SELECT utl_raw.cast_from_binary_double(123.45)
FROM dual;
CAST_FROM_BINARY_FLOAT
Return the RAW representation of a binary_float value utl_raw.cast_from_binary_float(n IN BINARY_FLOAT,
endianess IN PLS_INTEGER DEFAULT 1) RETURN RAW;
SELECT utl_raw.cast_from_binary_float(123.45)
FROM dual;
CAST_FROM_BINARY_INTEGER
Return the RAW representation of a binary_integer value utl_raw.cast_from_binary_integer(
n         IN BINARY_INTEGER,
endianess IN PLS_INTEGER DEFAULT 1) RETURN RAW;
SELECT utl_raw.cast_from_binary_integer(100)
FROM dual;
CAST_FROM_NUMBER
Returns the binary representation of a NUMBER in RAW | utl_raw.cast_from_number(n IN NUMBER) RETURN RAW;
SELECT utl_raw.cast_from_number(100)
FROM dual;
CAST_TO_BINARY_DOUBLE
Perform a casting of the binary representation of the raw into a binary_double. cast_to_binary_double(
r         IN RAW,
endianess IN PLS_INTEGER DEFAULT 1) RETURN BINARY_DOUBLE;
SELECT utl_raw.cast_to_binary_double('405EDCCCCCCCCCCD')
FROM dual;
CAST_TO_BINARY_FLOAT
Perform a casting of the binary representation of the raw into a binary_float utl_raw.cast_to_binary_float(
n         IN BINARY_FLOAT,
endianess IN PLS_INTEGER DEFAULT 1) RETURN RAW;
SELECT utl_raw.cast_to_binary_float('42F6E666')
FROM dual;
CAST_TO_BINARY_INTEGER
Perform a casting of the binary representation of the raw into a binary integer utl_raw.cast_to_binary_integer(
r         IN RAW,
endianess IN PLS_INTEGER DEFAULT 1) RETURN BINARY_INTEGER;
SELECT utl_raw.cast_to_binary_integer('00000064')
FROM dual;
CAST_TO_NUMBER
Perform a casting of the binary representation of the number (in RAW) into a NUMBER | utl_raw.cast_to_number(r IN RAW) RETURN NUMBER;
SELECT utl_raw.cast_to_number('C202')
FROM dual;
CAST_TO_NVARCHAR2

Converts a RAW represented using n data bytes into NVARCHAR2 with n data bytes 		utl_raw.cast_to_nvarchar2(r IN RAW) RETURN NVARCHAR2;
set serveroutput on

BEGIN
  FOR i IN 100..200 LOOP
    dbms_output.put_line(
    utl_raw.cast_to_nvarchar2(TO_CHAR(i)));
  END LOOP;
END;
/
CAST_TO_RAW
Converts a VARCHAR2 represented using n data bytes into a RAW with n data bytes | utl_raw.cast_to_raw(r IN RAW) RETURN RAW;
SELECT utl_raw.cast_to_raw('ABC')
FROM dual;
CAST_TO_VARCHAR2
To extract a substring from a BLOB using a PL/SQL program use dbms_lob.substr(). The problem is that it returns a string in hexadecimal characters. CAST_TO_VARCHAR2 turns the hexadecimal string into readable ascii format. | utl_raw.cast_to_nvarchar2(r IN RAW) RETURN VARCHAR2;
set serveroutput on

BEGIN
  FOR i IN 100..200 LOOP
    dbms_output.put_line(utl_raw.cast_to_varchar2(TO_CHAR(i)));
  END LOOP;
END;
/
COMPARE
Compares raw r1 against raw r2. Returns 0 if r1 and r2 are identical, otherwise, returns the position of the first byte from r1 that does not match r2 utl_raw.compare(r1 IN RAW, r2 IN RAW,
pad IN RAW DEFAULT NULL) RETURN NUMBER;
SELECT utl_raw.compare(utl_raw.cast_to_raw('ABC'),
utl_raw.cast_to_raw('ACC'))
FROM dual;
CONCAT

Concatenate a set of 12 raws into a single raw (up to 32K) 		utl_raw.concat(r1 IN RAW DEFAULT NULL,
r2  IN RAW DEFAULT NULL,
r3  IN RAW DEFAULT NULL,
r4  IN RAW DEFAULT NULL,
r5  IN RAW DEFAULT NULL,
r6  IN RAW DEFAULT NULL,
r7  IN RAW DEFAULT NULL,
r8  IN RAW DEFAULT NULL,
r9  IN RAW DEFAULT NULL,
r10 IN RAW DEFAULT NULL,
r11 IN RAW DEFAULT NULL,
r12 IN RAW DEFAULT NULL) RETURN RAW;
SELECT utl_raw.concat('A','41','B','42')
FROM dual;
CONVERT

Convert raw from one character to a different character set and return the resulting raw 		utl_raw.convert(
r            IN RAW,
to_charset   IN VARCHAR2,
from_charset IN VARCHAR2) RETURN RAW;
DECLARE
 fr_charset CONSTANT VARCHAR2(30) :=
 SUBSTR(SYS_CONTEXT('USERENV', 'LANGUAGE'),
 INSTR(SYS_CONTEXT('USERENV', 'LANGUAGE'),'.')+1);

 to_charset VARCHAR2(30) := 'TR8EBCDIC1026S';
 rawvar     RAW(100);
BEGIN
  dbms_output.put_line(fr_charset);
  dbms_output.put_line(to_charset);

  rawvar := utl_raw.convert(UTL_RAW.CAST_TO_RAW('Morgan'),
  'AMERICAN_AMERICA.'||to_charset,
  'AMERICAN_AMERICA.'||fr_charset);

  dbms_output.put_line(rawvar);
END;
/
COPIES
Return n copies of r concatenated together | utl_raw.copies(r IN RAW, n IN NUMBER) RETURN RAW;
SELECT utl_raw.copies('A', 6)
FROM dual;
LENGTH
Return the length in bytes of a raw | utl_raw.length(r IN RAW) RETURN NUMBER;
SELECT utl_raw.length('ABC')
FROM dual;
OVERLAY
Overlay the specified portion of target raw with overlay raw, starting from byte position pos of target and proceeding for len bytes utl_raw.overlay(overlay_str IN RAW, target IN RAW,
pos IN BINARY_INTEGER DEFAULT 1,
len IN BINARY_INTEGER DEFAULT NULL,
pad IN RAW DEFAULT NULL) RETURN RAW;
SELECT utl_raw.overlay('1', 'AAABBBCCC', 4)
FROM dual;
REVERSE
Reverse a byte sequence in raw r from end to end | utl_raw.reverse(r IN RAW) RETURN RAW;
SELECT utl_raw.reverse('123')
FROM dual;
SUBSTR

Return a substring portion of raw r beginning at pos for len bytes 		utl_raw.substr(r IN RAW,
pos IN BINARY_INTEGER,
len IN BINARY_INTEGER DEFAULT NULL) RETURN RAW;
set serveroutput on

DECLARE
 tmp  VARCHAR2(250) := '';
 vraw RAW(200) := utl_raw.cast_to_raw('ABCDEABCDEABCDE');
BEGIN
  FOR i IN 1 .. 15 LOOP
    tmp := tmp|| '0x' || utl_raw.substr(vraw, i, 1) || ' ';
    dbms_output.put_line(tmp);
  END LOOP;
END;
/
TRANSLATE

Translate the bytes in the input r raw according to the bytes in the translation raws, from_set and to_set 		utl_raw.translate(r IN RAW, from_set IN RAW, to_set IN RAW)
RETURN RAW;
CREATE OR REPLACE FUNCTION trans_demo(pin IN VARCHAR2)
RETURN VARCHAR2 IS
 r_in  RAW(2000);
 r_out RAW(2000);
 r_ul  RAW(64);
 r_lu  RAW(64);
BEGIN
  r_in := utl_raw.cast_to_raw(pin);
  r_ul := utl_raw.cast_to_raw('ABCDEFabcdef');
  r_lu := utl_raw.cast_to_raw('abcdefABCDEF');

  r_out := utl_raw.translate(r_in , r_ul, r_lu);

  return(utl_raw.cast_to_varchar2(r_out));
END trans_demo;
/

SELECT trans_demo('FaDe') FROM dual;
SELECT trans_demo('FAde') FROM dual;
TRANSLITERATE

Transliterate the bytes in the input r raw according to the bytes in the transliteration raws, from_set and to_set 		utl_raw.transliterate(r IN RAW, to_set IN RAW DEFAULT NULL,
from_set IN RAW DEFAULT NULL, pad IN RAW DEFAULT NULL)
RETURN RAW;
CREATE OR REPLACE FUNCTION tl_demo(pin IN VARCHAR2)
RETURN VARCHAR2 IS
 r_in  RAW(2000);
 r_out RAW(2000);
 r_up  RAW(64);
 r_lo  RAW(64);
 r_un  RAW(64) := utl_raw.cast_to_raw('_');
BEGIN
  r_in := utl_raw.cast_to_raw(pin);
  r_up := utl_raw.cast_to_raw('ABCDEF. ');
  r_lo := utl_raw.cast_to_raw('abcdef');

  r_out := utl_raw.transliterate(r_in , r_lo, r_up, r_un);

  return(utl_raw.cast_to_varchar2(r_out));
END tl_demo;
/

SELECT tl_demo('AB C.D') FROM dual;
XRANGE

Returns a raw containing all valid 1-byte encodings in succession beginning with the value start_byte and ending with the value end_byte. 		utl_raw.xrange(start_byte IN RAW DEFAULT NULL,
end_byte IN RAW DEFAULT NULL) RETURN RAW;
SELECT utl_raw.xrange(utl_raw.cast_to_raw('A'),
utl_raw.cast_to_raw('Z'))
FROM dual;

SELECT utl_raw.xrange(utl_raw.cast_to_raw('0A'),
utl_raw.cast_to_raw('Z'))
FROM dual;
Related Topics
DBMS_LOB


Oracle Varrays Array Object Nested Table Type DataType

Oracle VARRAYS
Version 10.2
General Information
A varray is a variable length array object.
Related Data Dictionary Objects col$
tab$
dba_source | all_source | user_source
dba_types | all_types | user_types
dba_tables | all_tables | user_tables
dba_tab_cols | all_tab_cols | user_tab_cols
dba_nested_tables | all_nested_tables | user_nested_tables
System Privileges CREATE TYPE
CREATE ANY TYPE
DROP ANY TYPE
Define Object as a TYPE CREATE OR REPLACE TYPE Project AS OBJECT (
project_no NUMBER(2),
title      VARCHAR2(35),
cost       NUMBER(7,2));
/

desc project

SELECT type_name, typecode, instantiable
FROM user_types;
Define VARRAY of object type CREATE OR REPLACE TYPE ProjectList AS VARRAY(50) OF Project;
/

desc projectlist

SELECT type_name, typecode, instantiable
FROM user_types;
Create table based on VARRAY Create relational table department, which has a column of type ProjectList

CREATE TABLE department (
dept_id  NUMBER(2),
name     VARCHAR2(15),
budget   NUMBER(11,2),
projects ProjectList);

desc department

set describe depth all linenum on indent on

desc department
Inserting into the VARRAY containing table Each item in column projects is a varray that will store
the projects scheduled for a given department.

Now, you are ready to populate relational table department.
In the following example, notice how varray constructor
ProjectList() provides values for column projects:

INSERT INTO department
VALUES(30, 'Accounting', 1205700,
ProjectList (Project(1, 'Design New Expense Report', 3250),
Project(2, 'Outsource Payroll', 12350),
Project(3, 'Evaluate Merger Proposal', 2750),
Project(4, 'Audit Accounts Payable', 1425)));

INSERT INTO department
VALUES(50, 'Maintenance', 925300,
ProjectList (Project(1, 'Repair Leak in Roof', 2850),
Project(2, 'Install New Door Locks', 1700),
Project(3, 'Wash Front Windows', 975),
Project(4, 'Repair Faulty Wiring', 1350),
Project(5, 'Winterize Cooling System', 1125)));

INSERT INTO department
VALUES(60, 'Security', 750400,
ProjectList (Project(1, 'Issue New Employee Badges', 13500),
Project(2, 'Find Missing IC Chips', 2750),
Project(3, 'Upgrade Alarm System', 3350),
Project(4, 'Inspect Emergency Exits', 1900)));

SELECT * FROM department;
Delete Record with VARRAY In the final example, you delete the Accounting Department
and its project list from table department:

DELETE FROM department WHERE dept_id = 30;

SELECT * FROM department;
Related Topics
Collections
Nested Tables
REF Cursors
Types


Oracle XML Functions

Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
APPENDCHILDXML
Note: Run these demos top to bottom without using COMMIT or ROLLBACK.

Appends a user-supplied value onto the target XML as the child of the node indicated by an XPath expression 		APPENDCHILDXML(XMLType_Instance>, <XPath_string>,
<value_expression>, <namespace_string>)
conn oe/oe

UPDATE warehouses
SET warehouse_spec = APPENDCHILDXML(warehouse_spec,
'Warehouse/Building', XMLType('<Owner>Grandco</Owner>'))
WHERE EXTRACTVALUE(warehouse_spec, '/Warehouse/Building') = 'Rented';

col "Prop.Owner" format a30

SELECT warehouse_id, warehouse_name,
EXTRACTVALUE(warehouse_spec, '/Warehouse/Building/Owner') "Prop.Owner"
FROM warehouses
WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Building/Owner') = 1;
DELETEXML

Deletes the node or nodes matched by the XPath expression in the target XML 		DELETEXML(XMLType_Instance>, <XPath_string>, <namespace_string>)
-- must follow APPENDCHILDXML demo (above)

SELECT warehouse_id, warehouse_spec
FROM warehouses
WHERE warehouse_id IN (2,3);

UPDATE warehouses
SET warehouse_spec=DELETEXML(warehouse_spec,'/Warehouse/Building/Owner')
WHERE warehouse_id = 2;

col warehouse_spec format a60

SELECT warehouse_id, warehouse_spec
FROM warehouses
WHERE warehouse_id IN (2,3);
DEPTH
Returns the number of levels in the path specified by the UNDER_PATH condition with the same correlation variable | DEPTH(correlation_integer)
conn oe/oe

SELECT PATH(1), DEPTH(2)
FROM RESOURCE_VIEW
WHERE UNDER_PATH(res, '/sys/schemas/OE', 1)=1
AND UNDER_PATH(res, '/sys/schemas/OE', 2)=1;
EXISTSNODE
Determines whether traversal of an XML document using a specified path results in any nodes | EXISTSNODE(XMLType_Instance>, <XPath_string>, <namespace_string>)
conn oe/oe

SELECT warehouse_id, warehouse_name
FROM warehouses
WHERE EXISTSNODE(warehouse_spec, '/Warehouse/Docks') = 1;
EXTRACT
Applies a VARCHAR2 XPath string and returns an XMLType instance containing an XML fragment | EXTRACT(XMLType_Instance>, <XPath_string>, <namespace_string>)
conn oe/oe

col "Number of Docks" format a30

SELECT warehouse_name,
EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks"
FROM warehouses
WHERE warehouse_spec IS NOT NULL;

Demo using the capability in a non-XML environment 		rollback;

conn uwclass/uwclass

CREATE TABLE t(
line  NUMBER(3),
site  VARCHAR2(4),
phase VARCHAR2(5),
test  VARCHAR2(25));

INSERT INTO t VALUES (1, '0100', '*','1111111111111111111111111' );
INSERT INTO t VALUES (2, '0100', '=','2222222222222222222222222' );
INSERT INTO t VALUES (3, '0100', '=','3333333333333333333333333' );
INSERT INTO t VALUES (4, '0100', '*','4444444444444444444444444' );
INSERT INTO t VALUES (5, '0100', '=','5555555555555555555555555' );
INSERT INTO t VALUES (6, '0200', '*','6666666666666666666666666' );

col text format a75

SELECT group_key AS "Line#", site, EXTRACT(XMLAGG(xmlelement("V", test)), '/V/text()') AS text
FROM (
  SELECT line, site, SUM(to_number(TRANSLATE(phase, '*=', '10')))
  OVER (ORDER BY line) AS group_key, test
  FROM t)
GROUP BY site, group_key;
EXTRACTVALUE
Takes as arguments an XMLType instance and an XPath expression and returns a scalar value of the resultant node | EXTRACTVALUE(XMLType_Instance>, <XPath_string>, <namespace_string>)
conn oe/oe

col docks format a30

SELECT warehouse_name,
EXTRACTVALUE(e.warehouse_spec, '/Warehouse/Docks') "Docks"
FROM warehouses e
WHERE warehouse_spec IS NOT NULL;
INSERTCHILDXML

Inserts a user-supplied value into the target XML at the node indicated by the XPath expression 		INSERTCHILDXML(XMLType_Instance>, <XPath_string>,
<child_expression>, <value_expression>, <namespace_string>)
conn oe/oe

set long 1000000

SELECT warehouse_spec
FROM warehouses
WHERE warehouse_id = 3;

UPDATE warehouses
SET warehouse_spec = INSERTCHILDXML(warehouse_spec,
'/Warehouse/Building', 'Owner', XMLType('<Owner>LesserCo</Owner>'))
WHERE warehouse_id = 3;

SELECT warehouse_spec
FROM warehouses
WHERE warehouse_id = 3;
INSERTXMLBEFORE

Inserts a user-supplied value into the target XML before the node indicated by the XPath expression 		INSERTXMLBEFORE(XMLType_Instance>, <XPath_string>,
<value_expression>, <namespace_string>)
conn oe/oe

SELECT warehouse_name, EXTRACT(warehouse_spec,
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;

UPDATE warehouses
SET warehouse_spec = INSERTXMLBEFORE(warehouse_spec,
'/Warehouse/Building/Owner[2]',
XMLType('<Owner>ThirdOwner</Owner>'))
WHERE warehouse_id = 3;

SELECT warehouse_name, EXTRACT(warehouse_spec,
'/Warehouse/Building/Owner') "Owners"
FROM warehouses
WHERE warehouse_id = 3;
PATH
Returns the relative path that leads to the resource specified in the parent condition. | PATH(<correlation_integer>)
See CONNECT_BY page
SYS_DBURIGEN
Generates a URL of datatype DBURIType to a particular column or row object | SYS_DBURIGEN(<column_or_attribute | rowid>, <'text()>');
conn oe/oe

SELECT SYS_DBURIGEN(employee_id, email)
FROM employees
WHERE employee_id = 206;
SYS_XMLAGG
Aggregates all of the XML documents or fragments represented by expr and produces a single XML document. It adds a new enclosing element with a default name ROWSET | SYS_XMLAGG(<expression>, <format>)
conn oe/oe

SELECT SYS_XMLAGG(SYS_XMLGEN(last_name))
FROM employees
WHERE last_name LIKE 'R%';
SYS_XMLGEN
Takes an expression that evaluates to a particular row and column of the database, and returns an instance of type XMLType containing an XML document | SYS_XMLGEN(<expression>, <format>)
conn oe/oe

SELECT SYS_XMLGEN(email)
FROM employees
WHERE employee_id = 205;
UPDATEXML

Takes as arguments an XMLType instance and an XPath-value pair and returns an XMLType instance with the updated value 		UPDATEXML(XMLType_Instance>, <XPath_string>,
<value_expression>, <namespace_string>)
conn oe/oe

SELECT warehouse_name,
EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks"
FROM warehouses
WHERE warehouse_name = 'San Francisco';

UPDATE warehouses
SET warehouse_spec = UPDATEXML(warehouse_spec,
'/Warehouse/Docks/text()',4)
WHERE warehouse_name = 'San Francisco';

SELECT warehouse_name,
EXTRACT(warehouse_spec, '/Warehouse/Docks') "Number of Docks"
FROM warehouses
WHERE warehouse_name = 'San Francisco';
XMLAGG

Takes a collection of XML fragments and returns an aggregated XML document. Any arguments that return null are dropped from the result 		XMLAGG(XMLType_Instance> <ORDER BY CLAUSE>)
conn oe/oe

set long 100000

SELECT XMLELEMENT("Department", XMLAGG(XMLELEMENT("Employee",
e.job_id||' '||e.last_name) ORDER BY last_name)) AS "Dept_list"
FROM employees e
WHERE e.department_id = 30;
XMLCAST (new in 11g)
XMLCast casts value_expression to the scalar SQL datatype specified by datatype. | XMLCAST(<value_expression> AS <data_type>)
TBD
XMLCDATA

Generates a CDATA section by evaluating value_expr 		XMLCDATA(<value_expression>)
conn oe/oe

SELECT XMLELEMENT("PurchaseOrder",
XMLAttributes(dummy AS "pono"),
XMLCdata('<!DOCTYPE po_dom_group [
<!ELEMENT po_dom_group(student_name)*>
<!ELEMENT po_purch_name (#PCDATA)>
<!ATTLIST po_name po_no ID #REQUIRED>
<!ATTLIST po_name trust_1 IDREF #IMPLIED>
<!ATTLIST po_name trust_2 IDREF #IMPLIED>
]>')) "XMLCData"
FROM dual;
XMLCOLATTVAL
Creates an XML fragment and then expands the resulting XML so that each XML fragment has the name column with the attribute name | XMLCOLATTVAL(<value_expression> AS c_alias)
conn oe/oe

SELECT XMLELEMENT("Emp",
XMLCOLATTVAL(e.employee_id, e.last_name, e.salary)) "Emp Element"
FROM employees e
WHERE employee_id = 204;
XMLCOMMENT
Generates an XML comment using an evaluated result of value_expr | XMLCOMMENT(<value_expression>)
conn oe/oe

SELECT XMLCOMMENT('OrderAnalysisComp imported, reconfigured, disassembled') AS "XMLCOMMENT"
FROM dual;
XMLCONCAT
Takes as input a series of XMLType instances, concatenates the series of elements for each row, and returns the concatenated series | XMLCONCAT(<XMLType_instance>)
conn oe/oe

SELECT XMLCONCAT(XMLELEMENT("First", e.first_name),
XMLELEMENT("Last", e.last_name)) AS "Result"
FROM employees e
WHERE e.employee_id > 202;
XMLDIFF

The XMLDiff function is the SQL interface for the XmlDiff C API. 		XMLDIFF(XMLType_document, XMLType_document, <integer>, <string>)
SELECT XMLDIFF(
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://nosuchsite.com">
  <bk:tr>
    <bk:td>
      <bk:chapter>
        Chapter 1.
      </bk:chapter>
    </bk:td>
    <bk:td>
      <bk:chapter>
         Chapter 2.
       </bk:chapter>
    </bk:td>
  </bk:tr>
</bk:book>'),
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://nosuchsite.com">
  <bk:tr>
    <bk:td>
      <bk:chapter>
        Chapter 1.
      </bk:chapter>
    </bk:td>
    <bk:td/>
  </bk:tr>
</bk:book>'))
FROM dual;
XMLELEMENT (missed earlier)
XMLElement takes an element name for identifier or evaluates an element name for EVALNAME value_expr, an optional collection of attributes for the element, and arguments that make up the content of the element. | XMLELEMENT(
SELECT XMLELEMENT("Emp", XMLELEMENT("Name", e.job_id||' '||e.last_name),
XMLELEMENT("Hiredate", e.hire_date)) AS "Result"
FROM employees e
WHERE employee_id > 200;
XMLEXISTS (new in 11g)
XMLExists checks whether a given XQuery expression returns a nonempty XQuery sequence. If so, the function returns TRUE; otherwise, it returns FALSE. | XMLEXISTS(XQuery_string PASSING [BY VALUE] expression [AS IDENTIFIER])
TBD
XMLFOREST
Converts each of its argument parameters to XML, and then returns an XML fragment that is the concatenation of these converted arguments | XMLFOREST(<value_expression> AS c_alias)
conn oe/oe

SELECT XMLELEMENT("Emp", XMLFOREST(e.employee_id, e.last_name, e.salary)) "Emp Element"
FROM employees e
WHERE employee_id = 204;
XMLISVALID
Checks if the input instance conforms to a specified XML schema. It does not change the validation status of the XML instance. If any argument is NULL, the result is NULL. If validation fails, then 0 is returned. | XMLIsValid(XMLType_inst [, schemaurl [, elem]])
CREATE TABLE po_tab OF XMLTYPE (CHECK (XMLIsValid(object_value) = 1))
XMLSchema "http://www.example.com/schemas/ipo.xsd" ELEMENT "purchaseOrder";
XMLPARSE
Parses and generates an XML instance from the evaluated result of value_expr | XMLPARSE(<document | content> <value_expression> [WELLFORMED])
conn oe/oe

SELECT XMLPARSE(CONTENT '124 <purchaseOrder poNo="12435">
<customerName> Acme Enterprises</customerName>
<itemNo>32987457</itemNo> </purchaseOrder>' WELLFORMED) AS PO
FROM dual;
XMLPATCH (new in 11g)

The XMLPatch function is the SQL interface for the XmlPatch C API. This function patches an XML document with the changes specified. The patched XMLType document is returned. 		XMLPATCH(XMLType_document, XMLType_document)
SELECT XMLPATCH(
XMLTYPE('<?xml version="1.0"?>
<bk:book xmlns:bk="http://nosuchsite.com">
  <bk:tr>
      <bk:td>
        <bk:chapter>
          Chapter 1.
        </bk:chapter>
      </bk:td>
      <bk:td>
        <bk:chapter>
          Chapter 2.
        </bk:chapter>
      </bk:td>
  </bk:tr>
</bk:book>'),
XMLTYPE('<?xml version="1.0"?>
<xd:xdiff xsi:schemaLocation="http://xmlns.oracle.com/xdb/xdiff.xsd
  http://xmlns.oracle.com/xdb/xdiff.xsd"
  xmlns:xd="http://xmlns.oracle.com/xdb/xdiff.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:bk="http://nosuchsite.com">
  <?oracle-xmldiff operations-in-docorder="true" output-model="snapshot"
    diff-algorithm="global"?>
  <xd:delete-node xd:node-type="element"
    xd:xpath="/bk:book[1]/bk:tr[1]/bk:td[2]/bk:chapter[1]"/>
</xd:xdiff>'))
FROM dual;
XMLPI
Generates an XML processing instruction using identifier and optionally the evaluated result of value_expr | XMLPI(<name> <identifier>, <value_expression>)
conn oe/oe

SELECT XMLPI(NAME "Order analysisComp", 'imported, reconfigured, disassembled') AS "XMLPI"
FROM dual;
XMLQUERY
See XMLQuery Web Page
XMLROOT
Create a new XML value by providing version and standalone properties in the XML root information (prolog) of an existing XML value XMLROOT(<value_expression>, VERSION <value_expression | NO VALUE>,
[STANDALONE <YES | NO | NO VALUE>])
conn oe/oe

SELECT XMLROOT(XMLType('<poid>143598</poid>'), VERSION '1.0', STANDALONE YES) AS "XMLROOT"
FROM dual;
XMLSEQUENCE
Takes as input an XMLType instance and returns a varray of the top-level nodes in the XMLType. | XMLSEQUENCE(<XMLType_Instance>)
conn oe/oe

SELECT EXTRACT(warehouse_spec, '/Warehouse') AS "Warehouse"
FROM warehouses
WHERE warehouse_name = 'San Francisco';

SELECT VALUE(p)
FROM warehouses w,
TABLE(XMLSEQUENCE(EXTRACT(warehouse_spec, '/Warehouse/*'))) p
WHERE w.warehouse_name = 'San Francisco';
Takes as input a REFCURSOR instance, with an optional instance of the XMLFormat object, and returns as an XMLSequence type an XML document for each row of the cursor | XMLSEQUENCE(<sys_refcursor_instance, format>)
TBD
XMLSERIALIZE
Creates a string or LOB containing the contents of value_expr. | XMLSERIALIZE(<DOCUMENT | CONTENT> <value_expression> AS <datatype>)
conn oe/oe

SELECT XMLSERIALIZE(CONTENT XMLTYPE('<Owner>Grandco</Owner>'))
FROM dual;
XMLTABLE
See XMLTABLE Web Page
XMLTRANSFORM

Takes as arguments an XMLType instance and an XSL style sheet, which is itself a form of XMLType instance. It applies the style sheet to the instance and returns an XMLType. 		XMLTRANSFORM(<XMLType_instance>, <XMLType_instance)
-- do not run this demo as part of the OE series as the implicit commit
-- in CREATE TABLE will change your OE schema permanently.

conn oe/oe

CREATE TABLE xsl_tab (col1 XMLTYPE);

INSERT INTO xsl_tab
VALUES (
XMLTYPE.createxml('<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8"/> <!-- alphabetizes an xml tree -->
<xsl:template match="*"> <xsl:copy>
<xsl:apply-templates select="*|text()">
<xsl:sort select="name(.)" data-type="text" order="ascending"/>
</xsl:apply-templates> </xsl:copy> </xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template> </xsl:stylesheet> '));

SELECT XMLTRANSFORM(w.warehouse_spec, x.col1).GetClobVal()
FROM warehouses w, xsl_tab x
WHERE w.warehouse_name = 'San Francisco';
Related Topics
Date Functions
Numeric Functions
CONNECT BY
String Functions
Timestamp
XMLQuery
XMLTable


Oracle XML Table

Oracle XML Tables
Version 10.2
General
Source | {ORACLE_HOME}/rdbms/admin/dbmsxmlt.sql
Dependencies
source$ | tab$ | type$
XMLType |  |
DBA | ALL | USER
dba_tables | all_tables | user_tables
dba_tab_cols | all_tab_cols | user_tab_cols
dba_xml_tables | all_xml_tables | user_xml_tables
Create

Simple XML Table 		CREATE TABLE <table_name> (
<column_name> <data type and precision>,
<column_name> <data type and precision>,
CONSTRAINT <constraint_name>
PRIMARY KEY (<primary key constraint columns>))
ORGANIZATION INDEX;
CREATE TABLE xml_lob_tab OF XMLTYPE;

desc xml_lob_tab

SELECT table_name, storage_type
FROM user_xml_tables;

col data_type format a30

SELECT column_name, data_type
FROM user_tab_cols
WHERE table_name = 'XML_LOB_TAB';

set linesize 121

SELECT owner, typecode, attributes, methods, instantiable
from all_types
WHERE type_name = 'XMLTYPE';

SELECT text
FROM all_source
WHERE name = 'XMLTYPE'
ORDER BY line;
Simple XML Table CREATE TABLE <table_name> (
CREATE TABLE xwarehouses OF XMLTYPE
XMLSCHEMA "http://www.oracle.com/xwarehouses.xsd"
ELEMENT "Warehouse";

CREATE TABLE xsample OF XMLTYPE
XMLSCHEMA "http://www.w3schools.com/xml/cd_catalog.xml"
ELEMENT "Sample";
Alter
Change Storage ALTER TABLE <table_name>
MODIFY LOB (<lob_name>)
(STORAGE (<storage_parameter>
ALTER TABLE xml_lob_tab
MODIFY LOB (XMLDATA)
(STORAGE (BUFFER_POOL DEFAULT) CACHE);
Drop
Drop XML Table | DROP TABLE <table_name>;
DROP TABLE xml_lob_tab PURGE;
Related Topics
DBMS_XMLGEN
XML Functions
Tables
XMLQuery
XMLTable


Oracle XMLQuery XML Query

Oracle XMLQuery
Version 10.2
General
Note: XMLQuery returns query results as XML. XMLTable returns results as relation data.
Demo Tables CREATE TABLE person_data (
person_id   NUMBER(3),
person_data XMLTYPE);

Demo Data 		INSERT INTO person_data
(person_id, person_data)
VALUES
(1, XMLTYPE('
 <PDRecord>
   <PDName>Daniel Morgan</PDName>
   <PDDOB>12/1/1951</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

INSERT INTO person_data
(person_id, person_data)
VALUES
(2, XMLTYPE('
 <PDRecord>
   <PDName>Jack Cline</PDName>
   <PDDOB>5/17/1949</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

INSERT INTO person_data
(person_id, person_data)
VALUES
(3, XMLTYPE('
 <PDRecord>
   <PDName>Caleb Small</PDName>
   <PDDOB>1/1/1960</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

COMMIT;

SELECT * FROM person_data;

set long 100000

SELECT * FROM person_data;
SELECT
Simple Query (with equals) SELECT <column_list>, XMLQuery (
'for $i IN <record_end_tag>
 where $i<item_end_tag> = <value>
 order by $i<item_end_tag>
 return $i<item_end_tag>
PASSING BY VALUE <xml_record_column>
RETURNING CONTENTS) <returning_column_alias>
FROM <table_name>;

Note: What is within the parentheses is case sensitive and you can not use Upper Case or InitCap for commands.
SELECT person_id, XMLQuery(
'for $i in /PDRecord
 where $i /PDName = "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName eq "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Greater Than SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName > "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName gt "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Greater Than Or Equal To SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName >= "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName ge "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Less Than SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName < "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName lt "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Less Than Or Equal To SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName >= "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'for $i in /PDRecord
 where $i /PDName le "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Not Equals SELECT person_id, XMLQuery (
'For $i in /PDRecord
 where $i /PDName != "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;

SELECT person_id, XMLQuery (
'For $i in /PDRecord
 where $i /PDName ne "Daniel Morgan"
 order by $i/PDName
 return $i/PDName'
passing by value person_data
RETURNING CONTENT) XMLData
FROM person_data;
Additional Syntax Items [
- -and- +
|
//
>>
and -and- or
div -or- *
except
idiv
is
mod
to
union -and- intersect
<CastAs>
<CastableAs>
<EOF>
<InstanceOf>
<TreatAs>
Related Topics
DBMS_XMLGEN
XML Functions
XMLTable
XML Tables


Oracle XMLTable XML Table

Oracle XMLTable
Version 10.2
General
Note: XMLQuery returns query results as XML. XMLTable returns results as relation data.
Demo Tables CREATE TABLE person_data (
person_id   NUMBER(3),
person_data XMLTYPE);
Demo Data INSERT INTO person_data
(person_id, person_data)
VALUES
(1, XMLTYPE('
 <PDRecord>
   <PDName>Daniel Morgan</PDName>
   <PDDOB>12/1/1951</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

INSERT INTO person_data
(person_id, person_data)
VALUES
(2, XMLTYPE('
 <PDRecord>
   <PDName>Jack Cline</PDName>
   <PDDOB>5/17/1949</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

INSERT INTO person_data
(person_id, person_data)
VALUES
(3, XMLTYPE('
 <PDRecord>
   <PDName>Caleb Small</PDName>
   <PDDOB>1/1/1960</PDDOB>
   <PDEmail>damorgan@u.washington.edu</PDEmail>
  </PDRecord>')
);

COMMIT;

SELECT * FROM person_data;

set long 100000

SELECT * FROM person_data;
SELECT
Simple Query (with equals) SELECT <column_list>, XMLQuery (
'for $i IN <record_end_tag>
 where $i<item_end_tag> = <value>
 order by $i<item_end_tag>
 return $i<item_end_tag>
PASSING BY VALUE <xml_record_column>
RETURNING CONTENTS) <returning_column_alias>
FROM <table_name>;

Note: What is within the parentheses is case sensitive and you can not use Upper Case or InitCap for commands.
SELECT t.column_value
FROM person_data a,
  XMLTABLE (
    'for $root in $date
     where $root/PDRecord/PDName = "Daniel Morgan"
     return $root/PDRecord/PDDOB/text()'
  passing a.person_data AS "date") t;
Related Topics
DBMS_XMLGEN
XML Functions
XMLQuery
XML Tables