Database Receive Updates For This Category
Auditing in Oracle 10g Release 2
This article presents an overview of auditing in Oracle 10g Release 2. Many of the topics presented here have been covered in previous articles, but this serves to bring them all together.
- Server Setup
- Audit Options
- View Audit Trail
- Maintenance and Security
- Fine Grained Auditing
Server Setup
Auditing is a default feature of the Oracle server. The initialization parameters that influence its behaviour can be displayed using the SHOW PARAMETERSQL*Plus command.
SQL> SHOW PARAMETER AUDIT
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
audit_file_dest string C:\ORACLE\PRODUCT\10.2.0\ADMIN
\DB10G\ADUMP
audit_sys_operations boolean FALSE
audit_trail string NONE
SQL>
Auditing is disabled by default, but can enabled by setting the AUDIT_TRAIL static parameter, which has the following allowed values.
AUDIT_TRAIL = { none | os | db | db,extended | xml | xml,extended }
The following list provides a description of each setting:
noneorfalse8211; Auditing is disabled.dbortrue8211; Auditing is enabled, with all audit records stored in the database audit trial (SYS.AUD$).db,extended8211; Asdb, but theSQL_BINDandSQL_TEXTcolumns are also populated.xml- Auditing is enabled, with all audit records stored as XML format OS files.xml,extended8211; Asxml, but theSQL_BINDandSQL_TEXTcolumns are also populated.os- Auditing is enabled, with all audit records directed to the operating system8217;s audit trail.
Note. In Oracle 10g Release 1, db_extended was used in place of db,extended. The XML options are new to Oracle 10g Release 2.
The AUDIT_SYS_OPERATIONS static parameter enables or disables the auditing of operations issued by users connecting with SYSDBA or SYSOPER privileges, including the SYS user. All audit records are written to the OS audit trail.
The AUDIT_FILE_DEST parameter specifies the OS directory used for the audit trail when the os, xml and xml,extended options are used. It is also the location for all mandatory auditing specified by the AUDIT_SYS_OPERATIONS parameter.
To enable auditing and direct audit records to the database audit trail, we would do the following.
SQL> ALTER SYSTEM SET audit_trail=db SCOPE=SPFILE; System altered. SQL> SHUTDOWN Database closed. Database dismounted. ORACLE instance shut down. SQL> STARTUP ORACLE instance started. Total System Global Area 289406976 bytes Fixed Size 1248600 bytes Variable Size 71303848 bytes Database Buffers 213909504 bytes Redo Buffers 2945024 bytes Database mounted. Database opened. SQL>
Audit Options
One look at the AUDIT command syntax should give you an idea of how flexible Oracle auditing is. There is no point repeating all this information, so instead we will look at a simple example.
First we create a new user called AUDIT_TEST.
CONNECT sys/password AS SYSDBA CREATE USER audit_test IDENTIFIED BY password DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp QUOTA UNLIMITED ON users; GRANT connect TO audit_test; GRANT create table, create procedure TO audit_test;
Next we audit all operations by the AUDIT_TEST user.
CONNECT sys/password AS SYSDBA AUDIT ALL BY audit_test BY ACCESS; AUDIT SELECT TABLE, UPDATE TABLE, INSERT TABLE, DELETE TABLE BY audit_test BY ACCESS; AUDIT EXECUTE PROCEDURE BY audit_test BY ACCESS;
These options audit all DDL and DML, along with some system events.
- DDL (CREATE, ALTER & DROP of objects)
- DML (INSERT UPDATE, DELETE, SELECT, EXECUTE).
- SYSTEM EVENTS (LOGON, LOGOFF etc.)
Next, we perform some operations that will be audited.
CONN audit_test/password CREATE TABLE test_tab ( id NUMBER ); INSERT INTO test_tab (id) VALUES (1); UPDATE test_tab SET id = id; SELECT * FROM test_tab; DELETE FROM test_tab; DROP TABLE test_tab;
In the next section we will look at how we view the contents of the audit trail.
View Audit Trail
The audit trail is stored in the SYS.AUD$ table. Its contents can be viewed directly or via the following views:
SELECT view_name FROM dba_views WHERE view_name LIKE 'DBA%AUDIT%' ORDER BY view_name; VIEW_NAME ------------------------------ DBA_AUDIT_EXISTS DBA_AUDIT_OBJECT DBA_AUDIT_POLICIES DBA_AUDIT_POLICY_COLUMNS DBA_AUDIT_SESSION DBA_AUDIT_STATEMENT DBA_AUDIT_TRAIL DBA_COMMON_AUDIT_TRAIL DBA_FGA_AUDIT_TRAIL DBA_OBJ_AUDIT_OPTS DBA_PRIV_AUDIT_OPTS DBA_REPAUDIT_ATTRIBUTE DBA_REPAUDIT_COLUMN DBA_STMT_AUDIT_OPTS 14 rows selected. SQL>
The three main views are:
DBA_AUDIT_TRAIL8211; Standard auditing only (fromAUD$).DBA_FGA_AUDIT_TRAIL8211; Fine-grained auditing only (fromFGA_LOG$).DBA_COMMON_AUDIT_TRAIL8211; Both standard and fine-grained auditing.
The most basic view of the database audit trail is provided by the DBA_AUDIT_TRAIL view, which contains a wide variety of information. The following query displays the some of the information from the database audit trail.
COLUMN username FORMAT A10
COLUMN owner FORMAT A10
COLUMN obj_name FORMAT A10
COLUMN extended_timestamp FORMAT A35
SELECT username,
extended_timestamp,
owner,
obj_name,
action_name
FROM dba_audit_trail
WHERE owner = 'AUDIT_TEST'
ORDER BY timestamp;
USERNAME EXTENDED_TIMESTAMP OWNER OBJ_NAME ACTION_NAME
---------- ----------------------------------- ---------- ---------- ----------------------------
AUDIT_TEST 16-FEB-2006 14:16:55.435000 +00:00 AUDIT_TEST TEST_TAB CREATE TABLE
AUDIT_TEST 16-FEB-2006 14:16:55.514000 +00:00 AUDIT_TEST TEST_TAB INSERT
AUDIT_TEST 16-FEB-2006 14:16:55.545000 +00:00 AUDIT_TEST TEST_TAB UPDATE
AUDIT_TEST 16-FEB-2006 14:16:55.592000 +00:00 AUDIT_TEST TEST_TAB SELECT
AUDIT_TEST 16-FEB-2006 14:16:55.670000 +00:00 AUDIT_TEST TEST_TAB DELETE
AUDIT_TEST 16-FEB-2006 14:17:00.045000 +00:00 AUDIT_TEST TEST_TAB DROP TABLE
6 rows selected.
SQL>
When the audit trail is directed to an XML format OS file, it can be read using a text editor or via the V$XML_AUDIT_TRAIL view, which contains similar information to the DBA_AUDIT_TRAIL view.
COLUMN db_user FORMAT A10
COLUMN object_schema FORMAT A10
COLUMN object_name FORMAT A10
COLUMN extended_timestamp FORMAT A35
SELECT db_user,
extended_timestamp,
object_schema,
object_name,
action
FROM v$xml_audit_trail
WHERE object_schema = 'AUDIT_TEST'
ORDER BY extended_timestamp;
DB_USER EXTENDED_TIMESTAMP OBJECT_SCH OBJECT_NAM ACTION
---------- ----------------------------------- ---------- ---------- ----------
AUDIT_TEST 16-FEB-2006 14:14:33.417000 +00:00 AUDIT_TEST TEST_TAB 1
AUDIT_TEST 16-FEB-2006 14:14:33.464000 +00:00 AUDIT_TEST TEST_TAB 2
AUDIT_TEST 16-FEB-2006 14:14:33.511000 +00:00 AUDIT_TEST TEST_TAB 6
AUDIT_TEST 16-FEB-2006 14:14:33.542000 +00:00 AUDIT_TEST TEST_TAB 3
AUDIT_TEST 16-FEB-2006 14:14:33.605000 +00:00 AUDIT_TEST TEST_TAB 7
AUDIT_TEST 16-FEB-2006 14:14:34.917000 +00:00 AUDIT_TEST TEST_TAB 12
6 rows selected.
SQL>
Several fields were added to both the standard and fine-grained audit trails in Oracle 10g, including:
EXTENDED_TIMESTAMP8211; A more precise value than the exisingTIMESTAMPcolumn.PROXY_SESSIONID8211; Proxy session serial number when an enterprise user is logging in via the proxy method.GLOBAL_UID8211; Global Universal Identifier for an enterprise user.INSTANCE_NUMBER8211; TheINSTANCE_NUMBERvalue from the actioning instance.OS_PROCESS8211; Operating system process id for the oracle process.TRANSACTIONID8211; Transaction identifier for the audited transaction. This column can be used to join to theXIDcolumn on theFLASHBACK_TRANSACTION_QUERYview.SCN8211; System change number of the query. This column can be used in flashback queries.SQL_BIND8211; The values of any bind variables if any.SQL_TEXT8211; The SQL statement that initiated the audit action.
The SQL_BIND and SQL_TEXT columns are only populated when the AUDIT_TRAIL parameter is set to db,extended or xml,extended.
Maintenance and Security
Auditing should be planned carefully to control the quantity of audit information. Only audit specific operations or objects of interest. Over time you can refine the level of auditing to match your requirements.
The database audit trail must be deleted, or archived, on a regular basis to prevent the SYS.AUD$ table growing to an unnacceptable size.Only DBAs should have maintenance access to the audit trail. Auditing modifications of the data in the audit trail itself can be achieved using the following statement:
AUDIT INSERT, UPDATE, DELETE ON sys.aud$ BY ACCESS;
The OS and XML audit trails are managed through the OS. These files should be secured at the OS level by assigning the correct file permissions.
Fine Grained Auditing (FGA)
Fine grained auditing extends Oracle standard auditing capabilities by allowing the user to audit actions based on user-defined predicates. It is independant of the AUDIT_TRAIL parameter setting and all audit records are stored in the FGA_LOG$ table, rather than the AUD$ table. The following example illustrates how fine grained auditing is used.
First, create a test table.
CONN audit_test/password CREATE TABLE emp ( empno NUMBER(4) NOT NULL, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) ); INSERT INTO emp (empno, ename, sal) VALUES (9999, 'Tim', 1); INSERT INTO emp (empno, ename, sal) VALUES (9999, 'Larry', 50001); COMMIT;
The following policy audits any queries of salaries greater than £50,000.
CONN sys/password AS sysdba
BEGIN
DBMS_FGA.add_policy(
object_schema => 'AUDIT_TEST',
object_name => 'EMP',
policy_name => 'SALARY_CHK_AUDIT',
audit_condition => 'SAL > 50000',
audit_column => 'SAL');
END;
/
Querying both employees proves the auditing policy works as expected.
CONN audit_test/password SELECT sal FROM emp WHERE ename = 'Tim'; SELECT sal FROM emp WHERE ename = 'Larry'; CONN sys/password AS SYSDBA SELECT sql_text FROM dba_fga_audit_trail; SQL_TEXT ------------------------------------------ SELECT sal FROM emp WHERE ename = 'Larry' 1 row selected. SQL>
Extra processing can be associated with an FGA event by defining a database procedure and associating this to the audit event. The following example assumes the FIRE_CLERK procedure has been defined:
BEGIN
DBMS_FGA.add_policy(
object_schema => 'AUDIT_TEST',
object_name => 'EMP',
policy_name => 'SALARY_CHK_AUDIT',
audit_condition => 'SAL > 50000',
audit_column => 'SAL',
handler_schema => 'AUDIT_TEST',
handler_module => 'FIRE_CLERK',
enable => TRUE);
END;
/
The DBMS_FGA package contains the following procedures:
ADD_POLICYDROP_POLICYENABLE_POLICYDISABLE_POLICY
In Oracle9i fine grained auditing was limited queries, but in Oracle 10g it has been extended to include DML statements, as shown by the following example.
-- Clear down the audit trail.
CONN sys/password AS SYSDBA
TRUNCATE TABLE fga_log$;
SELECT sql_text FROM dba_fga_audit_trail;
no rows selected.
-- Apply the policy to the SAL column of the EMP table.
BEGIN
DBMS_FGA.add_policy(
object_schema => 'AUDIT_TEST',
object_name => 'EMP',
policy_name => 'SAL_AUDIT',
audit_condition => NULL, -- Equivalent to TRUE
audit_column => 'SAL',
statement_types => 'SELECT,INSERT,UPDATE,DELETE');
END;
/
-- Test the auditing.
CONN audit_test/password
SELECT * FROM emp WHERE empno = 9998;
INSERT INTO emp (empno, ename, sal) VALUES (9998, 'Bill', 1);
UPDATE emp SET sal = 10 WHERE empno = 9998;
DELETE emp WHERE empno = 9998;
ROLLBACK;
-- Check the audit trail.
CONN sys/password AS SYSDBA
SELECT sql_text FROM dba_fga_audit_trail;
SQL_TEXT
--------------------------------------
SELECT * FROM emp WHERE empno = 9998
INSERT INTO emp (empno, ename, sal) VALUES (9998, 'Bill', 1)
UPDATE emp SET sal = 10 WHERE empno = 9998
DELETE emp WHERE empno = 9998
4 rows selected.
-- Drop the policy.
CONN sys/password AS SYSDBA
BEGIN
DBMS_FGA.drop_policy(
object_schema => 'AUDIT_TEST',
object_name => 'EMP',
policy_name => 'SAL_AUDIT');
END;
/
Automatic Database Diagnostic Monitor (ADDM) in Oracle Database 10g
This article describes several methods for producing reports from the Automatic Database Diagnostic Monitor (ADDM) in Oracle 10g.
- Overview
- Enterprise Manager
- addmrpt.sql Script
- DBMS_ADVISOR
- Related Views
Overview
The Automatic Database Diagnostic Monitor (ADDM) analyzes data in the Automatic Workload Repository (AWR) to identify potential performance bottlenecks. For each of the identified issues it locates the root cause and provides recommendations for correcting the problem. An ADDM analysis task is performed and its findings and recommendations stored in the database every time an AWR snapshot is taken provided the STATISTICS_LEVEL parameter is set to TYPICAL or ALL. The ADDM analysis includes the following.
- CPU load
- Memory usage
- I/O usage
- Resource intensive SQL
- Resource intensive PL/SQL and Java
- RAC issues
- Application issues
- Database configuration issues
- Concurrency issues
- Object contention
There are several ways to produce reports from the ADDM analysis which will be explained later, but all follow the same format. The findings (problems) are listed in order of potential impact on database performance, along with recommendations to resolve the issue and the symptoms which lead to it8217;s discovery. An example from my test instance is shown below.
FINDING 1: 59% impact (944 seconds)
-----------------------------------
The buffer cache was undersized causing significant additional read I/O.
RECOMMENDATION 1: DB Configuration, 59% benefit (944 seconds)
ACTION: Increase SGA target size by increasing the value of parameter
"sga_target" by 28 M.
SYMPTOMS THAT LED TO THE FINDING:
Wait class "User I/O" was consuming significant database time. (83%
impact [1336 seconds])
The recommendations may include:
- Hardware changes
- Database configuration changes
- Schema changes
- Application changes
- Using other advisors
The analysis of I/O performance is affected by the DBIO_EXPECTED parameter which should be set to the average time (in microseconds) it takes to read a single database block from disk. Typical values range from 5000 to 20000 microsoconds. The parameter can be set using the following.
EXECUTE DBMS_ADVISOR.set_default_task_parameter('ADDM', 'DBIO_EXPECTED', 8000);
Enterprise Manager
The obvious place to start viewing ADDM reports is Enterprise Manager. The 8220;Performance Analysis8221; section on the 8220;Home8221; page is a list of the top five findings from the last ADDM analysis task.
Specific reports can be produced by clicking on the 8220;Advisor Central8221; link, then the 8220;ADDM8221; link. The resulting page allows you to select a start and end snapshot, create an ADDM task and display the resulting report by clicking on a few links.
addmrpt.sql Script
The addmrpt.sql script can be used to create an ADDM report from SQL*Plus. The script is called as follows.
-- UNIX @/u01/app/oracle/product/10.1.0/db_1/rdbms/admin/addmrpt.sql -- Windows @d:oracleproduct10.1.0db_1rdbmsadminaddmrpt.sql
It then lists all available snapshots and prompts you to enter the start and end snapshot along with the report name.
DBMS_ADVISOR
The DBMS_ADVISOR package can be used to create and execute any advisor tasks, including ADDM tasks. The following example shows how it is used to create, execute and display a typical ADDM report.
BEGIN
-- Create an ADDM task.
DBMS_ADVISOR.create_task (
advisor_name => 'ADDM',
task_name => '970_1032_AWR_SNAPSHOT',
task_desc => 'Advisor for snapshots 970 to 1032.');
-- Set the start and end snapshots.
DBMS_ADVISOR.set_task_parameter (
task_name => '970_1032_AWR_SNAPSHOT',
parameter => 'START_SNAPSHOT',
value => 970);
DBMS_ADVISOR.set_task_parameter (
task_name => '970_1032_AWR_SNAPSHOT',
parameter => 'END_SNAPSHOT',
value => 1032);
-- Execute the task.
DBMS_ADVISOR.execute_task(task_name => '970_1032_AWR_SNAPSHOT');
END;
/
-- Display the report.
SET LONG 100000
SET PAGESIZE 50000
SELECT DBMS_ADVISOR.get_task_report('970_1032_AWR_SNAPSHOT') AS report
FROM dual;
SET PAGESIZE 24
The value for the SET LONG command should be adjusted to allow the whole report to be displayed.
The relevant AWR snapshots can be identified using the DBA_HIST_SNAPSHOT view.
Related Views
The following views can be used to display the ADDM output without using Enterprise Manager or the GET_TASK_REPORT function.
DBA_ADVISOR_TASKS8211; Basic information about existing tasks.DBA_ADVISOR_LOG8211; Status information about existing tasks.DBA_ADVISOR_FINDINGS8211; Findings identified for an existing task.DBA_ADVISOR_RECOMMENDATIONS8211; Recommendations for the problems identified by an existing task.
Automatic SQL Tuning in Oracle Database 10g
This article the discusses the new features which automate the tuning of SQL statements in Oracle 10g:
- Overview
- SQL Tuning Advisor
- Managing SQL Profiles
- SQL Tuning Sets
- Useful Views
Overview
In its normal mode the query optimizer needs to make decisions about execution plans in a very short time. As a result it may not always be able to obtain enough information to make the best decision. Oracle 10g allows the optimizer to run in tuning mode where it can gather additional information and make recommendations about how specific statements can be tuned further. This process may take several minutes for a single statement so it is intended to be used on high-load resource-intensive statements.
In tuning mode the optimizer performs the following analysis:
- Statistics Analysis 8211; The optimizer recommends the gathering of statistics on objects with missing or stale statistics. Additional statistics for these objects are stored in an SQL profile.
- SQL Profiling 8211; The optimizer may be able to improve performance by gathering additional statistics and altering session specific parameters such as the
OPTIMIZER_MODE. If such improvements are possible the information is stored in an SQL profile. If accepted this information can then used by the optimizer when running in normal mode. Unlike a stored outline which fixes the execution plan, an SQL profile may still be of benefit when the contents of the table alter drastically. Even so, it8217;s sensible to update profiles periodically. The SQL profiling is not performed when the tuining optimizer is run in limited mode. - Access Path Analysis 8211; The optimizer investigates the effect of new or modified indexes on the access path. It8217;s index recommendations relate to a specific statement so where necessary it will also suggest the use of the SQL Access Advisor to check the impact of these indexes on a representative SQL workload.
- SQL Structure Analysis 8211; The optimizer suggests alternatives for SQL statements that contain structures that may impact on performance. The implementation of these suggestions requires human intervention to check their validity.
The automatic SQL tuning features are accessible from Enterprise Manager on the 8220;Advisor Central8221; page these or from PL/SQL using the DBMS_SQLTUNE package. This article will focus on the PL/SQL API as the Enterprise Manager interface is reasonably intuative.
SQL Tuning Advisor
In order to access the SQL tuning advisor API a user must be granted the ADVISOR privilege:
CONN sys/password AS SYSDBA GRANT ADVISOR TO scott; CONN scott/tiger
The first step when using the SQL tuning advisor is to create a new tuning task using the CREATE_TUNING_TASK function. The statements to be analyzed can be retrieved from the Automatic Workload Repository (AWR), the cursor cache, an SQL tuning set or specified manually:
SET SERVEROUTPUT ON
-- Tuning task created for specific a statement from the AWR.
DECLARE
l_sql_tune_task_id VARCHAR2(100);
BEGIN
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
begin_snap => 764,
end_snap => 938,
sql_id => '19v5guvsgcd1v',
scope => DBMS_SQLTUNE.scope_comprehensive,
time_limit => 60,
task_name => '19v5guvsgcd1v_AWR_tuning_task',
description => 'Tuning task for statement 19v5guvsgcd1v in AWR.');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/
-- Tuning task created for specific a statement from the cursor cache.
DECLARE
l_sql_tune_task_id VARCHAR2(100);
BEGIN
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
sql_id => '19v5guvsgcd1v',
scope => DBMS_SQLTUNE.scope_comprehensive,
time_limit => 60,
task_name => '19v5guvsgcd1v_tuning_task',
description => 'Tuning task for statement 19v5guvsgcd1v.');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/
-- Tuning task created from an SQL tuning set.
DECLARE
l_sql_tune_task_id VARCHAR2(100);
BEGIN
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
sqlset_name => 'test_sql_tuning_set',
scope => DBMS_SQLTUNE.scope_comprehensive,
time_limit => 60,
task_name => 'sqlset_tuning_task',
description => 'Tuning task for an SQL tuning set.');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/
-- Tuning task created for a manually specified statement.
DECLARE
l_sql VARCHAR2(500);
l_sql_tune_task_id VARCHAR2(100);
BEGIN
l_sql := 'SELECT e.*, d.* ' ||
'FROM emp e JOIN dept d ON e.deptno = d.deptno ' ||
'WHERE NVL(empno, ''0'') = :empno';
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
sql_text => l_sql,
bind_list => sql_binds(anydata.ConvertNumber(100)),
user_name => 'scott',
scope => DBMS_SQLTUNE.scope_comprehensive,
time_limit => 60,
task_name => 'emp_dept_tuning_task',
description => 'Tuning task for an EMP to DEPT join query.');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/
If the TASK_NAME parameter is specified it8217;s value is returned as the SQL tune task identifier. If ommitted a system generated name like 8220;TASK_14788243; is returned. If the SCOPE parameter is set to scope_limited the SQL profiling analysis is omitted. The TIME_LIMIT parameter simply restricts the time the optimizer can spend compiling the recommendations.
The following examples will reference the last tuning set as it has no external dependancies other than the SCOTT schema. The NVL in the SQL statement was put in to provoke a reaction from the optimizer. In addition we can delete the statistics from one of the tables to provoke it even more:
EXEC DBMS_STATS.delete_table_stats('SCOTT','EMP');
With the tuning task defined the next step is to execute it using the EXECUTE_TUNING_TASK procedure:
EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'emp_dept_tuning_task');
During the execution phase you may wish to pause and restart the task, cancel it or reset the task to allow it to be re-executed:
-- Interrupt and resume a tuning task. EXEC DBMS_SQLTUNE.interrupt_tuning_task (task_name => 'emp_dept_tuning_task'); EXEC DBMS_SQLTUNE.resume_tuning_task (task_name => 'emp_dept_tuning_task'); -- Cancel a tuning task. EXEC DBMS_SQLTUNE.cancel_tuning_task (task_name => 'emp_dept_tuning_task'); -- Reset a tuning task allowing it to be re-executed. EXEC DBMS_SQLTUNE.reset_tuning_task (task_name => 'emp_dept_tuning_task');
The status of the tuning task can be monitored using the DBA_ADVISOR_LOG view:
SELECT task_name, status FROM dba_advisor_log WHERE owner = 'SCOTT'; TASK_NAME STATUS ------------------------------ ----------- emp_dept_tuning_task COMPLETED 1 row selected.
Once the tuning task has executed successfully the recommendations can be displayed using the REPORT_TUNING_TASK function:
SET LONG 10000;
SET PAGESIZE 1000
SET LINESIZE 200
SELECT DBMS_SQLTUNE.report_tuning_task('emp_dept_tuning_task') AS recommendations FROM dual;
SET PAGESIZE 24
In this case the output looks like this:
RECOMMENDATIONS
--------------------------------------------------------------------------------
GENERAL INFORMATION SECTION
-------------------------------------------------------------------------------
Tuning Task Name : emp_dept_tuning_task
Scope : COMPREHENSIVE
Time Limit(seconds): 60
Completion Status : COMPLETED
Started at : 05/06/2004 09:29:13
Completed at : 05/06/2004 09:29:15
-------------------------------------------------------------------------------
SQL ID : 0wrmfv2yvswx1
SQL Text: SELECT e.*, d.* FROM emp e JOIN dept d ON e.deptno = d.deptno
WHERE NVL(empno, '0') = :empno
-------------------------------------------------------------------------------
FINDINGS SECTION (2 findings)
-------------------------------------------------------------------------------
1- Statistics Finding
---------------------
Table "SCOTT"."EMP" and its indices were not analyzed.
Recommendation
--------------
Consider collecting optimizer statistics for this table and its indices.
execute dbms_stats.gather_table_stats(ownname => 'SCOTT', tabname =>
'EMP', estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,
method_opt => 'FOR ALL COLUMNS SIZE AUTO', cascade => TRUE)
Rationale
---------
The optimizer requires up-to-date statistics for the table and its indices
in order to select a good execution plan.
2- Restructure SQL finding (see plan 1 in explain plans section)
----------------------------------------------------------------
The predicate NVL("E"."EMPNO",0)=:B1 used at line ID 2 of the execution plan
contains an expression on indexed column "EMPNO". This expression prevents
the optimizer from selecting indices on table "SCOTT"."EMP".
Recommendation
--------------
Rewrite the predicate into an equivalent form to take advantage of
indices. Alternatively, create a function-based index on the expression.
Rationale
---------
The optimizer is unable to use an index if the predicate is an inequality
condition or if there is an expression or an implicit data type conversion
on the indexed column.
-------------------------------------------------------------------------------
EXPLAIN PLANS SECTION
-------------------------------------------------------------------------------
1- Original
-----------
Plan hash value: 1863486531
----------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 107 | 4 (0)| 00:00:01 |
| 1 | NESTED LOOPS | | 1 | 107 | 4 (0)| 00:00:01 |
| 2 | TABLE ACCESS FULL | EMP | 1 | 87 | 3 (0)| 00:00:01 |
| 3 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)| 00:00:01 |
| 4 | INDEX UNIQUE SCAN | PK_DEPT | 1 | | 0 (0)| 00:00:01 |
----------------------------------------------------------------------------------------
Note
-----
- dynamic sampling used for this statement
-------------------------------------------------------------------------------
1 row selected.
Once the tuning session is over the tuning task can be dropped using the DROP_TUNING_TASK procedure:
BEGIN DBMS_SQLTUNE.drop_tuning_task (task_name => '19v5guvsgcd1v_AWR_tuning_task'); DBMS_SQLTUNE.drop_tuning_task (task_name => '19v5guvsgcd1v_tuning_task'); DBMS_SQLTUNE.drop_tuning_task (task_name => 'sqlset_tuning_task'); DBMS_SQLTUNE.drop_tuning_task (task_name => 'emp_dept_tuning_task'); END; /
Managing SQL Profiles
To manage SQL profiles a user needs the following privileges:
CONN sys/password AS SYSDBA GRANT CREATE ANY SQL PROFILE TO scott; GRANT DROP ANY SQL PROFILE TO scott; GRANT ALTER ANY SQL PROFILE TO scott; CONN scott/tiger
If the recommendations of the SQL tuning advisor include a suggested profile you can choose to accept it using the ACCEPT_SQL_PROFILE procedure:
SET SERVEROUTPUT ON
DECLARE
l_sql_tune_task_id VARCHAR2(20);
BEGIN
l_sql_tune_task_id := DBMS_SQLTUNE.accept_sql_profile (
task_name => 'emp_dept_tuning_task',
name => 'emp_dept_profile');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/
The NAME parameter is used to specify a name for the profile. If it is not specified a system generated name will be used.
The STATUS, NAME, DESCRIPTION, and CATEGORY attributes of an SQL profile can be altered using the ALTER_SQL_PROFILE procedure:
BEGIN
DBMS_SQLTUNE.alter_sql_profile (
name => 'emp_dept_profile',
attribute_name => 'STATUS',
value => 'DISABLED');
END;
/
Existing SQL profiles can be dropped using the DROP_SQL_PROFILE procedure:
BEGIN
DBMS_SQLTUNE.drop_sql_profile (
name => 'emp_dept_profile',
ignore => TRUE);
END;
/
The IGNORE parameter prevents errors being reported if the specified profile does not exist.
SQL Tuning Sets
An SQL tuning set is a group of statements along with their execution context. These can be created automatically via Enterprise Manager or manually provided you have the necessary privileges:
CONN sys/password AS SYSDBA GRANT ADMINISTER ANY SQL TUNING SET TO scott; CONN scott/tiger
An SQL tuning set is created using the CREATE_SQLSET procedure:
BEGIN
DBMS_SQLTUNE.create_sqlset (
sqlset_name => 'test_sql_tuning_set',
description => 'A test SQL tuning set.');
END;
/
Statements are added to the set using the LOAD_SQLSET procedure which accepts a REF CURSOR of statements retrieved using one of the following pipelined functions:
SELECT_WORKLOAD_REPOSITORY8211; Retrieves statements from the Automatic Workload Repository (AWR).SELECT_CURSOR_CACHE8211; Retrieves statements from the cursor cache.SELECT_SQLSET8211; Retrieves statements from another SQL tuning set.
The following are examples of their usage:
-- Load the SQL set from the Automatic Workload Repository (AWR).
DECLARE
l_cursor DBMS_SQLTUNE.sqlset_cursor;
BEGIN
OPEN l_cursor FOR
SELECT VALUE(p)
FROM TABLE (DBMS_SQLTUNE.select_workload_repository (
765, -- begin_snap
766, -- end_snap
NULL, -- basic_filter
NULL, -- object_filter
NULL, -- ranking_measure1
NULL, -- ranking_measure2
NULL, -- ranking_measure3
NULL, -- result_percentage
10) -- result_limit
) p;
DBMS_SQLTUNE.load_sqlset (
sqlset_name => 'test_sql_tuning_set',
populate_cursor => l_cursor);
END;
/
-- Load the SQL set from the cursor cache.
DECLARE
l_cursor DBMS_SQLTUNE.sqlset_cursor;
BEGIN
OPEN l_cursor FOR
SELECT VALUE(p)
FROM TABLE (DBMS_SQLTUNE.select_cursor_cache (
NULL, -- basic_filter
NULL, -- object_filter
NULL, -- ranking_measure1
NULL, -- ranking_measure2
NULL, -- ranking_measure3
NULL, -- result_percentage
1) -- result_limit
) p;
DBMS_SQLTUNE.load_sqlset (
sqlset_name => 'test_sql_tuning_set',
populate_cursor => l_cursor);
END;
/
-- Create a new set and load it from the existing one.
DECLARE
l_cursor DBMS_SQLTUNE.sqlset_cursor;
BEGIN
DBMS_SQLTUNE.create_sqlset(
sqlset_name => 'test_sql_tuning_set_2',
description => 'Another test SQL tuning set.');
OPEN l_cursor FOR
SELECT VALUE(p)
FROM TABLE (DBMS_SQLTUNE.select_sqlset (
'test_sql_tuning_set', -- sqlset_name
NULL, -- basic_filter
NULL, -- object_filter
NULL, -- ranking_measure1
NULL, -- ranking_measure2
NULL, -- ranking_measure3
NULL, -- result_percentage
NULL) -- result_limit
) p;
DBMS_SQLTUNE.load_sqlset (
sqlset_name => 'test_sql_tuning_set_2',
populate_cursor => l_cursor);
END;
/
The contents of an SQL tuning set can be displayed using the SELECT_SQLSET function:
SELECT *
FROM TABLE(DBMS_SQLTUNE.select_sqlset ('test_sql_tuning_set'));
References can be added to a set to indicate its usage by a client using the ADD_SQLSET_REFERENCE function. The resulting reference ID can be used to remove it using the REMOVE_SQLSET_REFERENCE procedure:
DECLARE
l_ref_id NUMBER;
BEGIN
-- Add a reference to a set.
l_ref_id := DBMS_SQLTUNE.add_sqlset_reference (
sqlset_name => 'test_sql_tuning_set',
reference => 'Used for manual tuning by SQL*Plus.');
-- Delete the reference.
DBMS_SQLTUNE.remove_sqlset_reference (
sqlset_name => 'test_sql_tuning_set',
reference_id => l_ref_id);
END;
/
The UPDATE_SQLSET procedure is used to update specific string (MODULE and ACTION) and number (PRIORITY and PARSING_SCHEMA_ID) attributes of specific statements within a set:
BEGIN
DBMS_SQLTUNE.update_sqlset (
sqlset_name => 'test_sql_tuning_set',
sql_id => '19v5guvsgcd1v',
attribute_name => 'ACTION',
attribute_value => 'INSERT');
END;
/
The contents of a set can be trimmed down or deleted completely using the DELETE_SQLSET procedure:
BEGIN
-- Delete statements with less than 50 executions.
DBMS_SQLTUNE.delete_sqlset (
sqlset_name => 'test_sql_tuning_set',
basic_filter => 'executions < 50');
-- Delete all statements.
DBMS_SQLTUNE.delete_sqlset (
sqlset_name => 'test_sql_tuning_set');
END;
/
Tuning sets can be dropped using the DROP_SQLSET procedure:
BEGIN DBMS_SQLTUNE.drop_sqlset (sqlset_name => 'test_sql_tuning_set'); DBMS_SQLTUNE.drop_sqlset (sqlset_name => 'test_sql_tuning_set_2'); END; /
Useful Views
Useful views related to automatic SQL tuning include:
DBA_ADVISOR_TASKSDBA_ADVISOR_FINDINGSDBA_ADVISOR_RECOMMENDATIONSDBA_ADVISOR_RATIONALEDBA_SQLTUNE_STATISTICSDBA_SQLTUNE_BINDSDBA_SQLTUNE_PLANSDBA_SQLSETDBA_SQLSET_BINDSDBA_SQLSET_STATEMENTSDBA_SQLSET_REFERENCESDBA_SQL_PROFILESV$SQLV$SQLAREAV$ACTIVE_SESSION_HISTORY
Automatic Workload Repository (AWR) in Oracle Database 10g
Oracle have provided many performance gathering and reporting tools over the years. Originally the UTLBSTAT/UTLESTAT scripts were used to monitor performance metrics. Oracle8i introduced the Statspack functionality which Oracle9i extended. In Oracle 10g statspack has evolved into the Automatic Workload Repository (AWR).
- AWR Features
- Snapshots
- Baselines
- Workload Repository Views
- Workload Repository Reports
- Enterprise Manager
Related articles.
AWR Features
The AWR is used to collect performance statistics including:
- Wait events used to identify performance problems.
- Time model statistics indicating the amount of DB time associated with a process from the
V$SESS_TIME_MODELandV$SYS_TIME_MODELviews. - Active Session History (ASH) statistics from the
V$ACTIVE_SESSION_HISTORYview. - Some system and session statistics from the
V$SYSSTATandV$SESSTATviews. - Object usage statistics.
- Resource intensive SQL statements.
The repository is a source of information for several other Oracle 10g features including:
- Automatic Database Diagnostic Monitor
- SQL Tuning Advisor
- Undo Advisor
- Segment Advisor
Snapshots
By default snapshots of the relevant data are taken every hour and retained for 7 days. The default values for these settings can be altered using the following procedure.
BEGIN
DBMS_WORKLOAD_REPOSITORY.modify_snapshot_settings(
retention => 43200, -- Minutes (= 30 Days). Current value retained if NULL.
interval => 30); -- Minutes. Current value retained if NULL.
END;
/
The changes to the settings are reflected in the DBA_HIST_WR_CONTROL view. Typically the retention period should capture at least one complete workload cycle. If you system has monthly archive and loads a 1 month retention time would be more beneficial that the default 7 days. An interval of 8220;08243; switches off snapshot collection, which in turn stops much of the self-tuning functionality, hence this is not recommended. Automatic collection is only possible if the STATISTICS_LEVEL parameter is set to TYPICAL or ALL. If the value is set to BASIC manual snapshots can be taken, but they will be missing some statistics.
Extra snapshots can be taken and existing snapshots can be removed, as shown below.
EXEC DBMS_WORKLOAD_REPOSITORY.create_snapshot;
BEGIN
DBMS_WORKLOAD_REPOSITORY.drop_snapshot_range (
low_snap_id => 22,
high_snap_id => 32);
END;
/
Snapshot information can be queried from the DBA_HIST_SNAPSHOT view.
Baselines
A baseline is a pair of snapshots that represents a specific period of usage. Once baselines are defined they can be used to compare current performance against similar periods in the past. You may wish to create baseline to represent a period of batch processing.
BEGIN
DBMS_WORKLOAD_REPOSITORY.create_baseline (
start_snap_id => 210,
end_snap_id => 220,
baseline_name => 'batch baseline');
END;
/
The pair of snapshots associated with a baseline are retained until the baseline is explicitly deleted.
BEGIN
DBMS_WORKLOAD_REPOSITORY.drop_baseline (
baseline_name => 'batch baseline',
cascade => FALSE); -- Deletes associated snapshots if TRUE.
END;
/
Baseline information can be queried from the DBA_HIST_BASELINE view.
Workload Repository Views
The following workload repository views are available:
V$ACTIVE_SESSION_HISTORY8211; Displays the active session history (ASH) sampled every second.V$METRIC8211; Displays metric information.V$METRICNAME8211; Displays the metrics associated with each metric group.V$METRIC_HISTORY8211; Displays historical metrics.V$METRICGROUP8211; Displays all metrics groups.DBA_HIST_ACTIVE_SESS_HISTORY8211; Displays the history contents of the active session history.DBA_HIST_BASELINE8211; Displays baseline information.DBA_HIST_DATABASE_INSTANCE8211; Displays database environment information.DBA_HIST_SNAPSHOT8211; Displays snapshot information.DBA_HIST_SQL_PLAN8211; Displays SQL execution plans.DBA_HIST_WR_CONTROL8211; Displays AWR settings.
Workload Repository Reports
Oracle provide two scripts to produce workload repository reports (awrrpt.sql and awrrpti.sql). They are similar in format to the statspack reports and give the option of HTML or plain text formats. The two reports give essential the same output but the awrrpti.sql allows you to select a single instance. The reports can be generated as follows.
@$ORACLE_HOME/rdbms/admin/awrrpt.sql @$ORACLE_HOME/rdbms/admin/awrrpti.sql
The scripts prompt you to enter the report format (html or text), the start snapshot id, the end snapshot id and the report filename. The resulting report can be opend in a browser or text editor accordingly.
Enterprise Manager
The automated workload repository administration tasks have been included in Enterprise Manager. The 8220;Automatic Workload Repository8221; page is accessed from the main page by clicking on the 8220;Administration8221; link, then the 8220;Workload Repository8221; link under the 8220;Workload8221; section. The page allows you to modify AWR settings or manage snapshots without using the PL/SQL APIs.
December 10, 2011 Articles 0 0
Automating Database Startup and Shutdown on Linux
When using RAC or ASM under Oracle 10g Release 2 or above, the Oracle Clusterware automatically starts and stops the Oracle database instances, so the following procedures are not necessary. For all other cases, you can use the methods described below.
- The 8220;su8221; Command
- The 8220;rsh8221; Command
- Known Issues
The 8220;su8221; Command
The following represents the Oracle recommended method for automating database startup and shutdown of Oracle 9i instances.
Once the instance is created, edit the 8220;/etc/oratab8221; file setting the restart flag for each instance to 8216;Y8217;.
TSH1:/u01/app/oracle/product/9.2.0:Y
Next, create a file called 8220;/etc/init.d/dbora8221; as the root user, containing the following.
#!/bin/sh
# chkconfig: 345 99 10
# description: Oracle auto start-stop script.
#
# Set ORA_HOME to be equivalent to the $ORACLE_HOME
# from which you wish to execute dbstart and dbshut;
#
# Set ORA_OWNER to the user id of the owner of the
# Oracle database in ORA_HOME.
ORA_HOME=/u01/app/oracle/product/9.2.0
ORA_OWNER=oracle
if [ ! -f $ORA_HOME/bin/dbstart ]
then
echo "Oracle startup: cannot start"
exit
fi
case "$1" in
'start')
# Start the Oracle databases:
# The following command assumes that the oracle login
# will not prompt the user for any values
su - $ORA_OWNER -c "$ORA_HOME/bin/lsnrctl start"
su - $ORA_OWNER -c $ORA_HOME/bin/dbstart
touch /var/lock/subsys/dbora
;;
'stop')
# Stop the Oracle databases:
# The following command assumes that the oracle login
# will not prompt the user for any values
su - $ORA_OWNER -c $ORA_HOME/bin/dbshut
su - $ORA_OWNER -c "$ORA_HOME/bin/lsnrctl stop"
rm -f /var/lock/subsys/dbora
;;
esac
Use the chmod command to set the privileges to 750.
chmod 750 /etc/init.d/dbora
Associate the dbora service with the appropriate run levels and set it to auto-start using the following command.
chkconfig --add dbora
The relevant instances should now startup/shutdown automatically at system startup/shutdown.
This method can still be used under Oracle 10g and 11g, provided the 8220;ORA_HOME8221; variable is amended to use the correct path and this is added to the end of the dbstart and dbshut lines. The lines to start and stop the listener can be removed under Oracle 10g release 2, as the dbstart command includes an automatic start of the listener.
#!/bin/sh
# chkconfig: 345 99 10
# description: Oracle auto start-stop script.
#
# Set ORA_HOME to be equivalent to the $ORACLE_HOME
# from which you wish to execute dbstart and dbshut;
#
# Set ORA_OWNER to the user id of the owner of the
# Oracle database in ORA_HOME.
ORA_HOME=/u01/app/oracle/product/10.2.0/db_1
#ORA_HOME=/u01/app/oracle/product/11.1.0/db_1
#ORA_HOME=/u01/app/oracle/product/11.2.0/db_1
ORA_OWNER=oracle
if [ ! -f $ORA_HOME/bin/dbstart ]
then
echo "Oracle startup: cannot start"
exit
fi
case "$1" in
'start')
# Start the Oracle databases:
# The following command assumes that the oracle login
# will not prompt the user for any values
su - $ORA_OWNER -c "$ORA_HOME/bin/dbstart $ORA_HOME"
touch /var/lock/subsys/dbora
;;
'stop')
# Stop the Oracle databases:
# The following command assumes that the oracle login
# will not prompt the user for any values
su - $ORA_OWNER -c "$ORA_HOME/bin/dbshut $ORA_HOME"
rm -f /var/lock/subsys/dbora
;;
esac
The 8220;rsh8221; Command
With Oracle 10g, Oracle switched from recommending the 8220;su8221; command to the 8220;rsh8221; command. In Oracle 10g release 2, the dbstart command includes an automatic start of the listener, so there are some differences between the two versions, but the following represents the preferred method for Oracle 10g.
Once the instance is created, edit the 8220;/etc/oratab8221; file setting the restart flag for each instance to 8216;Y8217;.
TSH1:/u01/app/oracle/product/9.2.0:Y
Next, create a file called 8220;/etc/init.d/dbora8221; as the root user, containing the following.
#!/bin/sh
# chkconfig: 345 99 10
# description: Oracle auto start-stop script.
#
# Change the value of ORACLE_HOME to specify the correct Oracle home
# directory for your installation.
ORACLE_HOME=/u01/app/oracle/product/10.2.0/db_1
#
# Change the value of ORACLE to the login name of the
# oracle owner at your site.
#
ORACLE=oracle
PATH=${PATH}:$ORACLE_HOME/bin
HOST=`hostname`
PLATFORM=`uname`
export ORACLE_HOME PATH
#
if [ ! "$2" = "ORA_DB" ] ; then
if [ "$PLATFORM" = "HP-UX" ] ; then
remsh $HOST -l $ORACLE -n "$0 $1 ORA_DB"
exit
else
rsh $HOST -l $ORACLE $0 $1 ORA_DB
exit
fi
fi
#
case $1 in
'start')
$ORACLE_HOME/bin/dbstart $ORACLE_HOME
touch /var/lock/subsys/dbora
;;
'stop')
$ORACLE_HOME/bin/dbshut $ORACLE_HOME
rm -f /var/lock/subsys/dbora
;;
*)
echo "usage: $0 {start|stop}"
exit
;;
esac
#
exit
Use the chmod command to set the privileges to 750.
chmod 750 /etc/init.d/dbora
Associate the dbora service with the appropriate run levels and set it to auto-start using the following command.
chkconfig --add dbora
The relevant instances should now startup/shutdown automatically at system startup/shutdown.
This method relies on the presence of an RSH server, which requires additional packages and configuration.
# Install the rhs and rsh-server packages from the OS CD/DVD. rpm -Uvh --force rsh-* # Enable rsh and rlogin. chkconfig rsh on chkconfig rlogin on service xinetd reload
This can be quite problematic when attempting to use this method under later Linux distributions, where rsh is deprecated. As a result, I prefer to use the 8220;su8221; command method.
This method can also be used for 11g databases that are not using ASM or RAC.
Known Issues
When using Oracle 10g Release 2, calling dbstart might result in the following error message.
Failed to auto-start Oracle Net Listener using /ade/vikrkuma_new/oracle/bin/tnslsnr
This is due to a hard coded path in the dbstart script. You should not see this error if you pass the 8220;$ORACLE_HOME8221; as a parameter to dbstart and dbshut. To correct this, edit the 8220;$ORACLE_HOME/bin/dbstart8221; script and replace the following line (approximately line 78).
ORACLE_HOME_LISTNER=/ade/vikrkuma_new/oracle
With this.
ORACLE_HOME_LISTNER=$ORACLE_HOME
The dbstart script should now start the listener as expected.
AWR Baseline Enhancements in Oracle Database 11g Release 1
The Automatic Workload Repository (AWR) was introduced in Oracle 10g and included some simple baseline functionality. Creating a baseline allowed a specified range of snapshots to be retained, regardless of the AWR retention policy, and used for performance comparisons. This functionality, and the DBMS_WORKLOAD_REPOSITORY package that manages it, has been extended in Oracle 11g.
Note. Most of the procedures and functions in the DBMS_WORKLOAD_REPOSITORY package accept a DBID parameter, which defaults to the local database identifier. For that reason the following examples will omit this parameter.
- Fixed Baselines
- The Moving Window Baseline
- Baseline Templates
- Baseline Metric Thresholds
Fixed Baselines
The fixed, or static, baseline functionality is a little more flexible in Oracle 11g compared to that of Oracle 10g. Originally, the DBMS_WORKLOAD_REPOSITORY package included a single CREATE_BASELINE procedure allowing you to define baselines using specific snapshot IDs. It now includes overloaded procedures and functions allowing baselines to be created using start and end times, which are used to estimate the relevant snapshot IDs. The functions have the same parameter lists as the procedures, but return the baseline ID. By default baselines are kept forever, but the new expiration parameter allows them to be automatically expired after a specified number of days.
SET SERVEROUTPUT ON
DECLARE
l_return NUMBER;
BEGIN
-- Using procedures.
DBMS_WORKLOAD_REPOSITORY.create_baseline(
start_snap_id => 2490,
end_snap_id => 2491,
baseline_name => 'test1_bl',
expiration => 60);
DBMS_WORKLOAD_REPOSITORY.create_baseline(
start_time => TO_DATE('09-JUL-2008 17:00', 'DD-MON-YYYY HH24:MI'),
end_time => TO_DATE('09-JUL-2008 18:00', 'DD-MON-YYYY HH24:MI'),
baseline_name => 'test2_bl',
expiration => NULL);
-- Using functions.
l_return := DBMS_WORKLOAD_REPOSITORY.create_baseline(
start_snap_id => 2492,
end_snap_id => 2493,
baseline_name => 'test3_bl',
expiration => 30);
DBMS_OUTPUT.put_line('Return: ' || l_return);
l_return := DBMS_WORKLOAD_REPOSITORY.create_baseline(
start_time => TO_DATE('09-JUL-2008 19:00', 'DD-MON-YYYY HH24:MI'),
end_time => TO_DATE('09-JUL-2008 20:00', 'DD-MON-YYYY HH24:MI'),
baseline_name => 'test4_bl',
expiration => NULL);
DBMS_OUTPUT.put_line('Return: ' || l_return);
END;
/
Return: 8
Return: 9
PL/SQL procedure successfully completed.
SQL>
The new baselines are visible in DBA_HIST_BASELINE view.
COLUMN baseline_name FORMAT A15
SELECT baseline_id, baseline_name, START_SNAP_ID,
TO_CHAR(start_snap_time, 'DD-MON-YYYY HH24:MI') AS start_snap_time,
END_SNAP_ID,
TO_CHAR(end_snap_time, 'DD-MON-YYYY HH24:MI') AS end_snap_time
FROM dba_hist_baseline
WHERE baseline_type = 'STATIC'
ORDER BY baseline_id;
BASELINE_ID BASELINE_NAME START_SNAP_ID START_SNAP_TIME END_SNAP_ID END_SNAP_TIME
----------- --------------- ------------- ----------------- ----------- -----------------
6 test1_bl 2490 09-JUL-2008 17:00 2491 09-JUL-2008 18:00
7 test2_bl 2490 09-JUL-2008 17:00 2491 09-JUL-2008 18:00
8 test3_bl 2492 09-JUL-2008 19:00 2493 09-JUL-2008 20:00
9 test4_bl 2492 09-JUL-2008 19:00 2493 09-JUL-2008 20:00
4 rows selected.
SQL>
Information about a specific baseline can be displayed by using the BASELINE_ID with the SELECT_BASELINE_DETAILS pipelined table function, or the BASELINE_NAME with the SELECT_BASELINE_METRIC pipelined table function.
SELECT *
FROM TABLE(DBMS_WORKLOAD_REPOSITORY.select_baseline_details(6));
SELECT *
FROM TABLE(DBMS_WORKLOAD_REPOSITORY.select_baseline_metric('SYSTEM_MOVING_WINDOW'));
Baselines are renamed using the RENAME_BASELINE procedure.
BEGIN
DBMS_WORKLOAD_REPOSITORY.rename_baseline(
old_baseline_name => 'test4_bl',
new_baseline_name => 'test5_bl');
END;
/
Baselines are dropped using the DROP_BASELINE procedure.
BEGIN DBMS_WORKLOAD_REPOSITORY.drop_baseline(baseline_name => 'test1_bl'); DBMS_WORKLOAD_REPOSITORY.drop_baseline(baseline_name => 'test2_bl'); DBMS_WORKLOAD_REPOSITORY.drop_baseline(baseline_name => 'test3_bl'); DBMS_WORKLOAD_REPOSITORY.drop_baseline(baseline_name => 'test5_bl'); END; /
Enterprise Manager is probably the most convenient way to manage AWR baselines. From the 8220;AWR Baselines8221; screen (Server > AWR Baselines), click the 8220;Create8221; button.
Select the interval type of 8220;Single8221; and click the 8220;Continue8221; button.
Enter a name for the baseline and mark the start and end of the baseline by either clicking on the snapshot icons or entering the time range manually, then click the 8220;Finish8221; button.
The newly created baseline is now displayed in the 8220;AWR Baselines8221; screen.
The baseline is renamed or dropped by checking its 8220;Select8221; box and clicking the 8220;Edit8221; or 8220;Delete8221; button respectively. Once the baseline is created you can schedule statistics computation by checking its 8220;Select8221; box, selecting 8220;Schedule Statistics Computation8221; in the drop down list, then clicking 8220;Go8221; button.
The Moving Window Baseline
Oracle 11g introduces the concept of a moving window baseline, which is used to calculate metrics for the adaptive thresholds. The window is a view of the AWR data within the retention period. The default size of the window matches the default AWR retention period of 8 days, but it can be set as a subset of this value. Before you can increase the size of the window you must first increase the size of the AWR retention period.
The current AWR retention period can be displayed by querying the RETENTION column of the DBA_HIST_WR_CONTROL view.
SELECT retention FROM dba_hist_wr_control; RETENTION --------------------------------------------------------------------------- +00008 00:00:00.0 1 row selected. SQL>
The retention period is altered using the MODIFY_SNAPSHOT_SETTINGS procedure, which accepts a RETENTION parameter in minutes.
BEGIN
DBMS_WORKLOAD_REPOSITORY.modify_snapshot_settings(
retention => 43200); -- Minutes (= 30 Days).
END;
/
SELECT retention FROM dba_hist_wr_control;
RETENTION
---------------------------------------------------------------------------
+00030 00:00:00.0
1 row selected.
SQL>
The current moving window size is displayed by querying the DBA_HIST_BASELINE view.
SELECT moving_window_size
FROM dba_hist_baseline
WHERE baseline_type = 'MOVING_WINDOW';
MOVING_WINDOW_SIZE
------------------
8
1 row selected.
SQL>
The size of the moving window baseline is altered using the MODIFY_BASELINE_WINDOW_SIZE procedure, which accepts a WINDOW_SIZE parameter in days.
BEGIN
DBMS_WORKLOAD_REPOSITORY.modify_baseline_window_size(
window_size => 20);
END;
/
SELECT moving_window_size
FROM dba_hist_baseline
WHERE baseline_type = 'MOVING_WINDOW';
MOVING_WINDOW_SIZE
------------------
20
1 row selected.
SQL>
Oracle recommend of window size greater than or equal to 30 days when using adaptive thresholds.
To adjust the retention periods in Enterprise Manager, click on the 8220;Edit8221; button in the 8220;Automatic Workload Repository8221; screen (Server > Automatic Workload Repository).
Edit the 8220;Use Time-Based Retention8221; to the appropriate number of days and click the 8220;OK8221; button.
Next, navigate to the 8220;AWR baselines8221; screen (Server > AWR Baselines), select the 8220;SYSTEM_MOVING_WINDOW8221; baseline and click the 8220;Edit8221; button.
Set the appropriate 8220;Window Size8221; and click the 8220;Apply8221; button.
Baseline Templates
Baseline templates allow you to define baselines you would like to capture in the future. Overloads of the CREATE_BASELINE_TEMPLATE procedure define the capture of individual baselines, or repeating baselines. Creating a single baseline template is similar to creating a time-based baseline, except the time is in the future.
BEGIN
DBMS_WORKLOAD_REPOSITORY.create_baseline_template(
start_time => TO_DATE('01-DEC-2008 00:00', 'DD-MON-YYYY HH24:MI'),
end_time => TO_DATE('01-DEC-2008 05:00', 'DD-MON-YYYY HH24:MI'),
baseline_name => '01_dec_008_00_05_bl',
template_name => '01_dec_008_00_05_tp',
expiration => 100);
END;
/
Templates for repeating baselines are a little different as they require some basic scheduling information. The START_TIME and END_TIME parameters define when the template is activated and deactivated. The DAY_OF_WEEK, HOUR_IN_DAY and DURATION parameters define the day (MONDAY 8211; SUNDAY or ALL) the baselines are generated on and the start and end point of the baseline. Since the template will generate multiple baselines, the baseline name is derived from the BASELINE_NAME_PREFIX concatenated to the date. The following example creates a template that will run for the next six months, gathering a baseline every Monday between 00:00 and 05:00.
BEGIN DBMS_WORKLOAD_REPOSITORY.create_baseline_template( day_of_week => 'MONDAY', hour_in_day => 0, duration => 5, start_time => SYSDATE, end_time => ADD_MONTHS(SYSDATE, 6), baseline_name_prefix => 'monday_morning_bl_', template_name => 'monday_morning_tp', expiration => NULL); END; /
Information about baseline templates is displayed using the DBA_HIST_BASELINE_TEMPLATE view.
SELECT template_name,
template_type,
baseline_name_prefix,
start_time,
end_time,
day_of_week,
hour_in_day,
duration,
expiration
FROM dba_hist_baseline_template;
TEMPLATE_NAME TEMPLATE_ BASELINE_NAME_PREFIX START_TIME
------------------------------ --------- ------------------------------ --------------------
END_TIME DAY_OF_WE HOUR_IN_DAY DURATION EXPIRATION
-------------------- --------- ----------- ---------- ----------
01_dec_008_00_05_tp SINGLE 01_dec_008_00_05_bl 01-DEC-2008 00:00:00
01-DEC-2008 05:00:00 100
monday_morning_tp REPEATING monday_morning_bl_ 11-JUL-2008 14:43:36
11-JAN-2009 14:43:36 MONDAY 0 5
2 rows selected.
SQL>
Notice the BASELINE_NAME_PREFIX column holds either the prefix or full baseline name depending on the type of baseline being captured.
Baseline templates are dropped using the DROP_BASELINE_TEMPLATE procedure.
BEGIN DBMS_WORKLOAD_REPOSITORY.drop_baseline_template (template_name => '01_dec_008_00_05_tp'); DBMS_WORKLOAD_REPOSITORY.drop_baseline_template (template_name => 'monday_morning_tp'); END; /
Enterprise Manager uses the same screens for creating single baseline templates as it does for creating baselines. Navigate to the 8220;AWR Baselines8221; screen (Server > AWR Baselines) and click the 8220;Create8221; button.

Select the interval type of 8220;Single8221; and click the 8220;Continue8221; button.
Enter a name for the baseline template and mark the start and end of the baseline by entering the time range manually, then click the 8220;Finish8221; button. If the time range is in the future, a baseline template is automatically created, rather than a regular baseline.
To view the baseline template, click the 8220;AWR Baseline Templates8221; link at the bottom of the 8220;AWR baselines8221; screen.
To creating the repeating baseline templates, start the baseline creation as before, but select the interval type of 8220;Repeating8221; and click the 8220;Continue8221; button.
Enter the baseline name prefix, which is also used as the template name, along with the interval and scheduling details, then click the 8220;Finish8221; button.
Once again, the baseline template is visible on the 8220;AWR Baseline Templates8221; screen.
Baseline Metric Thresholds
Oracle 11g simplifies the definition of metric thresholds by allowing them to be applied to baselines, including the moving window baseline. The easiest way to start using baseline metric thresholds is to click the 8220;Quick Configuration8221; button on the 8220;Baseline Metric Thresholds8221; screen (Home > Baseline Metric Thresholds).
Select the relevant 8220;Workload Profile8221; for your system, then click the 8220;Continue8221; button.
Click the 8220;Finish8221; button on the review screen.
The adaptive thresholds are then visible on the 8220;Baseline Metric Thresholds8221; screen. Click the category name or 8220;Edit Threshold8221; icon to edit the threshold settings.
If you need to amend the threshold settings, remember to click the 8220;Apply Thresholds8221; button once you have finished.
Datatypes
Each value manipulated by Oracle Database has a datatype. The datatype of a value associates a fixed set of properties with the value. These properties cause Oracle to treat values of one datatype differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW datatype.
When you create a table or cluster, you must specify a datatype for each of its columns. When you create a procedure or stored function, you must specify a datatype for each of its arguments. These datatypes define the domain of values that each column can contain or each argument can have. For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values 2 or 8216;SHOE8217;. Each value subsequently placed in a column assumes the datatype of the column. For example, if you insert '01-JAN-98' into a DATE column, then Oracle treats the '01-JAN-98' character string as a DATE value after verifying that it translates to a valid date.
Oracle Database provides a number of built-in datatypes as well as several categories for user-defined types that can be used as datatypes. The syntax of Oracle datatypes appears in the diagrams that follow. The text of this section is divided into the following sections:
- Oracle Built-in Datatypes
- ANSI, DB2, and SQL/DS Datatypes
- User-Defined Types
- Oracle-Supplied Types
- Datatype Comparison Rules
- Data Conversion
A datatype is either scalar or nonscalar. A scalar type contains an atomic value, whereas a nonscalar (sometimes called a 8220;collection8221;) contains a set of values. A large object (LOB) is a special form of scalar datatype representing a large scalar value of binary or character data. LOBs are subject to some restrictions that do not affect other scalar types because of their size. Those restrictions are documented in the context of the relevant SQL syntax.
The Oracle precompilers recognize other datatypes in embedded SQL programs. These datatypes are called external datatypes and are associated with host variables. Do not confuse built-in datatypes and user-defined types with external datatypes.

Description of the illustration datatypes.gif
Oracle_built_in_datatypes::=

Description of the illustration Oracle_built_in_datatypes.gif
For descriptions of the Oracle built-in datatypes, please refer to 8220;Oracle Built-in Datatypes8221;.

Description of the illustration character_datatypes.gif
number_datatypes::=

Description of the illustration number_datatypes.gif
long_and_raw_datatypes::=

Description of the illustration long_and_raw_datatypes.gif
datetime_datatypes::=

Description of the illustration datetime_datatypes.gif
large_object_datatypes::=

Description of the illustration large_object_datatypes.gif
rowid_datatypes::=

Description of the illustration rowid_datatypes.gif
The ANSI-supported datatypes appear in the figure that follows. 8220;ANSI, DB2, and SQL/DS Datatypes8221; discusses the mapping of ANSI-supported datatypes to Oracle built-in datatypes.

Description of the illustration ANSI_supported_datatypes.gif
Oracle_supplied_types::=

Description of the illustration Oracle_supplied_types.gif
For a description of the expression_filter_type, please refer to 8220;Expression Filter Type8221;. Other Oracle-supplied types follow:

Description of the illustration any_types.gif
For descriptions of the Any types, please refer to 8220;Any Types8221;.

Description of the illustration XML_types.gif
For descriptions of the XML types, please refer to 8220;XML Types8221;.

Description of the illustration spatial_types.gif
For descriptions of the spatial types, please refer to 8220;Spatial Types8221;.

Description of the illustration media_types.gif
still_image_object_types::=

Description of the illustration still_image_object_types.gif
For descriptions of the media types, please refer to 8220;Media Types8221;.
Oracle Built-in Datatypes
The table that follows summarizes Oracle built-in datatypes. Please refer to the syntax in the preceding sections for the syntactic elements. The codes listed for the datatypes are used internally by Oracle Database. The datatype code of a column or object attribute is returned by the DUMP function.
Table 2-1 Built-in Datatype Summary
| Code | Datatype | Description |
|---|---|---|
| 1 | VARCHAR2(size [BYTE | CHAR]) |
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2.BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics. |
| 1 | NVARCHAR2(size) |
Variable-length Unicode character string having maximum length size characters. The number of bytes can be up to two times size for AL16UTF16 encoding and three times size for UTF8 encoding. Maximum size is determined by the national character set definition, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. |
| 2 | NUMBER[(precision [, scale]]) |
Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127. |
| 8 | LONG |
Character data of variable length up to 2 gigabytes, or 231 -1 bytes. Provided for backward compatibility. |
| 12 | DATE |
Valid date range from January 1, 4712 BC to December 31, 9999 AD. The default format is determined explicitly by the NLS_DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is fixed at 7 bytes. This datatype contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It does not have fractional seconds or a time zone. |
| 21 | BINARY_FLOAT |
32-bit floating point number. This datatype requires 5 bytes, including the length byte. |
| 22 | BINARY_DOUBLE |
64-bit floating point number. This datatype requires 9 bytes, including the length byte. |
| 180 | TIMESTAMP [(fractional_seconds)] |
Year, month, and day values of date, as well as hour, minute, and second values of time, where fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values of fractional_seconds_precision are 0 to 9. The default is 6. The default format is determined explicitly by the NLS_DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The sizes varies from 7 to 11 bytes, depending on the precision. This datatype contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It contains fractional seconds but does not have a time zone. |
| 181 | TIMESTAMP [(fractional_seconds)] WITH TIME ZONE |
All values of TIMESTAMP as well as time zone displacement value, where fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 0 to 9. The default is 6. The default format is determined explicitly by the NLS_DATE_FORMAT parameter or implicitly by the NLS_TERRITORY parameter. The size is fixed at 13 bytes. This datatype contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR, and TIMEZONE_MINUTE. It has fractional seconds and an explicit time zone. |
| 231 | TIMESTAMP [(fractional_seconds)] WITH LOCAL TIME ZONE |
All values of TIMESTAMP WITH TIME ZONE, with the following exceptions:
The default format is determined explicitly by the |
| 182 | INTERVAL YEAR [(year_precision)] TO MONTH |
Stores a period of time in years and months, where year_precision is the number of digits in the YEAR datetime field. Accepted values are 0 to 9. The default is 2. The size is fixed at 5 bytes. |
| 183 | INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds)] |
Stores a period of time in days, hours, minutes, and seconds, where
The size is fixed at 11 bytes. |
| 23 | RAW(size) |
Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. |
| 24 | LONG RAW |
Raw binary data of variable length up to 2 gigabytes. |
| 69 | ROWID |
Base 64 string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. |
| 208 | UROWID [(size)] |
Base 64 string representing the logical address of a row of an index-organized table. The optional size is the size of a column of type UROWID. The maximum size and default is 4000 bytes. |
| 96 | CHAR [(size [BYTE | CHAR])] |
Fixed-length character data of length size bytes. Maximum size is 2000 bytes or characters. Default and minimum sizeis 1 byte.BYTE and CHAR have the same semantics as for VARCHAR2. |
| 96 | NCHAR[(size)] |
Fixed-length character data of length size characters. The number of bytes can be up to two times size for AL16UTF16 encoding and three times size for UTF8 encoding. Maximum size is determined by the national character set definition, with an upper limit of 2000 bytes. Default and minimum size is 1 character. |
| 112 | CLOB |
A character large object containing single-byte or multibyte characters. Both fixed-width and variable-width character sets are supported, both using the database character set. Maximum size is (4 gigabytes 8211; 1) * (database block size). |
| 112 | NCLOB |
A character large object containing Unicode characters. Both fixed-width and variable-width character sets are supported, both using the database national character set. Maximum size is (4 gigabytes 8211; 1) * (database block size). Stores national character set data. |
| 113 | BLOB |
A binary large object. Maximum size is (4 gigabytes 8211; 1) * (database block size). |
| 114 | BFILE |
Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes. |
The sections that follow describe the Oracle datatypes as they are stored in Oracle Database. For information on specifying these datatypes as literals, please refer to 8220;Literals8221;.
Character datatypes store character (alphanumeric) data, which are words and free-form text, in the database character set or national character set. They are less restrictive than other datatypes and consequently have fewer properties. For example, character columns can store all alphanumeric values, but NUMBER columns can store only numeric values.
Character data is stored in strings with byte values corresponding to one of the character sets, such as 7-bit ASCII or EBCDIC, specified when the database was created. Oracle Database supports both single-byte and multibyte character sets.
These datatypes are used for character data:
For information on specifying character datatypes as literals, please refer to 8220;Text Literals8221;.
CHAR Datatype
The CHAR datatype specifies a fixed-length character string. Oracle ensures that all values stored in a CHAR column have the length specified by size. If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length. If you try to insert a value that is too long for the column, then Oracle returns an error.
The default length for a CHAR column is 1 byte and the maximum allowed is 2000 bytes. A 1-byte string can be inserted into a CHAR(10) column, but the string is blank-padded to 10 bytes before it is stored.
When you create a table with a CHAR column, by default you supply the column length in bytes. The BYTE qualifier is the same as the default. If you use the CHAR qualifier, for example CHAR(10 CHAR), then you supply the column length in characters. A character is technically a code point of the database character set. Its size can range from 1 byte to 4 bytes, depending on the database character set. The BYTE and CHAR qualifiers override the semantics specified by the NLS_LENGTH_SEMANTICS parameter, which has a default of byte semantics. For performance reasons, Oracle recommends that you use the NLS_LENGTH_SEMANTICS parameter to set length semantics and that you use the BYTE and CHAR qualifiers only when necessary to override the parameter.
To ensure proper data conversion between databases with different character sets, you must ensure that CHAR data consists of well-formed strings. See Oracle Database Globalization Support Guide for more information on character set support.
NCHAR Datatype
The NCHAR datatype is a Unicode-only datatype. When you create a table with an NCHAR column, you define the column length in characters. You define the national character set when you create your database.
The maximum length of a column is determined by the national character set definition. Width specifications of character datatype NCHAR refer to the number of characters. The maximum column size allowed is 2000 bytes.
If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length. You cannot insert a CHAR value into an NCHAR column, nor can you insert an NCHAR value into a CHAR column.
The following example compares the translated_description column of the pm.product_descriptions table with a national character set string:
SELECT translated_description FROM product_descriptions WHERE translated_name = N'LCD Monitor 11/PM';
Please refer to Oracle Database Globalization Support Guide for information on Unicode datatype support.
NVARCHAR2 Datatype
The NVARCHAR2 datatype is a Unicode-only datatype. When you create a table with an NVARCHAR2 column, you supply the maximum number of characters it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the maximum length of the column.
The maximum length of the column is determined by the national character set definition. Width specifications of character datatype NVARCHAR2 refer to the number of characters. The maximum column size allowed is 4000 bytes. Please refer to Oracle Database Globalization Support Guide for information on Unicode datatype support.
VARCHAR2 Datatype
The VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2 column, you supply the maximum number of bytes or characters of data that it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the column8217;s maximum length of the column. If you try to insert a value that exceeds the specified length, then Oracle returns an error.
You must specify a maximum length for a VARCHAR2 column. This maximum must be at least 1 byte, although the actual string stored is permitted to be a zero-length string (''). You can use the CHAR qualifier, for example VARCHAR2(10 CHAR), to give the maximum length in characters instead of bytes. A character is technically a code point of the database character set. CHAR and BYTE qualifiers override the setting of the NLS_LENGTH_SEMANTICS parameter, which has a default of bytes. For performance reasons, Oracle recommends that you use the NLS_LENGTH_SEMANTICS parameter to set length semantics and that you use the BYTE and CHAR qualifiers only when necessary to override the parameter. The maximum length of VARCHAR2 data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics.
To ensure proper data conversion between databases with different character sets, you must ensure that VARCHAR2 data consists of well-formed strings. See Oracle Database Globalization Support Guide for more information on character set support.
VARCHAR Datatype
Do not use the VARCHAR datatype. Use the VARCHAR2 datatype instead. Although the VARCHAR datatype is currently synonymous with VARCHAR2, the VARCHAR datatype is scheduled to be redefined as a separate datatype used for variable-length character strings compared with different comparison semantics.
The Oracle Database numeric datatypes store positive and negative fixed and floating-point numbers, zero, infinity, and values that are the undefined result of an operation (that is, is 8220;not a number8221; or NAN). For information on specifying numeric datatypes as literals, please refer to 8220;Numeric Literals8221;.
NUMBER Datatype
The NUMBER datatype stores zero as well as positive and negative fixed numbers with absolute values from 1.0 x 10-130 to (but not including) 1.0 x 10126. If you specify an arithmetic expression whose value has an absolute value greater than or equal to 1.0 x 10126, then Oracle returns an error. Each NUMBER value requires from 1 to 22 bytes.
Specify a fixed-point number using the following form:
NUMBER(p,s)
where:
pis the precision, or the total number of significant decimal digits, where the most significant digit is the left-most nonzero digit, and the least significant digit is the right-most known digit. Oracle guarantees the portability of numbers with precision of up to 20 base-100 digits, which is equivalent to 39 or 40 decimal digits depending on the position of the decimal point.sis the scale, or the number of digits from the decimal point to the least significant digit. The scale can range from -84 to 127.- Positive scale is the number of significant digits to the right of the decimal point to and including the least significant digit.
- Negative scale is the number of significant digits to the left of the decimal point, to but not including the least significant digit. For negative scale the least significant digit is on the left side of the decimal point, because the actual data is rounded to the specified number of places to the left of the decimal point. For example, a specification of (10,-2) means to round to hundreds.
Scale can be greater than precision, most commonly when e notation is used. When scale is greater than precision, the precision specifies the maximum number of significant digits to the right of the decimal point. For example, a column defined as NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all values past the fifth digit after the decimal point.
It is good practice to specify the scale and precision of a fixed-point number column for extra integrity checking on input. Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision, then Oracle returns an error. If a value exceeds the scale, then Oracle rounds it.
Specify an integer using the following form:
NUMBER(p)
This represents a fixed-point number with precision p and scale 0 and is equivalent to NUMBER(p,0).
Specify a floating-point number using the following form:
NUMBER
The absence of precision and scale designators specifies the maximum range and precision for an Oracle number.
Table 2-2 show how Oracle stores data using different precisions and scales.
Table 2-2 Storage of Scale and Precision
| Actual Data | Specified As | Stored As |
|---|---|---|
| 123.89 | NUMBER |
123.89 |
| 123.89 | NUMBER(3) |
124 |
| 123.89 | NUMBER(6,2) |
123.89 |
| 123.89 | NUMBER(6,1) |
123.9 |
| 123.89 | NUMBER(3) |
exceeds precision |
| 123.89 | NUMBER(4,2) |
exceeds precision |
| 123.89 | NUMBER(6,-2) |
100 |
| .01234 | NUMBER(4,5) |
.01234 |
| .00012 | NUMBER(4,5) |
.00012 |
| .000127 | NUMBER(4,5) |
.00013 |
| .0000012 | NUMBER(2,7) |
.0000012 |
| .00000123 | NUMBER(2,7) |
.0000012 |
| 1.2e-4 | NUMBER(2,5) |
0.00012 |
| 1.2e-5 | NUMBER(2,5) |
0.00001 |
Floating-Point Numbers
Floating-point numbers can have a decimal point anywhere from the first to the last digit or can have no decimal point at all. An exponent may optionally be used following the number to increase the range (for example, 1.777 e-20). A scale value is not applicable to floating-point numbers, because the number of digits that can appear after the decimal point is not restricted.
Binary floating-point numbers differ from NUMBER in the way the values are stored internally by Oracle Database. Values are stored using decimal precision for NUMBER. All literals that are within the range and precision supported by NUMBER are stored exactly as NUMBER. Literals are stored exactly because literals are expressed using decimal precision (the digits 0 through 9). Binary floating-point numbers are stored using binary precision (the digits 0 and 1). Such a storage scheme cannot represent all values using decimal precision exactly. Frequently, the error that occurs when converting a value from decimal to binary precision is undone when the value is converted back from binary to decimal precision. The literal 0.1 is such an example.
Oracle Database provides two numeric datatypes exclusively for floating-point numbers:
BINARY_FLOAT
BINARY_FLOAT is a 32-bit, single-precision floating-point number datatype. Each BINARY_FLOAT value requires 5 bytes, including a length byte.
BINARY_DOUBLE
BINARY_DOUBLE is a 64-bit, double-precision floating-point number datatype. Each BINARY_DOUBLE value requires 9 bytes, including a length byte.
In a NUMBER column, floating point numbers have decimal precision. In a BINARY_FLOAT or BINARY_DOUBLE column, floating-point numbers have binary precision. The binary floating-point numbers support the special values infinity and NaN (not a number).
You can specify floating-point numbers within the limits listed in Table 2-3. The format for specifying floating-point numbers is defined in 8220;Numeric Literals8221;.
Table 2-3 Floating Point Number Limits
| Value | Binary-Float | Binary-Double |
|---|---|---|
| Maximum positive finite value | 3.40282E+38F | 1.79769313486231E+308 |
| Minimum positive finite value | 1.17549E-38F | 2.22507485850720E-308 |
Oracle Database also supports the ANSI datatype FLOAT. You can specify this datatype using one of these syntactic forms:
FLOAT FLOAT(n)
The number n indicates the number of bits of precision that the value can store. The value for n can range from 1 to 126. To convert from binary to decimal precision, multiply n by 0.30103. To convert from decimal to binary precision, multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision.
IEEE754 Conformance The Oracle implementation of floating-point datatypes conforms substantially with the Institute of Electrical and Electronics Engineers (IEEE) Standard for Binary Floating-Point Arithmetic, IEEE Standard 754-1985 (IEEE754). The new datatypes conform to IEEE754 in the following areas:
- The SQL function
SQRTimplements square root. See SQRT. - The SQL function
REMAINDERimplements remainder. See REMAINDER. - Arithmetic operators conform. See 8220;Arithmetic Operators8221;.
- Comparison operators conform, except for comparisons with
NaN. Oracle ordersNaNgreatest with respect to all other values, and evaluatesNaNequal toNaN. See 8220;Floating-Point Conditions8221;. - Conversion operators conform. See 8220;Conversion Functions8221;.
- The default rounding mode is supported.
- The default exception handling mode is supported.
- The special values
INF, -INF, andNaNare supported. See 8220;Floating-Point Conditions8221;. - Rounding of
BINARY_FLOATandBINARY_DOUBLEvalues to integer-valuedBINARY_FLOATandBINARY_DOUBLEvalues is provided by the SQL functionsROUND,TRUNC,CEIL, andFLOOR. - Rounding of
BINARY_FLOAT/BINARY_DOUBLEto decimal and decimal toBINARY_FLOAT/BINARY_DOUBLEis provided by the SQL functionsTO_CHAR,TO_NUMBER,TO_NCHAR,TO_BINARY_FLOAT,TO_BINARY_DOUBLE, andCAST.
The new datatypes do not conform to IEEE754 in the following areas:
- -0 is coerced to +0.
- Comparison with
NaNis not supported. - All
NaNvalues are coerced to eitherBINARY_FLOAT_NANorBINARY_DOUBLE_NAN. - Non-default rounding modes are not supported.
- Non-default exception handling mode are not supported.
Numeric Precedence
Numeric precedence determines, for operations that support numeric datatypes, the datatype Oracle uses if the arguments to the operation have different datatypes. BINARY_DOUBLE has the highest numeric precedence, followed by BINARY_FLOAT, and finally by NUMBER. Therefore, in any operation on multiple numeric values:
- If any of the operands is
BINARY_DOUBLE, then Oracle attempts to convert all the operands implicitly toBINARY_DOUBLEbefore performing the operation. - If none of the operands is
BINARY_DOUBLEbut any of the operands isBINARY_FLOAT, then Oracle attempts to convert all the operands implicitly toBINARY_FLOATbefore performing the operation. - Otherwise, Oracle attempts to convert all the operands to
NUMBERbefore performing the operation.
If any implicit conversion is needed and fails, then the operation fails. Table 2-10, 8220;Implicit Type Conversion Matrix8221; for more information on implicit conversion.
In the context of other datatypes, numeric datatypes have lower precedence than the datetime/interval datatypes and higher precedence than character and all other datatypes.
LONG columns store variable-length character strings containing up to 2 gigabytes -1, or 231-1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. The length of LONG values may be limited by the memory available on your computer. LONG literals are formed as described for 8220;Text Literals8221;.
Do not create tables with LONG columns. Use LOB columns (CLOB, NCLOB, BLOB) instead. LONG columns are supported only for backward compatibility.
Oracle also recommends that you convert existing LONG columns to LOB columns. LOB columns are subject to far fewer restrictions than LONG columns. Further, LOB functionality is enhanced in every release, whereas LONG functionality has been static for several releases. See the modify_col_properties clause of ALTER TABLE and TO_LOB for more information on converting LONG columns to LOB.
You can reference LONG columns in SQL statements in these places:
SELECTlistsSETclauses ofUPDATEstatementsVALUESclauses ofINSERTstatements
The use of LONG values is subject to these restrictions:
- A table can contain only one
LONGcolumn. - You cannot create an object type with a
LONGattribute. LONGcolumns cannot appear inWHEREclauses or in integrity constraints (except that they can appear inNULLandNOTNULLconstraints).LONGcolumns cannot be indexed.LONGdata cannot be specified in regular expressions.- A stored function cannot return a
LONGvalue. - You can declare a variable or argument of a PL/SQL program unit using the
LONGdatatype. However, you cannot then call the program unit from SQL. - Within a single SQL statement, all
LONGcolumns, updated tables, and locked tables must be located on the same database. LONGandLONGRAWcolumns cannot be used in distributed SQL statements and cannot be replicated.- If a table has both
LONGand LOB columns, then you cannot bind more than 4000 bytes of data to both theLONGand LOB columns in the same SQL statement. However, you can bind more than 4000 bytes of data to either theLONGor the LOB column.
In addition, LONG columns cannot appear in these parts of SQL statements:
GROUPBYclauses,ORDERBYclauses, orCONNECTBYclauses or with theDISTINCToperator inSELECTstatements- The
UNIQUEoperator of aSELECTstatement - The column list of a
CREATECLUSTERstatement - The
CLUSTERclause of aCREATEMATERIALIZEDVIEWstatement - SQL built-in functions, expressions, or conditions
SELECTlists of queries containingGROUPBYclausesSELECTlists of subqueries or queries combined by theUNION,INTERSECT, orMINUSset operatorsSELECTlists ofCREATETABLE8230;ASSELECTstatementsALTERTABLE8230;MOVEstatementsSELECTlists in subqueries inINSERTstatements
Triggers can use the LONG datatype in the following manner:
- A SQL statement within a trigger can insert data into a
LONGcolumn. - If data from a
LONGcolumn can be converted to a constrained datatype (such asCHARandVARCHAR2), then aLONGcolumn can be referenced in a SQL statement within a trigger. - Variables in triggers cannot be declared using the
LONGdatatype. - :
NEWand :OLDcannot be used withLONGcolumns.
You can use Oracle Call Interface functions to retrieve a portion of a LONG value from the database.
Datetime and Interval Datatypes
The datetime datatypes are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE. Values of datetime datatypes are sometimes called datetimes. The interval datatypes are INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND. Values of interval datatypes are sometimes called intervals. For information on expressing datetime and interval values as literals, please refer to 8220;Datetime Literals8221; and 8220;Interval Literals8221;.
Both datetimes and intervals are made up of fields. The values of these fields determine the value of the datatype. Table 2-4 lists the datetime fields and their possible values for datetimes and intervals.
To avoid unexpected results in your DML operations on datetime data, you can verify the database and session time zones by querying the built-in SQL functions DBTIMEZONE and SESSIONTIMEZONE. If the time zones have not been set manually, Oracle Database uses the operating system time zone by default. If the operating system time zone is not a valid Oracle time zone, then Oracle uses UTC as the default value.
Table 2-4 Datetime Fields and Values
| Datetime Field | Valid Values for Datetime | Valid Values for INTERVAL |
|---|---|---|
YEAR |
-4712 to 9999 (excluding year 0) | Any positive or negative integer |
MONTH |
01 to 12 | 0 to 11 |
DAY |
01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the current NLS calendar parameter) |
Any positive or negative integer |
HOUR |
00 to 23 | 0 to 23 |
MINUTE |
00 to 59 | 0 to 59 |
SECOND |
00 to 59.9(n), where 9(n) is the precision of time fractional seconds. The 9(n) portion is not applicable for DATE. |
0 to 59.9(n), where 9(n) is the precision of interval fractional seconds |
TIMEZONE_HOUR |
-12 to 14 (This range accommodates daylight saving time changes.) Not applicable for DATE or TIMESTAMP. |
Not applicable |
TIMEZONE_MINUTE(See note at end of table) |
00 to 59. Not applicable for DATE or TIMESTAMP. |
Not applicable |
TIMEZONE_REGION |
Query the TZNAME column of the V$TIMEZONE_NAMES data dictionary view. Not applicable for DATE or TIMESTAMP. For a complete listing of all timezone regions, refer to Oracle Database Globalization Support Guide. |
Not applicable |
TIMEZONE_ABBR |
Query the TZABBREV column of the V$TIMEZONE_NAMES data dictionary view. Not applicable for DATE or TIMESTAMP. |
Not applicable |
Note: TIMEZONE_HOUR and TIMEZONE_MINUTE are specified together and interpreted as an entity in the format +|- hh:mm, with values ranging from -12:59 to +14:00. Please refer to Oracle Data Provider for .NET Developer8217;s Guide for information on specifying time zone values for that API.
DATE Datatype
The DATE datatype stores date and time information. Although date and time information can be represented in both character and number datatypes, the DATE datatype has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, date, hour, minute, and second.
You can specify a DATE value as a literal, or you can convert a character or numeric value to a date value with the TO_DATE function. For examples of expressing DATE values in both these ways, please refer to 8220;Datetime Literals8221;.
Using Julian Days
A Julian day number is the number of days since January 1, 4712 BC. Julian days allow continuous dating from a common reference. You can use the date format model 8220;J8221; with date functions TO_DATE and TO_CHAR to convert between Oracle DATE values and their Julian equivalents.
Note:
Oracle Database uses the astronomical system of calculating Julian days, in which the year 4713 BC is specified as -4712. The historical system of calculating Julian days, in contrast, specifies 4713 BC as -4713. If you are comparing Oracle Julian days with values calculated using the historical system, then take care to allow for the 365-day difference in BC dates. For more information, see http://aa.usno.navy.mil/faq/docs/millennium.html.
The default date values are determined as follows:
- The year is the current year, as returned by
SYSDATE. - The month is the current month, as returned by
SYSDATE. - The day is 01 (the first day of the month).
- The hour, minute, and second are all 0.
These default values are used in a query that requests date values where the date itself is not specified, as in the following example, which is issued in the month of May:
SELECT TO_DATE('2005', 'YYYY') FROM DUAL;
TO_DATE('
---------
01-MAY-05
Example This statement returns the Julian equivalent of January 1, 1997:
SELECT TO_CHAR(TO_DATE('01-01-1997', 'MM-DD-YYYY'),'J')
FROM DUAL;
TO_CHAR
--------
2450450
TIMESTAMP Datatype
The TIMESTAMP datatype is an extension of the DATE datatype. It stores the year, month, and day of the DATE datatype, plus hour, minute, and second values. This datatype is useful for storing precise time values. Specify the TIMESTAMP datatype as follows:
TIMESTAMP [(fractional_seconds_precision)]
where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this datatype, the value can be a number in the range 0 to 9. The default is 6.
TIMESTAMP WITH TIME ZONE Datatype
TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time—formerly Greenwich Mean Time). This datatype is useful for collecting and evaluating date information across geographic regions.
Specify the TIMESTAMP WITH TIME ZONE datatype as follows:
TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE
where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this datatype, the value can be a number in the range 0 to 9. The default is 6.
Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site.
TIMESTAMP WITH LOCAL TIME ZONE Datatype
TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP that includes a time zone offset in its value. It differs from TIMESTAMP WITH TIME ZONE in that data stored in the database is normalized to the database time zone, and the time zone offset is not stored as part of the column data. When a user retrieves the data, Oracle returns it in the user8217;s local session time zone. The time zone offset is the difference (in hours and minutes) between local time and UTC (Coordinated Universal Time—formerly Greenwich Mean Time). This datatype is useful for displaying date information in the time zone of the client system in a two-tier application.
Specify the TIMESTAMP WITH LOCAL TIME ZONE datatype as follows:
TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE
where fractional_seconds_precision optionally specifies the number of digits Oracle stores in the fractional part of the SECOND datetime field. When you create a column of this datatype, the value can be a number in the range 0 to 9. The default is 6.
Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site.
INTERVAL YEAR TO MONTH Datatype
INTERVAL YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime fields. This datatype is useful for representing the difference between two datetime values when only the year and month values are significant.
Specify INTERVAL YEAR TO MONTH as follows:
INTERVAL YEAR [(year_precision)] TO MONTH
where year_precision is the number of digits in the YEAR datetime field. The default value of year_precision is 2.
You have a great deal of flexibility when specifying interval values as literals. Please refer to 8220;Interval Literals8221; for detailed information on specify interval values as literals. Also see 8220;Datetime and Interval Examples8221; for an example using intervals.
INTERVAL DAY TO SECOND Datatype
INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and seconds. This datatype is useful for representing the precise difference between two datetime values.
Specify this datatype as follows:
INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]
where
day_precisionis the number of digits in theDAYdatetime field. Accepted values are 0 to 9. The default is 2.fractional_seconds_precisionis the number of digits in the fractional part of theSECONDdatetime field. Accepted values are 0 to 9. The default is 6.
You have a great deal of flexibility when specifying interval values as literals. Please refer to 8220;Interval Literals8221; for detailed information on specify interval values as literals. Also see 8220;Datetime and Interval Examples8221; for an example using intervals.
Datetime/Interval Arithmetic
You can perform a number of arithmetic operations on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE) and interval (INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH) data. Oracle calculates the results based on the following rules:
- You can use
NUMBERconstants in arithmetic operations on date and timestamp values, but not interval values. Oracle internally converts timestamp values to date values and interpretsNUMBERconstants in arithmetic datetime and interval expressions as numbers of days. For example,SYSDATE+ 1 is tomorrow.SYSDATE8211; 7 is one week ago.SYSDATE+ (10/1440) is ten minutes from now. Subtracting thehire_datecolumn of the sample tableemployeesfromSYSDATEreturns the number of days since each employee was hired. You cannot multiply or divide date or timestamp values. - Oracle implicitly converts
BINARY_FLOATandBINARY_DOUBLEoperands toNUMBER. - Each
DATEvalue contains a time component, and the result of many date operations include a fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours. These fractions are also returned by Oracle built-in functions for common operations onDATEdata. For example, theMONTHS_BETWEENfunction returns the number of months between two dates. The fractional portion of the result represents that portion of a 31-day month. - If one operand is a
DATEvalue or a numeric value (neither of which contains time zone or fractional seconds components), then:- Oracle implicitly converts the other operand to
DATEdata. (The exception is multiplication of a numeric value times an interval, which returns an interval.) - If the other operand has a time zone value, then Oracle uses the session time zone in the returned value.
- If the other operand has a fractional seconds value, then the fractional seconds value is lost.
- Oracle implicitly converts the other operand to
- When you pass a timestamp, interval, or numeric value to a built-in function that was designed only for the
DATEdatatype, Oracle implicitly converts the non-DATEvalue to aDATEvalue. Please refer to 8220;Datetime Functions8221; for information on which functions cause implicit conversion toDATE. - When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error. For example, the next two statements return errors:
SELECT TO_DATE('31-AUG-2004','DD-MON-YYYY') + TO_YMINTERVAL('0-1') FROM DUAL; SELECT TO_DATE('29-FEB-2004','DD-MON-YYYY') + TO_YMINTERVAL('1-0') FROM DUAL;The first fails because adding one month to a 31-day month would result in September 31, which is not a valid date. The second fails because adding one year to a date that exists only every four years is not valid. However, the next statement succeeds, because adding four years to a February 29 date is valid:
SELECT TO_DATE('29-FEB-2004', 'DD-MON-YYYY') + TO_YMINTERVAL('4-0') FROM DUAL; TO_DATE(' --------- 29-FEB-08 - Oracle performs all timestamp arithmetic in UTC time. For
TIMESTAMPWITHLOCALTIMEZONE, Oracle converts the datetime value from the database time zone to UTC and converts back to the database time zone after performing the arithmetic. ForTIMESTAMPWITHTIMEZONE, the datetime value is always in UTC, so no conversion is necessary.
Table 2-5 is a matrix of datetime arithmetic operations. Dashes represent operations that are not supported.
Table 2-5 Matrix of Datetime Arithmetic
| Operand & Operator | DATE | TIMESTAMP | INTERVAL | Numeric |
|---|---|---|---|---|
| DATE | — | — | — | — |
| + | — |
— |
DATE |
DATE |
| - | DATE |
DATE |
DATE |
DATE |
| * | — |
— |
— |
— |
| / | — |
— |
— |
— |
| TIMESTAMP | — | — | — | — |
| + | — |
— |
TIMESTAMP |
— |
| - | INTERVAL |
INTERVAL |
TIMESTAMP |
TIMESTAMP |
| * | — |
— |
— |
— |
| / | — |
— |
— |
— |
| INTERVAL | — | — | — | — |
| + | DATE |
TIMESTAMP |
INTERVAL |
— |
| - | — |
— |
INTERVAL |
— |
| * | — |
— |
— |
INTERVAL |
| / | — |
— |
— |
INTERVAL |
| Numeric | — | — | — | — |
| + | DATE |
DATE |
— |
NA |
| - | — |
— |
— |
NA |
| * | — |
— |
INTERVAL |
NA |
| / | — |
— |
— |
NA |
Examples You can add an interval value expression to a start time. Consider the sample table oe.orders with a column order_date. The following statement adds 30 days to the value of the order_date column:
SELECT order_id, order_date + INTERVAL '30' DAY FROM orders;
Support for Daylight Saving Times
Oracle Database automatically determines, for any given time zone region, whether daylight saving is in effect and returns local time values accordingly. The datetime value is sufficient for Oracle to determine whether daylight saving time is in effect for a given region in all cases except boundary cases. A boundary case occurs during the period when daylight saving goes into or comes out of effect. For example, in the US-Pacific region, when daylight saving goes into effect, the time changes from 2:00 a.m. to 3:00 a.m. The one hour interval between 2 and 3 a.m. does not exist. When daylight saving goes out of effect, the time changes from 2:00 a.m. back to 1:00 a.m., and the one-hour interval between 1 and 2 a.m. is repeated.
To resolve these boundary cases, Oracle uses the TZR and TZD format elements, as described in Table 2-15. TZR represents the time zone region in datetime input strings. Examples are 8216;Australia/North8216;, 8216;UTC8216;, and 8216;Singapore8216;. TZD represents an abbreviated form of the time zone region with daylight saving information. Examples are 8216;PST8216; for US/Pacific standard time and 8216;PDT8216; for US/Pacific daylight time. To see a listing of valid values for the TZR and TZD format elements, query the TZNAME and TZABBREV columns of the V$TIMEZONE_NAMES dynamic performance view.
Timezone region names are needed by the daylight saving feature. The region names are stored in two time zone files. The default time zone file is the complete (larger) file containing all time zones. The other time zone file is a small file containing only the most common time zones to maximize performance. If your time zone is in the small file, and you want to maximize performance, then you must provide a path to the small file by way of the ORA_TZFILE environment variable. Please refer to Oracle Database Administrator8217;s Guide for more information about setting the ORA_TZFILE environment variable. For a complete listing of the timezone region names in both files, please refer to Oracle Database Globalization Support Guide.
Oracle time zone data is derived from the public domain information available at ftp://elsie.nci.nih.gov/pub/. Oracle time zone data may not reflect the most recent data available at this site.
Datetime and Interval Examples
The following example shows how to declare some datetime and interval datatypes.
CREATE TABLE time_table ( start_time TIMESTAMP, duration_1 INTERVAL DAY (6) TO SECOND (5), duration_2 INTERVAL YEAR TO MONTH);
The start_time column is of type TIMESTAMP. The implicit fractional seconds precision of TIMESTAMP is 6.
The duration_1 column is of type INTERVAL DAY TO SECOND. The maximum number of digits in field DAY is 6 and the maximum number of digits in the fractional second is 5. The maximum number of digits in all other datetime fields is 2.
The duration_2 column is of type INTERVAL YEAR TO MONTH. The maximum number of digits of the value in each field (YEAR and MONTH) is 2.
Interval datatypes do not have format models. Therefore, to adjust their presentation, you must combine character functions such as EXTRACT and concatenate the components. For example, the following examples query the hr.employees and oe.orders tables, respectively, and change interval output from the form 8220;yy-mm8221; to 8220;yy years mm months8221; and from 8220;dd-hh8221; to 8220;dddd days hh hours8221;:
SELECT last_name, EXTRACT(YEAR FROM (SYSDATE - hire_date) YEAR TO MONTH )
|| ' years '
|| EXTRACT(MONTH FROM (SYSDATE - hire_date) YEAR TO MONTH )
|| ' months' "Interval"
FROM employees ;
LAST_NAME Interval
------------------------- --------------------
King 17 years 11 months
Kochhar 15 years 8 months
De Haan 12 years 4 months
Hunold 15 years 4 months
Ernst 14 years 0 months
Austin 7 years 11 months
Pataballa 7 years 3 months
Lorentz 6 years 3 months
Greenberg 10 years 9 months
. . .
SELECT order_id,
EXTRACT(DAY FROM (SYSDATE - order_date) DAY TO SECOND )
|| ' days '
|| EXTRACT(HOUR FROM (SYSDATE - order_date) DAY TO SECOND )
|| ' hours' "Interval"
FROM orders;
ORDER_ID Interval
---------- --------------------
2458 2095 days 18 hours
2397 2000 days 17 hours
2454 2048 days 16 hours
2354 1762 days 16 hours
2358 1950 days 15 hours
2381 1823 days 13 hours
2440 2080 days 12 hours
2357 2680 days 11 hours
2394 1917 days 10 hours
2435 2078 days 10 hours
. . .
RAW and LONG RAW Datatypes
The RAW and LONG RAW datatypes store data that is not to be interpreted (that is, not explicitly converted when moving data between different systems) by Oracle Database. These datatypes are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use.
Oracle strongly recommends that you convert LONG RAW columns to binary LOB (BLOB) columns. LOB columns are subject to far fewer restrictions than LONG columns. See TO_LOB for more information.
RAW is a variable-length datatype like VARCHAR2, except that Oracle Net (which connects user sessions to the instance) and the Import and Export utilities do not perform character conversion when transmitting RAW or LONG RAW data. In contrast, Oracle Net and Import/Export automatically convert CHAR, VARCHAR2, and LONG data from the database character set to the user session character set (which you can set with the NLS_LANGUAGE parameter of the ALTER SESSION statement), if the two character sets are different.
When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary data is represented in hexadecimal form, with one hexadecimal character representing every four bits of RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as CB.
The built-in LOB datatypes BLOB, CLOB, and NCLOB (stored internally) and BFILE (stored externally) can store large and unstructured data such as text, image, video, and spatial data. The size of BLOB, CLOB, and NCLOB data can be up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage). If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes 8211; 1) * (database block size). BFILE data can be up to 232-1 bytes, although your operating system may impose restrictions on this maximum.
When creating a table, you can optionally specify different tablespace and storage characteristics for LOB columns or LOB object attributes from those specified for the table.
LOB columns contain LOB locators that can refer to in-line (in the database) or out-of-line (outside the database) LOB values. Selecting a LOB from a table actually returns the LOB locator and not the entire LOB value. The DBMS_LOB package and Oracle Call Interface (OCI) operations on LOBs are performed through these locators.
LOBs are similar to LONG and LONG RAW types, but differ in the following ways:
- LOBs can be attributes of an object type (user-defined datatype).
- The LOB locator is stored in the table column, either with or without the actual LOB value.
BLOB,NCLOB, andCLOBvalues can be stored in separate tablespaces.BFILEdata is stored in an external file on the server. - When you access a LOB column, the locator is returned.
- A LOB can be up to (4 gigabytes 8211; 1)*(database block size) in size.
BFILEdata can be up to 232-1 bytes, although your operating system may impose restrictions on this maximum.Preceding corrected; thomas.chang, 8/26/04. - LOBs permit efficient, random, piece-wise access to and manipulation of data.
- You can define more than one LOB column in a table.
- With the exception of
NCLOB, you can define one or more LOB attributes in an object. - You can declare LOB bind variables.
- You can select LOB columns and LOB attributes.
- You can insert a new row or update an existing row that contains one or more LOB columns or an object with one or more LOB attributes. In update operations, you can set the internal LOB value to
NULL, empty, or replace the entire LOB with data. You can set theBFILEtoNULLor make it point to a different file. - You can update a LOB row-column intersection or a LOB attribute with another LOB row-column intersection or LOB attribute.
- You can delete a row containing a LOB column or LOB attribute and thereby also delete the LOB value. For BFILEs, the actual operating system file is not deleted.
You can access and populate rows of an in-line LOB column (a LOB column stored in the database) or a LOB attribute (an attribute of an object type column stored in the database) simply by issuing an INSERT or UPDATE statement.
Restrictions on LOB Columns LOB columns are subject to the following restrictions:
- You cannot specify a LOB as a primary key column.
- Oracle Database has limited support for remote LOBs. Remote LOBs are supported in three ways..1. Create table as select or insert as select.
CREATE TABLE t AS SELECT * FROM table1@remote_site; INSERT INTO t SELECT * FROM table1@remote_site; UPDATE t SET lobcol = (SELECT lobcol FROM table1@remote_site); INSERT INTO table1@remote_site SELECT * FROM local_table; UPDATE table1@remote_site SET lobcol = (SELECT lobcol FROM local_table); DELETE FROM table1@remote_site <WHERE clause involving non_lob_columns>
In statements structured like the preceding examples, only standalone LOB columns are allowed in the select list.
2. Functions on remote LOBs returning scalars. SQL and PL/SQL functions having a LOB parameter and returning a scalar datatype are supported. Other SQL functions and
DBMS_LOBAPIs are not supported for use with remote LOB columns. For example, the following statement is supported:CREATE TABLE tab AS SELECT DBMS_LOB.GETLENGTH@dbs2(clob_col) len FROM tab@dbs2; CREATE TABLE tab AS SELECT LENGTH(clob_col) len FROM tab@dbs2;
However, the following statement is not supported because
DBMS_LOB.SUBSTRreturns a LOB:CREATE TABLE tab AS SELECT DBMS_LOB.SUBSTR(clob_col) from tab@dbs2;
3. Data Interface for remote LOBs. You can insert a character or binary buffer into a remote
CLOBorBLOB, and select a remoteCLOBorBLOBinto a character or binary buffer. For example (in PL/SQL):SELECT clobcol1, type1.blobattr INTO varchar_buf1, raw_buf2 FROM table1@remote_site; INSERT INTO table1@remotesite (clobcol1, type1.blobattr) VALUES varchar_buf1, raw_buf2; INSERT INTO table1@remotesite (lobcol) VALUES ('test'); UPDATE table1 SET lobcol = 'xxx';These are the only supported syntax involving LOBs in remote tables. No other usage is supported.
- Clusters cannot contain LOBs, either as key or non-key columns.
- The following data structures are supported only as temporary instances. You cannot store these instances in database tables:
VARRAYof any LOB typeVARRAYof any type containing a LOB type, such as an object type with a LOB attributeANYDATAof any LOB typeANYDATAof any type containing a LOB
- You cannot specify LOB columns in the
ORDERBYclause of a query, or in theGROUPBYclause of a query or in an aggregate function. - You cannot specify a LOB column in a
SELECT8230;DISTINCTorSELECT8230;UNIQUEstatement or in a join. However, you can specify a LOB attribute of an object type column in aSELECT8230;DISTINCTstatement or in a query that uses theUNIONorMINUSset operator if the column8217;s object type has aMAPorORDERfunction defined on it. - You cannot specify LOB columns in
ANALYZE8230;COMPUTEorANALYZE8230;ESTIMATEstatements. - The first (
INITIAL) extent of a LOB segment must contain at least three database blocks. - When creating an
UPDATEDML trigger, you cannot specify a LOB column in theUPDATEOFclause. - You cannot specify a LOB column as part of an index key. However, you can specify a LOB column in the indextype specification of a domain index. In addition, Oracle Text lets you define an index on a
CLOBcolumn. - In an
INSERT8230;ASSELECToperation, you can bind up to 4000 bytes of data to LOB columns and attributes. - If a table has both
LONGand LOB columns, you cannot bind more than 4000 bytes of data to both theLONGand LOB columns in the same SQL statement. However, you can bind more than 4000 bytes of data to either theLONGor the LOB column.
Note:
For a table on which you have defined a DML trigger, if you use OCI functions or DBMS_LOB routines to change the value of a LOB column or the LOB attribute of an object type column, then the database does not fire the DML trigger.
BFILE Datatype
The BFILE datatype enables access to binary file LOBs that are stored in file systems outside Oracle Database. A BFILE column or attribute stores a BFILE locator, which serves as a pointer to a binary file on the server file system. The locator maintains the directory name and the filename.
You can change the filename and path of a BFILE without affecting the base table by using the BFILENAME function. Please refer to BFILENAME for more information on this built-in SQL function.
Correction in last sentence below; thomas.chang, 8/26/04.
Binary file LOBs do not participate in transactions and are not recoverable. Rather, the underlying operating system provides file integrity and durability. BFILE data can be up to 232-1 bytes, although your operating system may impose restrictions on this maximum.
The database administrator must ensure that the external file exists and that Oracle processes have operating system read permissions on the file.
The BFILE datatype enables read-only support of large binary files. You cannot modify or replicate such a file. Oracle provides APIs to access file data. The primary interfaces that you use to access file data are the DBMS_LOB package and the Oracle Call Interface (OCI).
BLOB Datatype
The BLOB datatype stores unstructured binary large objects. BLOB objects can be thought of as bitstreams with no character set semantics. BLOB objects can store binary data up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage). If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes 8211; 1) * (database block size).
BLOB objects have full transactional support. Changes made through SQL, the DBMS_LOB package, or the Oracle Call Interface (OCI) participate fully in the transaction. BLOB value manipulations can be committed and rolled back. However, you cannot save a BLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
CLOB Datatype
The CLOB datatype stores single-byte and multibyte character data. Both fixed-width and variable-width character sets are supported, and both use the database character set. CLOB objects can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage) of character data. If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes 8211; 1) * (database block size).
CLOB objects have full transactional support. Changes made through SQL, the DBMS_LOB package, or the Oracle Call Interface (OCI) participate fully in the transaction. CLOB value manipulations can be committed and rolled back. However, you cannot save a CLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
NCLOB Datatype
The NCLOB datatype stores Unicode data. Both fixed-width and variable-width character sets are supported, and both use the national character set. NCLOB objects can store up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage) of character text data. If the tablespaces in your database are of standard block size, and if you have used the default value of the CHUNK parameter of LOB storage when creating a LOB column, then this is equivalent to (4 gigabytes 8211; 1) * (database block size)(4 gigabytes-1) * (database block size).
NCLOB objects have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. NCLOB value manipulations can be committed and rolled back. However, you cannot save an NCLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
Each row in the database has an address. You can examine a row address by querying the pseudocolumn ROWID. Values of this pseudocolumn are strings representing the address of each row. These strings have the datatype ROWID. You can also create tables and clusters that contain actual columns having the ROWID datatype. Oracle Database does not guarantee that the values of such columns are valid rowids. Please refer to Chapter 3, 8220;Pseudocolumns8221; for more information on the ROWID pseudocolumn.
Restricted Rowids
Beginning with Oracle8, Oracle SQL incorporated an extended format for rowids to efficiently support partitioned tables and indexes and tablespace-relative data block addresses (DBAs) without ambiguity.
Character values representing rowids in Oracle7 and earlier releases are called restricted rowids. Their format is as follows:
block.row.file
blockis a hexadecimal string identifying the data block of the datafile containing the row. The length of this string depends on your operating system.rowis a four-digit hexadecimal string identifying the row in the data block. The first row of the block has a digit of 0.fileis a hexadecimal string identifying the database file containing the row. The first datafile has the number 1. The length of this string depends on your operating system.
Extended Rowids
The extended ROWID datatype stored in a user column includes the data in the restricted rowid plus a data object number. The data object number is an identification number assigned to every database segment. You can retrieve the data object number from the data dictionary views USER_OBJECTS, DBA_OBJECTS, and ALL_OBJECTS. Objects that share the same segment (clustered tables in the same cluster, for example) have the same object number.
Extended rowids are stored as base 64 values that can contain the characters A-Z, a-z, 0-9, and the plus sign (+) and forward slash (/). Extended rowids are not available directly. You can use a supplied package, DBMS_ROWID, to interpret extended rowid contents. The package functions extract and provide information that would be available directly from a restricted rowid as well as information specific to extended rowids.
Compatibility and Migration
The restricted form of a rowid is still supported in this release for backward compatibility, but all tables return rowids in the extended format.
UROWID Datatype
Each row in a database has an address. However, the rows of some tables have addresses that are not physical or permanent or were not generated by Oracle Database. For example, the row addresses of index-organized tables are stored in index leaves, which can move. Rowids of foreign tables (such as DB2 tables accessed through a gateway) are not standard Oracle rowids.
Oracle uses universal rowids (urowids) to store the addresses of index-organized and foreign tables. Index-organized tables have logical urowids and foreign tables have foreign urowids. Both types of urowid are stored in the ROWID pseudocolumn (as are the physical rowids of heap-organized tables).
Oracle creates logical rowids based on the primary key of the table. The logical rowids do not change as long as the primary key does not change. The ROWID pseudocolumn of an index-organized table has a datatype of UROWID. You can access this pseudocolumn as you would the ROWID pseudocolumn of a heap-organized table (that is, using a SELECT 8230; ROWID statement). If you want to store the rowids of an index-organized table, then you can define a column of type UROWID for the table and retrieve the value of the ROWID pseudocolumn into that column.
Note:
Heap-organized tables have physical rowids. Oracle does not recommend that you specify a column of datatype UROWID for a heap-organized table.
ANSI, DB2, and SQL/DS Datatypes
SQL statements that create tables and clusters can also use ANSI datatypes and datatypes from the IBM products SQL/DS and DB2. Oracle recognizes the ANSI or IBM datatype name that differs from the Oracle Database datatype name, records it as the name of the datatype of the column, and then stores the column data in an Oracle datatype based on the conversions shown in the tables that follow.
Table 2-6 ANSI Datatypes Converted to Oracle Datatypes
| ANSI SQL Datatype | Oracle Datatype |
|---|---|
CHARACTER(n)CHAR(n) |
CHAR(n) |
CHARACTER VARYING(n)CHAR VARYING(n) |
VARCHAR(n) |
NATIONAL CHARACTER(n)NATIONAL CHAR(n)NCHAR(n) |
NCHAR(n) |
NATIONAL CHARACTER VARYING(n)NATIONAL CHAR VARYING(n)NCHAR VARYING(n) |
NVARCHAR2(n) |
NUMERIC(p,s)DECIMAL(p,s) (a) |
NUMBER(p,s) |
INTEGERINTSMALLINT |
NUMBER(38) |
FLOAT(b)DOUBLE PRECISION(c)REAL (d) |
NUMBER |
-
- The
NUMERICandDECIMALdatatypes can specify only fixed-point numbers. For those datatypes, s defaults to 0. - The
FLOATdatatype is a floating-point number with a binary precision b. The default precision for this datatypes is 126 binary, or 38 decimal. - The
DOUBLE PRECISIONdatatype is a floating-point number with binary precision 126. - The
REALdatatype is a floating-point number with a binary precision of 63, or 18 decimal.
- The
Table 2-7 SQL/DS and DB2 Datatypes Converted to Oracle Datatypes
| SQL/DS or DB2 Datatype | Oracle Datatype |
|---|---|
CHARACTER(n) |
CHAR(n) |
VARCHAR(n) |
VARCHAR(n) |
LONG VARCHAR(n) |
LONG |
DECIMAL(p,s) (a) |
NUMBER(p,s) |
INTEGERSMALLINT |
NUMBER(38) |
FLOAT (b) |
NUMBER |
-
- The
DECIMALdatatype can specify only fixed-point numbers. For this datatype,sdefaults to 0.. - The
FLOATdatatype is a floating-point number with a binary precisionb. The default precision for this datatype is 126 binary or 38 decimal.
- The
Do not define columns with the following SQL/DS and DB2 datatypes, because they have no corresponding Oracle datatype:
GRAPHICLONGVARGRAPHICVARGRAPHICTIME
Note that data of type TIME can also be expressed as Oracle datetime data.
User-Defined Types
User-defined datatypes use Oracle built-in datatypes and other user-defined datatypes as the building blocks of object types that model the structure and behavior of data in applications. The sections that follow describe the various categories of user-defined types.
Object Types
Object types are abstractions of the real-world entities, such as purchase orders, that application programs deal with. An object type is a schema object with three kinds of components:
- A name, which identifies the object type uniquely within that schema.
- Attributes, which are built-in types or other user-defined types. Attributes model the structure of the real-world entity.
- Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C or Java and stored externally. Methods implement operations the application can perform on the real-world entity.
REF Datatypes
An object identifier (represented by the keyword OID) uniquely identifies an object and enables you to reference the object from other objects or from relational tables. A datatype category called REF represents such references. A REF datatype is a container for an object identifier. REF values are pointers to objects.
When a REF value points to a nonexistent object, the REF is said to be 8220;dangling8221;. A dangling REF is different from a null REF. To determine whether a REF is dangling or not, use the condition IS [NOT] DANGLING. For example, given object view oc_orders in the sample schema oe, the column customer_ref is of type REF to type customer_typ, which has an attribute cust_email:
SELECT o.customer_ref.cust_email FROM oc_orders o WHERE o.customer_ref IS NOT DANGLING;
Varrays
An array is an ordered set of data elements. All elements of a given array are of the same datatype. Each element has an index, which is a number corresponding to the position of the element in the array.
The number of elements in an array is the size of the array. Oracle arrays are of variable size, which is why they are called varrays. You must specify a maximum size when you declare the varray.
When you declare a varray, it does not allocate space. It defines a type, which you can use as:
- The datatype of a column of a relational table
- An object type attribute
- A PL/SQL variable, parameter, or function return type
Oracle normally stores an array object either in line (that is, as part of the row data) or out of line (in a LOB), depending on its size. However, if you specify separate storage characteristics for a varray, then Oracle stores it out of line, regardless of its size. Please refer to the varray_col_properties of CREATE TABLE for more information about varray storage.
Nested Tables
A nested table type models an unordered set of elements. The elements may be built-in types or user-defined types. You can view a nested table as a single-column table or, if the nested table is an object type, as a multicolumn table, with a column for each attribute of the object type.
A nested table definition does not allocate space. It defines a type, which you can use to declare:
- The datatype of a column of a relational table
- An object type attribute
- A PL/SQL variable, parameter, or function return type
When a nested table appears as the type of a column in a relational table or as an attribute of the underlying object type of an object table, Oracle stores all of the nested table data in a single table, which it associates with the enclosing relational or object table.
Oracle-Supplied Types
Oracle provides SQL-based interfaces for defining new types when the built-in or ANSI-supported types are not sufficient. The behavior for these types can be implemented in C/C++, Java, or PL/ SQL. Oracle Database automatically provides the low-level infrastructure services needed for input-output, heterogeneous client-side access for new datatypes, and optimizations for data transfers between the application and the database.
These interfaces can be used to build user-defined (or object) types and are also used by Oracle to create some commonly useful datatypes. Several such datatypes are supplied with the server, and they serve both broad horizontal application areas (for example, the Any types) and specific vertical ones (for example, the spatial types).
The Oracle-supplied types, along with cross-references to the documentation of their implementation and use, are described in the following sections:
Any Types
The Any types provide highly flexible modeling of procedure parameters and table columns where the actual type is not known. These datatypes let you dynamically encapsulate and access type descriptions, data instances, and sets of data instances of any other SQL type. These types have OCI and PL/SQL interfaces for construction and access.
XML Types
Extensible Markup Language (XML) is a standard format developed by the World Wide Web Consortium (W3C) for representing structured and unstructured data on the World Wide Web. Universal resource identifiers (URIs) identify resources such as Web pages anywhere on the Web. Oracle provides types to handle XML and URI data, as well as a class of URIs called DBURIRef types to access data stored within the database itself. It also provides a new set of types to store and access both external and internal URIs from within the database.
XMLType
This Oracle-supplied type can be used to store and query XML data in the database. XMLType has member functions you can use to access, extract, and query the XML data using XPath expressions. XPath is another standard developed by the W3C committee to traverse XML documents. Oracle XMLType functions support many W3C XPath expressions. Oracle also provides a set of SQL functions and PL/SQL packages to create XMLType values from existing relational or object-relational data.
XMLType is a system-defined type, so you can use it as an argument of a function or as the datatype of a table or view column. You can also create tables and views of XMLType. When you create an XMLType column in a table, you can choose to store the XML data in a CLOB column or object relationally.
You can also register the schema (using the DBMS_XMLSCHEMA package) and create a table or column conforming to the registered schema. In this case Oracle stores the XML data in underlying object-relational columns by default, but you can specify storage in a CLOB column even for schema-based data.
Queries and DML on XMLType columns operate the same regardless of the storage mechanism.
URI Datatypes
Oracle supplies a family of URI types—URIType, DBURIType, XDBURIType, and HTTPURIType—which are related by an inheritance hierarchy. URIType is an object type and the others are subtypes of URIType. Since URIType is the supertype, you can create columns of this type and store DBURIType or HTTPURIType type instances in this column.
HTTPURIType You can use HTTPURIType to store URLs to external Web pages or to files. Oracle accesses these files using HTTP (Hypertext Transfer Protocol).
XDBURIType You can use XDBURIType to expose documents in the XML database hierarchy as URIs that can be embedded in any URIType column in a table. The XDBURIType consists of a URL, which comprises the hierarchical name of the XML document to which it refers and an optional fragment representing the XPath syntax. The fragment is separated from the URL part by a pound sign (#). The following lines are examples of XDBURIType:
/home/oe/doc1.xml /home/oe/doc1.xml#/orders/order_item
DBURIType DBURIType can be used to store DBURIRef values, which reference data inside the database. Storing DBURIRef values lets you reference data stored inside or outside the database and access the data consistently.
DBURIRef values use an XPath-like representation to reference data inside the database. If you imagine the database as an XML tree, then you would see the tables, rows, and columns as elements in the XML document. For example, the sample human resources user hr would see the following XML tree:
<HR>
<EMPLOYEES>
<ROW>
<EMPLOYEE_ID>205</EMPLOYEE_ID>
<LAST_NAME>Higgins</LAST_NAME>
<SALARY>12000</SALARY>
.. <!-- other columns -->
</ROW>
... <!-- other rows -->
</EMPLOYEES>
<!-- other tables..-->
</HR>
<!-- other user schemas on which you have some privilege on..-->
The DBURIRef is an XPath expression over this virtual XML document. So to reference the SALARY value in the EMPLOYEES table for the employee with employee number 205, we can write a DBURIRef as,
/HR/EMPLOYEES/ROW[EMPLOYEE_ID=205]/SALARY
Using this model, you can reference data stored in CLOB columns or other columns and expose them as URLs to the external world.
URIFactory Package
Oracle also provides the URIFactory package, which can create and return instances of the various subtypes of the URITypes. The package analyzes the URL string, identifies the type of URL (HTTP, DBURI, and so on), and creates an instance of the subtype. To create a DBURI instance, the URL must start with the prefix /oradb. For example, URIFactory.getURI('/oradb/HR/EMPLOYEES') would create a DBURIType instance and URIFactory.getUri('/sys/schema') would create an XDBURIType instance.
Spatial Types
Oracle Spatial is designed to make spatial data management easier and more natural to users of location-enabled applications, geographic information system (GIS) applications, and geoimaging applications. After the spatial data is stored in an Oracle database, you can easily manipulate, retrieve, and relate it to all the other data stored in the database. The following datatypes are not available unless you have installed Oracle Spatial.
SDO_GEOMETRY
The geometric description of a spatial object is stored in a single row, in a single column of object type SDO_GEOMETRY in a user-defined table. Any table that has a column of type SDO_GEOMETRY must have another column, or set of columns, that defines a unique primary key for that table. Tables of this sort are sometimes called geometry tables.
The SDO_GEOMETRY object type has the following definition:
CREATE TYPE SDO_GEOMETRY AS OBJECT ( sgo_gtype NUMBER, sdo_srid NUMBER, sdo_point SDO_POINT_TYPE, sdo_elem_info SDO_ELEM_INFO_ARRAY, sdo_ordinates SDO_ORDINATE_ARRAY);
SDO_TOPO_GEOMETRY
This type describes a topology geometry, which is stored in a single row, in a single column of object type SDO_TOPO_GEOMETRY in a user-defined table.
The SDO_TOPO_GEOMETRY object type has the following definition:
CREATE TYPE SDO_TOPO_GEOMETRY AS OBJECT ( tg_type NUMBER, tg_id NUMBER, tg_layer_id NUMBER, topology_id NUMBER);
SDO_GEORASTER
In the GeoRaster object-relational model, a raster grid or image object is stored in a single row, in a single column of object type SDO_GEORASTER in a user-defined table. Tables of this sort are called GeoRaster tables.
The SDO_GEORASTER object type has the following definition:
CREATE TYPE SDO_GEORASTER AS OBJECT ( rasterType NUMBER, spatialExtent SDO_GEOMETRY, rasterDataTable VARCHAR2(32), rasterID NUMBER, metadata XMLType);
Media Types
Oracle interMedia uses object types, similar to Java or C++ classes, to describe multimedia data. An instance of these object types consists of attributes, including metadata and the media data, and methods. The interMedia datatypes are created in the ORDSYS schema. Public synonyms exist for all the datatypes, so you can access them without specifying the schema name.
ORDImageSignature
The ORDImageSignature object type supports a compact representation of the color, texture, and shape information of image data.
ORDDoc
The ORDDOC object type supports storage and management of any type of media data, including audio, image and video data. Use this type when you want all media to be stored in a single column.
The following datatypes provide compliance with the ISO-IEC 13249-5 Still Image standard, commonly referred to as SQL/MM StillImage.
SI_StillImage
The SI_StillImage object type represents digital images with inherent image characteristics such as height, width, and format.
SI_AverageColor
The SI_AverageColor object type represents a feature that characterizes an image by its average color.
SI_ColorHistogram
The SI_ColorHistogram object type represents a feature that characterizes an image by the relative frequencies of the colors exhibited by samples of the raw image.
SI_PositionalColor
Given an image divided into n by m rectangles, the SI_PositionalColor object type represents the feature that characterizes an image by the n by m most significant colors of the rectangles.
Expression Filter Type
The Oracle Expression Filter allows application developers to manage and evaluate conditional expressions that describe users8217; interests in data. The Expression Filter includes the following datatype:
Expression
Expression Filter uses a virtual datatype called Expression to manage and evaluate conditional expressions as data in database tables. The Expression Filter creates a column of Expression datatype from a VARCHAR2 column by assigning an attribute set to the column. This assignment enables a data constraint that ensures the validity of expressions stored in the column.
You can define conditions using the EVALUATE operator on an Expression datatype to evaluate the expressions stored in a column for some data. If you are using Enterprise Edition, then you can also define an Expression Filter index on a column of Expression datatype to process queries using the EVALUATE operator.
Datatype Comparison Rules
This section describes how Oracle Database compares values of each datatype.
Numeric Values
A larger value is considered greater than a smaller one. All negative numbers are less than zero and all positive numbers. Thus, -1 is less than 100; -100 is less than -1.
The floating-point value NaN (not a number) is greater than any other numeric value and is equal to itself.
Date Values
A later date is considered greater than an earlier one. For example, the date equivalent of 8217;29-MAR-19978242; is less than that of 8217;05-JAN-19988242; and 8217;05-JAN-1998 1:35pm8217; is greater than 8217;05-JAN-1998 10:09am8217;.
Character Values
Character values are compared on the basis of two measures:
- Binary or linguistic sorting
- Blank-padded or nonpadded comparison semantics
The following subsections describe the two measures.
In binary sorting, which is the default, Oracle compares character strings according to the concatenated value of the numeric codes of the characters in the database character set. One character is greater than another if it has a greater numeric value than the other in the character set. Oracle considers blanks to be less than any character, which is true in most character sets.
Linguistic sorting is useful if the binary sequence of numeric codes does not match the linguistic sequence of the characters you are comparing. Linguistic sorting is used if the NLS_COMP parameter is set to LINGUISTIC. In linguistic sorting, all SQL sorting and comparison are based on the linguistic rule specified by NLS_SORT.
Blank-Padded and Nonpadded Comparison Semantics
With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. Oracle then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text literals, or values returned by the USER function.
With nonpadded semantics, Oracle compares two values character by character up to the first character that differs. The value with the greater character in that position is considered greater. If two values of different length are identical up to the end of the shorter one, then the longer value is considered greater. If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the datatype VARCHAR2 or NVARCHAR2.
The results of comparing two character values using different comparison semantics may vary. The table that follows shows the results of comparing five pairs of character values using each comparison semantic. Usually, the results of blank-padded and nonpadded comparisons are the same. The last comparison in the table illustrates the differences between the blank-padded and nonpadded comparison semantics.
| Blank-Padded | Nonpadded |
|---|---|
'ac' > 'ab' |
'ac' > 'ab' |
'ab' > 'a ' |
'ab' > 'a ' |
'ab' > 'a' |
'ab' > 'a' |
'ab' = 'ab' |
'ab' = 'ab' |
'a ' = 'a' |
'a ' > 'a' |
These are some common character sets:
- 7-bit ASCII (American Standard Code for Information Interchange)
- EBCDIC Code (Extended Binary Coded Decimal Interchange Code)
- ISO 8859/1 (International Standards Organization)
- JEUC Japan Extended UNIX
Portions of the ASCII and EBCDIC character sets appear in Table 2-8 and Table 2-9. Uppercase and lowercase letters are not equivalent. The numeric values for the characters of a character set may not match the linguistic sequence for a particular language.
| Symbol | Decimal value | Symbol | Decimal value |
|---|---|---|---|
blank |
32 |
; |
59 |
! |
33 |
< |
60 |
" |
34 |
= |
61 |
# |
35 |
> |
62 |
$ |
36 |
? |
63 |
% |
37 |
@ |
64 |
& |
38 |
A-Z |
65-90 |
' |
39 |
[ |
91 |
( |
40 |
\ |
92 |
) |
41 |
] |
93 |
* |
42 |
^ |
94 |
+ |
43 |
_ |
95 |
, |
44 |
' |
96 |
- |
45 |
a-z |
97-122 |
. |
46 |
{ |
123 |
/ |
47 |
| |
124 |
0-9 |
48-57 |
} |
125 |
: |
58 |
~ |
126 |
Object Values
Object values are compared using one of two comparison functions: MAP and ORDER. Both functions compare object type instances, but they are quite different from one another. These functions must be specified as part of any object type that will be compared with other object types.
Varrays and Nested Tables
Comparison of nested tables is described in 8220;Comparison Conditions8221;.
Datatype Precedence Oracle uses datatype precedence to determine implicit datatype conversion, which is discussed in the section that follows. Oracle datatypes take the following precedence:
- Datetime and interval datatypes
BINARY_DOUBLEBINARY_FLOATNUMBER- Character datatypes
- All other built-in datatypes
Data Conversion
Generally an expression cannot contain values of different datatypes. For example, an expression cannot multiply 5 by 10 and then add 8216;JAMES8217;. However, Oracle supports both implicit and explicit conversion of values from one datatype to another.
Implicit and Explicit Data Conversion
Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:
- SQL statements are easier to understand when you use explicit datatype conversion functions.
- Implicit datatype conversion can have a negative impact on performance, especially if the datatype of a column value is converted to that of a constant rather than the other way around.
- Implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a
VARCHAR2value may return an unexpected year depending on the value of theNLS_DATE_FORMATparameter. - Algorithms for implicit conversion are subject to change across software releases and among Oracle products. Behavior of explicit conversions is more predictable.
Implicit Data Conversion
Oracle Database automatically converts a value from one datatype to another when such a conversion makes sense. Implicit conversion to character datatypes follows these rules:
Table 2-10 is a matrix of Oracle implicit conversions. The table shows all possible conversions, without regard to the direction of the conversion or the context in which it is made. The rules governing these details follow the table.
Table 2-10 Implicit Type Conversion Matrix
| CHAR | VARCHAR2 | NCHAR | NVARCHAR2 | DATE | DATETIME/INTERVAL | NUMBER | BINARY_FLOAT | BINARY_DOUBLE | LONG | RAW | ROWID | CLOB | BLOB | NCLOB | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| CHAR | 8211; | X | X | X | X | X | X | X | X | X | X | 8211; | X | X | X |
| VARCHAR2 | X | 8211; | X | X | X | X | X | X | X | X | X | X | X | 8211; | X |
| NCHAR | X | X | 8211; | X | X | X | X | X | X | X | X | X | X | 8211; | X |
| NVARCHAR2 | X | X | X | 8211; | X | X | X | X | X | X | X | X | X | 8211; | X |
| DATE | X | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; |
| DATETIME/ INTERVAL | X | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | X | 8211; | 8211; | 8211; | 8211; | 8211; |
| NUMBER | X | X | X | X | 8211; | 8211; | 8211; | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; |
| BINARY_FLOAT | X | X | X | X | 8211; | 8211; | X | 8211; | X | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; |
| BINARY_DOUBLE | X | X | X | X | 8211; | 8211; | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; |
| LONG | X | X | X | X | 8211; | X | 8211; | 8211; | 8211; | 8211; | X | 8211; | X | 8211; | X |
| RAW | X | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | X | 8211; | 8211; | 8211; | X | 8211; |
| ROWID | 8211; | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; |
| CLOB | X | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | X | 8211; | 8211; | 8211; | 8211; | X |
| BLOB | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | 8211; | X | 8211; | 8211; | 8211; | 8211; |
| NCLOB | X | X | X | X | 8211; | 8211; | 8211; | 8211; | 8211; | X | 8211; | 8211; | X | 8211; | 8211; |
The following rules govern the direction in which Oracle Database makes implicit datatype conversions:
- During
INSERTandUPDATEoperations, Oracle converts the value to the datatype of the affected column. - During
SELECTFROMoperations, Oracle converts the data from the column to the type of the target variable. - When manipulating numeric values, Oracle usually adjusts precision and scale to allow for maximum capacity. In such cases, the numeric datatype resulting from such operations can differ from the numeric datatype found in the underlying tables.
- When comparing a character value with a numeric value, Oracle converts the character data to a numeric value.
- Conversions between character values or
NUMBERvalues and floating-point number values can be inexact, because the character types andNUMBERuse decimal precision to represent the numeric value, and the floating-point numbers use binary precision. - When converting a
CLOBvalue into a character datatype such asVARCHAR2, or convertingBLOBtoRAWdata, if the data to be converted is larger than the target datatype, then the database returns an error. - Conversions from
BINARY_FLOATtoBINARY_DOUBLEare exact. - Conversions from
BINARY_DOUBLEtoBINARY_FLOATare inexact if theBINARY_DOUBLEvalue uses more bits of precision that supported by theBINARY_FLOAT. - When comparing a character value with a
DATEvalue, Oracle converts the character data toDATE. - When you use a SQL function or operator with an argument of a datatype other than the one it accepts, Oracle converts the argument to the accepted datatype.
- When making assignments, Oracle converts the value on the right side of the equal sign (=) to the datatype of the target of the assignment on the left side.
- During concatenation operations, Oracle converts from noncharacter datatypes to
CHARorNCHAR. - During arithmetic operations on and comparisons between character and noncharacter datatypes, Oracle converts from any character datatype to a numeric, date, or rowid, as appropriate. In arithmetic operations between
CHAR/VARCHAR2andNCHAR/NVARCHAR2, Oracle converts to aNUMBER. - Comparisons between
CHARandVARCHAR2and betweenNCHARandNVARCHAR2types may entail different character sets. The default direction of conversion in such cases is from the database character set to the national character set. Table 2-11 shows the direction of implicit conversions between different character types. - Most SQL character functions are enabled to accept
CLOBs as parameters, and Oracle performs implicit conversions betweenCLOBand character types. Therefore, functions that are not yet enabled forCLOBs can acceptCLOBs through implicit conversion. In such cases, Oracle converts theCLOBs toCHARorVARCHAR2before the function is invoked. If theCLOBis larger than 4000 bytes, then Oracle converts only the first 4000 bytes toCHAR.
Table 2-11 Conversion Direction of Different Character Types
| to CHAR | to VARCHAR2 | to NCHAR | to NVARCHAR2 | |
|---|---|---|---|---|
| from CHAR | 8211; | VARCHAR2 |
NCHAR |
NVARCHAR2 |
| from VARCHAR2 | VARCHAR2 |
8211; | NVARCHAR2 |
NVARCHAR2 |
| from NCHAR | NCHAR |
NCHAR |
8211; | NVARCHAR2 |
| from NVARCHAR2 | NVARCHAR2 |
NVARCHAR2 |
NVARCHAR2 |
8211; |
User-defined types such as collections cannot be implicitly converted, but must be explicitly converted using CAST 8230; MULTISET
Implicit Data Conversion Examples
Text Literal Example The text literal 8217;108242; has datatype CHAR. Oracle implicitly converts it to the NUMBER datatype if it appears in a numeric expression as in the following statement:
SELECT salary + '10' FROM employees;
Character and Number Values Example When a condition compares a character value and a NUMBER value, Oracle implicitly converts the character value to a NUMBER value, rather than converting the NUMBER value to a character value. In the following statement, Oracle implicitly converts 8217;2008242; to 200:
SELECT last_name
FROM employees
WHERE employee_id = '200';
Date Example In the following statement, Oracle implicitly converts 8216;03-MAR-978216; to a DATE value using the default date format 8216;DD-MON-YY8216;:
SELECT last_name
FROM employees
WHERE hire_date = '03-MAR-97';
Rowid Example In the following statement, Oracle implicitly converts the text literal 8216;AAAGH6AADAAAAFGAAN8216; to a rowid value. (Rowids are unique within a database, so to use this example you must know an actual rowid in your database.)
SELECT last_name
FROM employees
WHERE ROWID = 'AAAGH6AADAAAAFGAAN';
Explicit Data Conversion
You can explicitly specify datatype conversions using SQL conversion functions. Table 2-12 shows SQL functions that explicitly convert a value from one datatype to another.
You cannot specify LONG and LONG RAW values in cases in which Oracle can perform implicit datatype conversion. For example, LONG and LONG RAW values cannot appear in expressions with functions or operators. Please refer to 8220;LONG Datatype8221; for information on the limitations on LONG and LONG RAW datatypes.
Table 2-12 Explicit Type Conversions
| to CHAR,VARCHAR2,NCHAR,NVARCHAR2 | to NUMBER | to Datetime/Interval | to RAW | to ROWID | to LONG,LONG RAW | to CLOB, NCLOB,BLOB | to BINARY_FLOAT | to BINARY_DOUBLE | |
|---|---|---|---|---|---|---|---|---|---|
| from CHAR, VARCHAR2, NCHAR, NVARCHAR2 | TO_CHAR (char.)TO_NCHAR (char.) |
TO_NUMBER |
TO_DATETO_TIMESTAMPTO_TIMESTAMP_TZ
|
HEXTORAW |
CHARTO=ROWID |
-- |
TO_CLOBTO_NCLOB |
TO_BINARY_FLOAT |
TO_BINARY_DOUBLE |
| from NUMBER | TO_CHAR (number)TO_NCHAR (number) |
-- |
TO_DATENUMTOYM- INTERVALNUMTODS- INTERVAL |
-- |
-- |
-- |
-- |
TO_BINARY_FLOAT |
TO_BINARY_DOUBLE |
| from Datetime/ Interval | TO_CHAR (date)TO_NCHAR (datetime) |
-- |
-- |
-- |
-- |
-- |
-- |
-- |
-- |
| from RAW | RAWTOHEXRAWTONHEX |
-- |
-- |
-- |
-- |
-- |
TO_BLOB |
-- |
-- |
| from ROWID | ROWIDTOCHAR |
-- |
-- |
-- |
-- |
-- |
-- |
-- |
-- |
| from LONG / LONG RAW | -- |
-- |
-- |
-- |
-- |
-- |
TO_LOB |
-- |
-- |
| from CLOB, NCLOB, BLOB | TO_CHARTO_NCHAR |
-- |
-- |
-- |
-- |
-- |
TO_CLOBTO_NCLOB |
-- |
-- |
| from CLOB, NCLOB, BLOB | TO_CHARTO_NCHAR |
-- |
-- |
-- |
-- |
-- |
TO_CLOBTO_NCLOB |
-- |
-- |
| from BINARY_FLOAT | TO_CHAR (char.)TO_NCHAR (char.) |
TO_NUMBER |
-- |
-- |
-- |
-- |
-- |
TO_BINARY_FLOAT |
TO_BINARY_DOUBLE |
| from BINARY_DOUBLE | TO_CHAR (char.)TO_NCHAR (char.) |
TO_NUMBER |
-- |
-- |
-- |
-- |
-- |
TO_BINARY_FLOAT |
TO_BINARY_DOUBLE |
Literals
The terms literal and constant value are synonymous and refer to a fixed data value. For example, 8216;JACK8217;, 8216;BLUE ISLAND8217;, and 8217;1018242; are all character literals; 5001 is a numeric literal. Character literals are enclosed in single quotation marks so that Oracle can distinguish them from schema object names.
This section contains these topics:
Many SQL statements and functions require you to specify character and numeric literal values. You can also specify literals as part of expressions and conditions. You can specify character literals with the 8216;text8216; notation, national character literals with the N'text' notation, and numeric literals with the integer, or number notation, depending on the context of the literal. The syntactic forms of these notations appear in the sections that follow.
To specify a datetime or interval datatype as a literal, you must take into account any optional precisions included in the datatypes. Examples of specifying datetime and interval datatypes as literals are provided in the relevant sections of 8220;Datatypes8221;.
Text Literals
Use the text literal notation to specify values whenever 'string' or appears in the syntax of expressions, conditions, SQL functions, and SQL statements in other parts of this reference. This reference uses the terms text literal, character literal, and string interchangeably. Text, character, and string literals are always surrounded by single quotation marks. If the syntax uses the term char, you can specify either a text literal or another expression that resolves to character data — for example, the last_name column of the hr.employees table. When char appears in the syntax, the single quotation marks are not used.
The syntax of text literals is as follows:

Description of the illustration text.gif
where N or n specifies the literal using the national character set (NCHAR or NVARCHAR2 data). By default, text entered using this notation is translated into the national character set by way of the database character set when used by the server. To avoid potential loss of data during the text literal conversion to the database character set, set the environment variable ORA_NCHAR_LITERAL_REPLACE to TRUE. Doing so transparently replaces the n' internally and preserves the text literal for SQL processing.
In the top branch of the syntax:
cis any member of the user8217;s character set. A single quotation mark (8216;) within the literal must be preceded by an escape character. To represent one single quotation mark within a literal, enter two single quotation marks.- 8216; 8216; are two single quotation marks that begin and end text literals.
In the bottom branch of the syntax:
Qorqindicates that the alternative quoting mechanism will be used. This mechanism allows a wide range of delimiters for the text string.- The outermost
''are two single quotation marks that precede and follow, respectively, the opening and closingquote_delimiter. cis any member of the user8217;s character set. You can include quotation marks (8220;) in the text literal made up ofccharacters. You can also include thequote_delimiter, as long as it is not immediately followed by a single quotation mark.quote_delimiteris any single- or multibyte character except space, tab, and return. Thequote_delimitercan be a single quotation mark. However, if thequote_delimiterappears in the text literal itself, ensure that it is not immediately followed by a single quotation mark.If the openingquote_delimiteris one of[,{,<, or(, then the closingquote_delimitermust be the corresponding],},>, or). In all other cases, the opening and closingquote_delimitermust be the same character.
Text literals have properties of both the CHAR and VARCHAR2 datatypes:
- Within expressions and conditions, Oracle treats text literals as though they have the datatype
CHARby comparing them using blank-padded comparison semantics. - A text literal can have a maximum length of 4000 bytes.
Here are some valid text literals:
'Hello' 'ORACLE.dbs' 'Jackie''s raincoat' '09-MAR-98' N'nchar literal'
Here are some valid text literals using the alternative quoting mechanism:
q'!name LIKE '%DBMS_%%'!'
q'<'So,' she said, 'It's finished.'>'
q'{SELECT * FROM employees WHERE last_name = 'Smith';}'
nq'ï Ÿ1234 ï'
q'"name like '['"'
Numeric Literals
Use numeric literal notation to specify fixed and floating-point numbers.
Integer Literals
You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference.
The syntax of integer is as follows:

Description of the illustration integer.gif
where digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
An integer can store a maximum of 38 digits of precision.
Here are some valid integers:
7 +255
NUMBER and Floating-Point Literals
You must use the number or floating-point notation to specify values whenever number or n appears in expressions, conditions, SQL functions, and SQL statements in other parts of this reference.
The syntax of number is as follows:

Description of the illustration number.gif
where
- + or - indicates a positive or negative value. If you omit the sign, then a positive value is the default.
digitis one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.- e or E indicates that the number is specified in scientific notation. The digits after the E specify the exponent. The exponent can range from -130 to 125.
- f or F indicates that the number is a 32-bit binary floating point number (of type
BINARY_FLOAT). - d or D indicates that the number is a 64-bit binary floating point number (of type
BINARY_DOUBLE)If you omit f or F and d or D, then the number is of typeNUMBER.The suffixes f (F) and d (D) are supported only in floating-point number literals, not in character strings that are to be converted toNUMBER. That is, if Oracle is expecting aNUMBERand it encounters the string'9', then it converts the string to the number 9. However, if Oracle encounters the string'9f', then conversion fails and an error is returned.
A number of type NUMBER can store a maximum of 38 digits of precision. If the literal requires more precision than provided by NUMBER, BINARY_FLOAT, or BINARY_DOUBLE, then Oracle truncates the value. If the range of the literal exceeds the range supported by NUMBER, BINARY_FLOAT, or BINARY_DOUBLE, then Oracle raises an error.
If you have established a decimal character other than a period (.) with the initialization parameter NLS_NUMERIC_CHARACTERS, then you must specify numeric literals with 'text' notation. In these cases, Oracle automatically converts the text literal to a numeric value.
Note:
You cannot use this notation for floating-point number literals.
For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character of comma, specify the number 5.123 as follows:
'5,123'
Here are some valid NUMBER literals:
25 +6.34 0.5 25e-03 -1
Here are some valid floating-point number literals:
25f +6.34F 0.5d -1D
You can also use the following supplied floating-point literals in situations where a value cannot be expressed as a numeric literal:
| Literal | Meaning | Example |
|---|---|---|
binary_float_nan |
A value of type BINARY_FLOAT for which the condition IS NAN is true |
SELECT COUNT(*) FROM employees WHERE TO_BINARY_FLOAT(commission_pct) != BINARY_FLOAT_NAN; |
binary_float_infinity |
Single-precision positive infinity |
SELECT COUNT(*) FROM employees WHERE salary < BINARY_FLOAT_INFINITY; |
binary_double_nan |
A value of type BINARY_DOUBLE for which the condition IS NAN is true |
SELECT COUNT(*) FROM employees WHERE TO_BINARY_FLOAT(commission_pct) != BINARY_FLOAT_NAN; |
binary_double_infinity |
Double-precision positive infinity |
SELECT COUNT(*) FROM employees WHERE salary < BINARY_FLOAT_INFINITY; |
Datetime Literals
Oracle Database supports four datetime datatypes: DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE.
Date Literals You can specify a DATE value as a string literal, or you can convert a character or numeric value to a date value with the TO_DATE function. DATE literals are the only case in which Oracle Database accepts a TO_DATE expression in place of a string literal.
To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example:
DATE '1998-12-25'
The ANSI date literal contains no time portion, and must be specified in exactly this format ('YYYY-MM-DD'). Alternatively you can specify an Oracle date value, as in the following example:
TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')
The default date format for an Oracle DATE value is specified by the initialization parameter NLS_DATE_FORMAT. This example date format includes a two-digit number for the day of the month, an abbreviation of the month name, the last two digits of the year, and a 24-hour time designation.
Oracle automatically converts character values that are in the default date format into date values when they are used in date expressions.
If you specify a date value without a time component, then the default time is midnight (00:00:00 or 12:00:00 for 24-hour and 12-hour clock time, respectively). If you specify a date value without a date, then the default date is the first day of the current month.
Oracle DATE columns always contain both the date and time fields. Therefore, if you query a DATE column, then you must either specify the time field in your query or ensure that the time fields in the DATE column are set to midnight. Otherwise, Oracle may not return the query results you expect. You can use the TRUNC (date) function to set the time field to midnight, or you can include a greater-than or less-than condition in the query instead of an equality or inequality condition.
Here are some examples that assume a table my_table with a number column row_num and a DATE column datecol:
INSERT INTO my_table VALUES (1, SYSDATE);
INSERT INTO my_table VALUES (2, TRUNC(SYSDATE));
SELECT * FROM my_table;
ROW_NUM DATECOL
---------- ---------
1 03-OCT-02
2 03-OCT-02
SELECT * FROM my_table
WHERE datecol = TO_DATE('03-OCT-02','DD-MON-YY');
ROW_NUM DATECOL
---------- ---------
2 03-OCT-02
SELECT * FROM my_table
WHERE datecol > TO_DATE('02-OCT-02', 'DD-MON-YY');
ROW_NUM DATECOL
---------- ---------
1 03-OCT-02
2 03-OCT-02
If you know that the time fields of your DATE column are set to midnight, then you can query your DATE column as shown in the immediately preceding example, or by using the DATE literal:
SELECT * FROM my_table WHERE datecol = DATE '2002-10-03';
However, if the DATE column contains values other than midnight, then you must filter out the time fields in the query to get the correct result. For example:
SELECT * FROM my_table WHERE TRUNC(datecol) = DATE '2002-10-03';
Oracle applies the TRUNC function to each row in the query, so performance is better if you ensure the midnight value of the time fields in your data. To ensure that the time fields are set to midnight, use one of the following methods during inserts and updates:
- Use the
TO_DATEfunction to mask out the time fields:INSERT INTO my_table VALUES (3, TO_DATE('3-OCT-2002','DD-MON-YYYY')); - Use the
DATEliteral:INSERT INTO my_table VALUES (4, '03-OCT-02');
- Use the
TRUNCfunction:INSERT INTO my_table VALUES (5, TRUNC(SYSDATE));
The date function SYSDATE returns the current system date and time. The function CURRENT_DATE returns the current session date. For information on



















