SQL Objects

This chapter describes the concepts and features of the following objects that configure the database.

Database

Database-related Statements

For more information, refer to the following.

The information related to the database objects can be retrieved through the following views.

Database object-related information

Schema

View name

Description

DICTIONARY_SCHEMA

ALL_NONSCHEMA_COMMENTS

Comment information of user-accessible non-schema objects

INFORMATION_SCHEMA

INFORMATION_SCHEMA_CATALOG_NAME

Database name information

SQL_FEATURES

The SQL standard compatibility information of GOLDILOCKS

SQL_IMPLEMENTATION_INFO

The SQL standard compatibility information of GOLDILOCKS

SQL_PACKAGES

The SQL standard compatibility information of GOLDILOCKS

SQL_PARTS

The SQL standard compatibility information of GOLDILOCKS

SQL_SIZING

The SQL standard compatibility information of GOLDILOCKS

Database Configuration Objects

SQL Objects that Configure the Database

A database is composed of multiple SQL objects.

SQL objects in a database are classified as SQL schema objects and non-schema objects, depending on whether they are included in the SCHEMA.

SQL objects

SQL objects

SQL schema objects are included in the SCHEMA and are as follows.

An SQL schema object can be used with a schema name or without it. If the schema name is omitted, it is interpreted based on the user's schema path.
The following is an example of when objects are created by specifying the schema name.
gSQL> CREATE TABLE my_schema.lineitem ( id INTEGER );
gSQL> CREATE INDEX my_schema.my_index ON my_schema.lineitem ( id );

Non-schema objects are not included in the schema, and they are as follows.

The SQL standard explicitly defines concepts and syntax for SCHEMA objects. However, the concepts of USER and DATABASE are only described, and their syntaxes are not defined in SQL. The SQL standard does not address the TABLESPACE object. In other words, the SQL standard does not explicitly define non-schema objects.
GOLDILOCKS defines USER, SCHEMA, and TABLESPACE as separate descendants of a database. However, other DBMS vendors define the concept of non-schema objects as follows.

Name Space of Objects

An object in the database has a unique name.
An SQL schema object has a distinct name within a schema.
For example, the same lineitem table object can be created in different schemas as follows.
gSQL> CREATE TABLE my_schema.lineitem ( id INTEGER );
gSQL> CREATE TABLE your_schema.lineitem ( name VARCHAR(128) );

SQL schema objects have the following name spaces within a single schema as follows.

A table and a view can not be created under the same name, but a table and an index can be created under the same name, as follows.

• A table and a view can not be created under the same name.

gSQL> CREATE TABLE my_relation ( id INTEGER );
gSQL> CREATE VIEW my_relation ( name ) AS SELECT name FROM tmp_relation;

• A table and an index can be created under the same name.

gSQL> CREATE TABLE my_object ( id INTEGER );
gSQL> CREATE INDEX my_object ON my_table ( name );

A non-schema object has an identifiable name within the database and has the following name spaces.

Namely, USERs can not be created under the same name, but a USER and a SCHEMA can be created under the same name.

• The my_name USER object and the my_name SCHEMA object are created.

gSQL> CREATE USER my_name IDENTIFIED BY my_name WITH SCHEMA my_name;

Built-in Objects

When creating a database, GOLDILOCKS automatically creates objects such as users, schemas, and tablespaces that are necessary for system operation.

Built-in Authorization

When creating a database, the following authorizations are automatically created. The built-in authorizations can not be removed, except for the TEST user.

Built-in Schema

When creating a database, the following schemas are automatically created. The built-in schemas can not be removed.

Built-in Tablespace

When creating a database, the following tablespaces are automatically created. All built-in tablespaces can not be removed.

Built-in Profile

When creating a database, the following "DEFAULT" profile is automatically created. The password parameter information for the automatically created "DEFAULT" profile is as follows.

DEFAULT profile configuration

Parameter

Value

FAILED_LOGIN_ATTEMPTS

10

PASSWORD_LOCK_TIME

1

PASSWORD_LIFE_TIME

180

PASSWORD_GRACE_TIME

7

PASSWORD_REUSE_MAX

UNLIMITED

PASSWORD_REUSE_TIME

UNLIMITED

PASSWORD_VERIFY_FUNCTION

NULL

The following are the characteristics of the default values in the "DEFAULT" profile.

Profile

Profile-related Statements

For more information, refer to the following.

Profile object-related information

Schema

View

Description

DICTIONARY_SCHEMA

DBA_PROFILES

All profile information

DBA_USERS

User's profile information

Concept of Profile

GOLDILOCKS performs user authentication for database security. A password management policy is necessary because user authentication passwords are vulnerable to theft, forgery, and misuse.
A profile includes password management policy information like this. DBAs or security administrators assign the profile to a user and apply the password management policy that is appropriate for the user's role.

Creating, Altering, Assigning Profile

A profile is created using the CREATE PROFILE statement.

CREATE PROFILE profile1 LIMIT 
       FAILED_LOGIN_ATTEMPTS     10  
       PASSWORD_LOCK_TIME        1 
       PASSWORD_LIFE_TIME        180 
       PASSWORD_GRACE_TIME       7
       PASSWORD_REUSE_MAX        UNLIMITED
       PASSWORD_REUSE_TIME       UNLIMITED
       PASSWORD_VERIFY_FUNCTION  NULL;

A profile is assigned using the CREATE USER or ALTER USER statements.

CREATE USER u1 IDENTIFIED BY u1 PROFILE profile1;
ALTER USER u2 PROFILE profile1;

The profile parameters are updated using the ALTER PROFILE statement.

ALTER PROFILE profile1 LIMIT 
      PASSWORD_REUSE_MAX        3
      PASSWORD_REUSE_TIME       30;
If a profile is not assigned to a user, the user is not restricted in creating or using a password.
If a created profile or the DEFAULT profile is assigned to a user, the user must comply with the profile's password policies when creating or using a password.

Password Settings of DEFAULT Profile

When the default profile is assigned to a user, the password is managed as follows.

DEFAULT profile of password

Parameter

Default

setting

Description

FAILED_LOGIN_ATTEMPS

10

The allowed number of consecutive login failures

The account is locked after 10 consecutive failed login attempts.

PASSWORD_LOCK_TIME

1

The account lockout duration

If the number of consecutive login failures exceeds the allowed value, the account is locked for one day.

PASSWORD_LIFE_TIME

180

The password lifetime

The password expires after 180 days.

PASSWORD_GRACE_TIME

7

The duration allowed to change the password after expiration.

The password must be changed within seven days after the first login following expiration. If the user does not change the password within this period, they will not be able to log in using the expired password.

PASSWORD_REUSE_MAX

UNLIMITED

It is the number of times the password cannot be reused.

PASSWORD_REUSE_MAX and PASSWORD_REUSE_TIME must be set together. If both values are set to UNLIMITED, the password can always be reused.

PASSWORD_REUSE_TIME

UNLIMITED

The duration during which a password cannot be reused

Account Lockout

If the number of consecutive login attempt failures exceeds the value specified in FAILED_LOGIN_ATTEMPTS, the account is locked for the duration specified in PASSWORD_LOCK_TIME.

CREATE PROFILE profile1 LIMIT 
       FAILED_LOGIN_ATTEMPTS     10  
       PASSWORD_LOCK_TIME        1;

ALTER USER u1 PROFILE profile1;

When user u1's login attempts fail consecutively more than 10 times, the account is locked for one day. After one day, the account is automatically unlocked.

If the PASSWORD_LOCK_TIME value is not specified, it is considered to be the value specified in the PASSWORD_LIFE_TIME of the DEFAULT profile.

If the PASSWORD_LOCK_TIME value is set to UNLIMITED, the locked account will not be automatically released. Therefore, the following statement should be executed to unlock the account.

ALTER USER u1 ACCOUNT UNLOCK;

Upon a successful login, the number of failed login attempts is reset to zero.

A security manager can explicitly lock user accounts. In this case, the accounts will not be automatically released, so the security manager must unlock the locked accounts.

ALTER USER u1 ACCOUNT LOCK;
ALTER USER u1 ACCOUNT UNLOCK;

Password Lifetime

PASSWORD_LIFE_TIME specifies the lifetime of the password. After this period, the password expires.
A user, DBA or security manager should change the password once it has expired.
CREATE PROFILE profile1 LIMIT 
       PASSWORD_LIFE_TIME        180
       PASSWORD_GRACE_TIME       7;

ALTER USER u1 PROFILE profile1;
The grace period begins when user u1 attempts to log in for the first time after 180 days.
During the seven-day grace period, the user will be reminded to enter a new password each time they access their account, until the password is changed. If the seven-day grace period expires without the password being changed, the user will not be able to log in until a new password is entered.
A password can expire by using the CREATE USER or ALTER USER statements.
ALTER USER u1 PASSWORD EXPIRE;

After the password has expired, when the user attempts to log in, the password expiration error (ERR-28000(16312): The password has expired) will occur, as shown in the example below, and a new password must be entered.

% gsql u1 u1

ERR-28000(16312): the password has expired

Changing password for u1
New password: 
Retype new password: 
Connected to GOLDILOCKS Database.

gSQL>

Password Reuse

The password can be reused after it has been changed the specified number of times, as defined by PASSWORD_REUSE_MAX. Additionally, it can only be reused after the time period specified in PASSWORD_REUSE_TIME has passed.

CREATE PROFILE profile1 LIMIT 
       PASSWORD_REUSE_MAX        2
       PASSWORD_REUSE_TIME       1;

ALTER USER u1 PROFILE profile1;

User u1 can reuse the current password after it has been changed for twice and 10 days have passed.

ALTER USER u1 IDENTIFIED BY u1 REPLACE u1;
ALTER USER u1 IDENTIFIED BY u1 REPLACE u1
*
ERROR at line 1:
ORA-28007: the password cannot be reused

ALTER USER u1 IDENTIFIED BY u2 REPLACE u1;

User altered.

ALTER USER u1 IDENTIFIED BY u3 REPLACE u2;

User altered.

• 10 days have passed.

ALTER USER u1 IDENTIFIED BY u1 REPLACE u3;

User altered.
Both conditions must be satisfied to reuse the old password. If only one of the values in PASSWORD_REUSE_MAX or PASSWORD_REUSE_TIME is set to UNLIMITED, the password cannot be reused. If both values are set to UNLIMITED, the password can always be reused.
Password reuse

PASSWORD_REUSE_MAX

PASSWORD_REUSE_TIME

Password reusability

Integer value

Integer value

If both of the conditions are satisfied, it can be reused.

Integer value

UNLIMITED

It can not be reused.

UNLIMITED

Integer value

It can not be reused.

UNLIMITED

UNLIMITED

It is always reusable.

Password Complexity Verification

Password complexity verification checks whether the password is complex enough to protect against unauthorized access to the system.
GOLDILOCKS supports the following method of password complexity verification.
Password complexity verification

Method

Details

KISA_VERIFY_FUNCTION

  • At least 8 characters

  • At least one letter

  • At least one digit

  • At least one special character

ORA12C_VERIFY_FUNCTION

  • At least 8 characters

  • At least one letter

  • At least one digit

  • Must not contain the database name

  • Must not contain the username or the reversed username

  • Must not contain 'goldilocks'

  • Must not contain 'oracle'

  • The following simple passwords cannot be used

    • welcome1, database1, account1, user1234, password1, oracle123, computer1, abcdefg1, change_on_install

  • Must differ by at least 3 characters from the previous password

ORA12C_STRONG_VERIFY_FUNCTION

  • At least 9 characters

  • At least two uppercase letters

  • At least two lowercase letters

  • At least two digits

  • At least two special characters

  • Must differ by at least 4 characters from the previous password

VERIFY_FUNCTION_11G

  • At least 8 characters

  • At least one letter

  • At least one digit

  • Must not contain the username

  • Must differ by at least 3 characters from the previous password

VERIFY_FUNCTION

  • Must not be the same as the username

  • At least 4 characters

  • At least one letter

  • At least one digit

  • At least one special character

  • The following simple passwords cannot be used.

    • welcome, database, account, user, password, oracle, computer, abcd

  • Must differ by at least 3 characters from the previous password

For more information about profile and user settings, refer to the CREATE PROFILE and CREATE USER statements.

Audit Policy

Audit Policy-related Statement

For more information, refer to the following.

Audit policy object-related information

Schema

View

Description

DICTIONARY_SCHEMA

AUDIT_POLICIES

Information about all audit policies

AUDIT_POLICY_OPTIONS

Information about the audit policy option

AUDIT_POLICY_ENABLED

Information about activating the audit policy

Examples

The AUDIT SYSTEM ON DATABASE privilege is required to perform the following actions.

Creating Audit Policy

Perform the CREATE AUDIT POLICY statement to create an audit policy object.

The following is an example of creating an audit_t1_dml object to audit DML operations on the u1.t1 table.

CREATE AUDIT POLICY audit_t1_dml
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
;

Audit policy created.

Query the AUDIT_POLICY_OPTIONS view to check the audit policy options information.

SELECT policy_name
     , audit_option
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'AUDIT_T1_DML'
 ORDER BY audit_option
;

POLICY_NAME  AUDIT_OPTION OBJECT_SCHEMA OBJECT_NAME
------------ ------------ ------------- -----------
AUDIT_T1_DML DELETE       U1            T1         
AUDIT_T1_DML INSERT       U1            T1         
AUDIT_T1_DML UPDATE       U1            T1         

3 rows selected.

Activating Audit Policy

Use the AUDIT POLICY statement to activate the audit policy.

The following is an example of activating an audit policy to generate an audit record when a user, other than 'u1' and 'sys', successfully performs a DML operation on the 'u1.t1' table.

AUDIT POLICY audit_t1_dml
      EXCEPT u1, sys
      WHENEVER SUCCESSFUL
;

The activated audit policy is applied to newly created sessions, but it does not affect existing sessions.

View information about the activated audit policy using the AUDIT_POLICY_ENABLED.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
 ORDER BY user_name
;

POLICY_NAME             ENABLED_OPT           USER_NAME  WHEN_SUCCESS WHEN_FAILURE
-------------------- --------------------- ---------- ------------ ---------
AUDIT_T1_DML         EXCEPT                   SYS        YES          NO
AUDIT_T1_DML         EXCEPT                   U1         YES          NO

2 rows selected.

Once the audit policy is activated, the corresponding actions will generate audit records.

The following is an example of when the u2 user successfully performs SQL statements.

SELECT COUNT(*) FROM u1.t1;
INSERT INTO u1.t1 VALUES ( 1 );
UPDATE u1.t1 SET id = id + 1 WHERE id = 1;
DELETE u1.t1 WHERE id = 2;
COMMIT;
In the example above, INSERT, UPDATE, and DELETE are the target actions for auditing, so they create  audit records, but SELECT and COMMIT are not target actions for auditing, so they do not create audit records.

View Audit Trail

SELECT ON DICTIONARY_SCHEMA.AUDIT_TRAIL privilege for the AUDIT_TRAIL view is required to view audit records.

The following is an example of viewing the audit trail created by the audit_t1_dml audit policy.

SELECT policy_name
     , logon_username
     , action_name
     , object_schema
     , object_name
     , sql_text
  FROM audit_trail
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  LOGON_USERNAME ACTION_NAME OBJECT_SCHEMA OBJECT_NAME SQL_TEXT                                 
------------ -------------- ----------- ------------- ----------- -----------------------------------------
AUDIT_T1_DML U2             INSERT      U1            T1          INSERT INTO u1.t1 VALUES ( 1 )           
AUDIT_T1_DML U2             UPDATE      U1            T1          UPDATE u1.t1 SET c1 = c1 + 1 WHERE c1 = 1
AUDIT_T1_DML U2             DELETE      U1            T1          DELETE u1.t1 WHERE c1 = 2                

3 rows selected.

Dropping Audit Trail

When an audit policy is activated, the size of the audit trail continues to increase.
Execute the following statement to drop the audit trail.
ALTER DATABASE CLEAR AUDIT TRAIL;

Store it in the user table and then drop it as follows to maintain the audit trail.

CREATE TABLE my_audit_trail
AS SELECT *
     FROM audit_trail
     WITH NO DATA;
INSERT INTO my_audit_trail SELECT * FROM audit_trail;
ALTER DATABASE CLEAR AUDIT TRAIL;

Create and manage the view as follows to view both the stored audit trail and the current audit_trail.

CREATE VIEW unified_audit_trail
AS 
SELECT * FROM my_audit_trail
 UNION ALL
SELECT * FROM dictionary_schema.audit_trail
;

Deactivating Audit Policy

Deactivate the audit policy using the following statement.

NOAUDIT POLICY audit_t1_dml;

Deactivating the audit policy only affects new sessions but does not impact the activation information of existing sessions.

Dropping Audit Policy

Execute the following statement to drop the audit policy object.

DROP AUDIT POLICY audit_t1_dml;
The audit policy object must be deactivated before it can be dropped, and dropping the object does not affect existing sessions.

Concept of Audit Policy

Audit Trail

Viewing Audit Trail

Audit records can be viewed using the DICTIONARY_SCHEMA.AUDIT_TRAIL view.

The SELECT privilege is required to view the AUDIT_TRAIL view.

GRANT SELECT ON DICTIONARY_SCHEMA.AUDIT_TRAIL TO user_name;

The AUDIT_TRAIL view contains the following information.

Column information

Information

Column name

Description

Session

information

MEMBER_NAME

Cluster member name

SESSION_ID

Session identifier

SESSION_SERIAL

Session serial number

LOGON_USERNAME

Logon user name of the user whose actions were audited

CURRENT_USERNAME

Effective user for the statement execution

SERVER_PROCESS

Server process identifier for the session

Peer client

information

CLIENT_PROGRAM_NAME

Client program used for session

CLIENT_USERNAME

Client operating system user name for the session

CLIENT_PROCESS

Client process identifier for the session

CLIENT_HOST

Client host ip address for the session

CLIENT_PORT

Client port number for the session

CLIENT_TERMINAL

Client terminal name for the session

SQL

information

TRANSACTION_ID

Transaction identifier

SCN

System change number (SCN) string of the query at the time of the event

GCN

Global change number (GCN) of the query at the time of the event

DCN

Domain change number (DCN) of the query at the time of the event

LCN

Local change number (LCN) of the query at the time of the event

STMT_NO

Numeric number for each statement run in a session

SQL_TEXT

SQL associated with the event

SQL_BINDS

List of bind variables, if any, associated with SQL_TEXT

RETURN_CODE

Error code generated by the action, zero if the action succeeded

ERROR_MESSAGE

Error message generated by the action, null if the action succeeded

Event

information

ENTRY_ID

Audit trail entry identifier in the session

EVENT_TIMESTAMP

Timestamp of the creation of the audit trail entry in local time zone

POLICY_NAME

Audit policy name that caused the current audit record

PRIVILEGE_USED

Database privilege used to execute the action

ACTION_NAME

Action name executed by the user

OBJECT_TYPE

Object type of object affected by the action

OBJECT_SCHEMA

Schema name of object affected by the action

OBJECT_NAME

Object name of object affected by the action

Storing Audit Trail

The AUDIT_TRAIL view consists of the following tables.

Audit records, which configure an audit trail, are divided into multiple tables and then stored.
The schema for these tables is DEFINITION_SCHEMA, and they are stored in the MEM_AUX_TBS tablespace.

Creating Audit Record

When the audit policy is activated, an audit record is created whenever an action matching the specified conditions occurs. If multiple actions matching the audit conditions occur, one or more audit records are created.
CREATE AUDIT POLICY p1
       PRIVILEGES INSERT ANY TABLE
       ACTIONS INSERT;

AUDIT POLICY p1;
INSERT INTO other_user.t1 VALUES ( 1 );
CREATE AUDIT POLICY p1
       ACTIONS SELECT ON u1.t1
             , SELECT ON u1.t2;

AUDIT POLICY p1;
SELECT COUNT(*) FROM u1.t1 A, u1.t2 B WHERE A.id = B.id;
CREATE AUDIT POLICY p1
       PRIVILEGES INSERT ANY TABLE;
AUDIT POLICY p1;

CREATE AUDIT POLICY p2
       ACTIONS INSERT;
AUDIT POLICY p2;
INSERT INTO other.t1 VALUES (1);

Dropping Audit Trail (purge)

Execute the following statement to drop the audit trail.

ALTER DATABASE CLEAR AUDIT TRAIL;

Create a user table and store the old audit records in it as follows.

CREATE TABLE my_audit_trail AS SELECT * FROM audit_trail WITH NO DATA;

Then, regularly store it using the INSERT .. SELECT statement before dropping the audit trail.

INSERT INTO my_audit_trail SELECT * FROM audit_trail;

ALTER DATABASE CLEAR AUDIT TRAIL;

To store audit records for a specific period, execute the DELETE statement using the EVENT_TIMESTAMP column.

INSERT INTO my_audit_trail SELECT * FROM audit_trail;

DELETE FROM my_audit_trail WHERE event_timestamp < ADD_MONTHS( sysdate, -3 );

ALTER DATABASE CLEAR AUDIT TRAIL;

View the old and current audit records together by creating a view as follows.

CREATE VIEW audit_trail_view
AS SELECT * FROM dictionary_schema.audit_trail
   UNION ALL
   SELECT * FROM my_audit_trail; 

SELECT * FROM audit_trail_view;

Audit Policy Configuration

The audit policy may include the following options.

Multiple audit policies can be created to manage audit options, but it is preferable to manage multiple audit options using a smaller number of audit policies.
The information for activated audit policies is constructed as session information at logon time, so the fewer the number of audit policies, the lower the load. Additionally, if multiple audit policies are activated, the system determines whether to create an audit record for an SQL statement, which may result in additional load due to the creation of multiple audit records.
Audit policy information constructed in a session at logon time is not affected by dropping, altering, activating or deactivating an audit policy.  
Altering an audit policy only applies to newly logged-in sessions.

Privilege Auditing

Privilege auditing is configured to audit when an SQL statement is successfully executed using database privileges. It does not create an audit record for the sys user, who is the database owner, based on privilege auditing.

The database privilege that can be listed for privilege auditing can be viewed through the V$AUDITABLE_DB_PRIVILEGES view.

gSQL> SELECT privilege_name FROM v$auditable_db_privileges;

PRIVILEGE_NAME   
-----------------
ADMINISTRATION   
ALTER DATABASE   
ALTER SYSTEM     
ACCESS CONTROL   
CREATE USER      
ALTER USER       
DROP USER        
CREATE ROLE      
DROP ROLE        
GRANT ROLE       
CREATE TABLESPACE
ALTER TABLESPACE 
DROP TABLESPACE  
USAGE TABLESPACE 
CREATE SCHEMA    
DROP SCHEMA      
ANALYZE ANY      
CREATE ANY TABLE 
ALTER ANY TABLE  
DROP ANY TABLE   
SELECT ANY TABLE     
INSERT ANY TABLE     
DELETE ANY TABLE     
UPDATE ANY TABLE     
LOCK ANY TABLE       
CREATE ANY VIEW      
DROP ANY VIEW        
CREATE ANY SEQUENCE  
ALTER ANY SEQUENCE   
DROP ANY SEQUENCE    
USAGE ANY SEQUENCE   
CREATE ANY INDEX     
ALTER ANY INDEX      
DROP ANY INDEX       
CREATE ANY SYNONYM   
DROP ANY SYNONYM     
CREATE PUBLIC SYNONYM
DROP PUBLIC SYNONYM  
CREATE PROFILE       
ALTER PROFILE        
DROP PROFILE         
CREATE ANY PROCEDURE 
ALTER ANY PROCEDURE  
DROP ANY PROCEDURE   
EXECUTE ANY PROCEDURE
AUDIT SYSTEM         
PURGE DBA_RECYCLEBIN 
CREATE ANY PACKAGE   
ALTER ANY PACKAGE    
DROP ANY PACKAGE     
EXECUTE ANY PACKAGE  
CREATE ANY LIBRARY   
ALTER ANY LIBRARY    
DROP ANY LIBRARY     
EXECUTE ANY LIBRARY  
CREATE ANY TRIGGER   
ALTER ANY TRIGGER    
DROP ANY TRIGGER     

58 rows selected.

The following is an example of when a user, u1, who has the SELECT ANY TABLE privilege, activates an audit policy for privilege auditing.

CREATE AUDIT POLICY p1
       PRIVILEGES SELECT ANY TABLE;

AUDIT POLICY p1;

Whether an audit record is created when user u1 performs the following two statements is as follows.

Use the AUDIT_POLICY_OPTIONS view to view privilege auditing information as follows.

SELECT audit_option 
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'P1'
;

AUDIT_OPTION         AUDIT_OPTION_TYPE    OBJECT_SCHEMA     OBJECT_NAME
-------------------- -------------------- ----------------- ------------
SELECT ANY TABLE     DATABASE PRIVILEGE   null              null

Object Action Auditing

It audits SQL statements performed on a specific object.
The actions to be audited for each object type are as follows.
Audit actions per object type

Object type

Actions

Table

ALTER, COMMENT, DELETE, GRANT, INDEX, INSERT, LOCK, RENAME, SELECT, UPDATE

View

ALTER, COMMENT, GRANT, SELECT

Sequence

ALTER, COMMENT, GRANT, SELECT

Stored function/

procedure

ALTER, COMMENT, EXECUTE, GRANT

Package

ALTER, COMMENT, EXECUTE, GRANT

Library

COMMENT, EXECUTE, GRANT

Create the audit policy as follows to audit DML operations on table u1.t1.

CREATE AUDIT POLICY audit_t1_dml
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
;

Information about object action auditing can be viewed by querying the AUDIT_POLICY_OPTIONS view as follows.

SELECT audit_option
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'AUDIT_T1_DML'
 ORDER BY audit_option
;

AUDIT_OPTION AUDIT_OPTION_TYPE OBJECT_SCHEMA OBJECT_NAME
------------ ----------------- ------------- -----------
DELETE       OBJECT ACTION     U1            T1         
INSERT       OBJECT ACTION     U1            T1         
UPDATE       OBJECT ACTION     U1            T1         

3 rows selected.
The ALL option, such as ALL ON schema.object, represents all audit actions that can be defined for the corresponding object.

The following is an example of using the ALL option together with other options.

CREATE AUDIT POLICY p1
       ACTIONS ALL ON u1.seq1
             , ALTER ON u1.seq1
;

Audit policy created.

SELECT audit_option 
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'P1'
 ORDER BY audit_option
;

AUDIT_OPTION AUDIT_OPTION_TYPE OBJECT_SCHEMA OBJECT_NAME
------------ ----------------- ------------- -----------
ALL          OBJECT ACTION     U1            SEQ1       
ALTER        OBJECT ACTION     U1            SEQ1       

2 rows selected.

When dropping the ALL option as follows, not all audit options are dropped—only the ALL option is dropped.

ALTER AUDIT POLICY p1
      DROP ACTIONS ALL ON u1.seq1;

Audit Policy altered.



SELECT audit_option 
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'P1'
 ORDER BY audit_option;


AUDIT_OPTION AUDIT_OPTION_TYPE OBJECT_SCHEMA OBJECT_NAME
------------ ----------------- ------------- -----------
ALTER        OBJECT ACTION     U1            SEQ1       

1 row selected.
The auditing of success or failure for EXECUTE on a stored function or stored procedure is determined solely by whether it is executable at the time of execution.

The following is an example of executing a SELECT statement that includes a stored function.

SELECT others.func1( t1.c1 )
  FROM t1;
It corresponds to WHENEVER NOT SUCCESSFUL when the call to others.func1() fails due to an error, such as a lack of privilege. It corresponds to WHENEVER SUCCESSFUL if the call to others.func1() succeeds, even if an error occurs while executing an SQL statement within the stored function.

System Action Auditing

It audits an SQL statement regardless of a specific object.
Valid system actions can be queried from the V$AUDITABLE_SYSTEM_ACTIONS view.
gSQL> SELECT action_name FROM v$auditable_system_actions;

ACTION_NAME    
---------------
ALL            
DDL            
SELECT         
INSERT         
UPDATE         
DELETE         
MERGE          
EXECUTE        
CREATE TABLE   
DROP TABLE     
ALTER TABLE    
LOCK TABLE     
TRUNCATE TABLE 
ANALYZE TABLE  
RENAME         
CREATE INDEX   
DROP INDEX     
ALTER INDEX    
CREATE SEQUENCE
DROP SEQUENCE
ALTER SEQUENCE     
GRANT              
REVOKE             
CREATE SYNONYM     
DROP SYNONYM       
CREATE VIEW        
DROP VIEW          
ALTER VIEW         
CREATE PROCEDURE   
DROP PROCEDURE     
ALTER PROCEDURE    
CREATE FUNCTION    
DROP FUNCTION      
ALTER FUNCTION     
CREATE PACKAGE     
DROP PACKAGE       
ALTER PACKAGE      
CREATE PACKAGE BODY
CREATE TRIGGER     
DROP TRIGGER       
ALTER TRIGGER      
COMMENT            
ALTER DATABASE     
CREATE PROFILE     
DROP PROFILE       
ALTER PROFILE      
CREATE TABLESPACE  
DROP TABLESPACE    
ALTER TABLESPACE   
CREATE ROLE        
DROP ROLE          
CREATE USER        
DROP USER          
ALTER USER         
CHANGE PASSWORD    
CREATE SCHEMA      
DROP SCHEMA        
CREATE AUDIT POLICY
DROP AUDIT POLICY  
ALTER AUDIT POLICY
AUDIT                  
NOAUDIT                
ALTER SYSTEM           
ALTER SESSION          
ANALYZE SYSTEM         
COMMIT                 
ROLLBACK               
SAVEPOINT              
LOGON                  
LOGOFF                 
SET SESSION            
SET ROLE               
SET TRANSACTION        
SET CONSTRAINTS        
CREATE CLUSTER GROUP   
DROP CLUSTER GROUP     
ALTER CLUSTER GROUP    
CREATE CLUSTER LOCATION
DROP CLUSTER LOCATION  
ALTER CLUSTER LOCATION 
PURGE CONSTRAINT    
PURGE INDEX         
PURGE TRIGGER       
PURGE TABLE         
PURGE TABLESPACE    
PURGE RECYCLEBIN    
PURGE DBA_RECYCLEBIN
FLASHBACK TABLE     
CREATE LIBRARY      
DROP LIBRARY        

90 rows selected.

The system action name corresponding to each SQL statement can be viewed by querying the V$SQL_COMMAND view.

gSQL> SELECT command , audit_action FROM v$sql_command;

COMMAND                                         AUDIT_ACTION       
----------------------------------------------- -------------------
ALTER AUDIT POLICY                              ALTER AUDIT POLICY 
ALTER CLUSTER GROUP .. ADD CLUSTER MEMBER       ALTER CLUSTER GROUP
ALTER DATABASE DROP INACTIVE CLUSTER MEMBERS    ALTER DATABASE     
ALTER DATABASE DROP OFFLINE SEGMENTS            ALTER DATABASE     
ALTER DATABASE DROP UNUSABLE SEGMENTS           ALTER DATABASE     
ALTER DATABASE SYNCHRONIZE                      ALTER DATABASE    

... Ellipsis ...

PURGE RECYCLEBIN                                           PURGE RECYCLEBIN     
PURGE DBA_RECYCLEBIN                                       PURGE DBA_RECYCLEBIN 
FLASHBACK TABLE                                            FLASHBACK TABLE      
ALTER DATABASE ENABLE CHANGE TRACKING [ USING FILE REUSE ] null                 
ALTER DATABASE DISABLE CHANGE TRACKING                     null                 
ALTER DATABASE RENAME GLOBAL TRANSACTION LOGFILE           null                 

234 rows selected.

The following is an example of creating an audit policy that includes a system action and querying an audit option.

CREATE AUDIT POLICY p1
       ACTIONS SELECT
             , DROP TABLE
             , DROP USER
;

Audit Policy created.


SELECT audit_option 
     , audit_option_type
     , object_schema
     , object_name
  FROM audit_policy_options
 WHERE policy_name = 'P1'
 ORDER BY audit_option
;

AUDIT_OPTION AUDIT_OPTION_TYPE OBJECT_SCHEMA OBJECT_NAME
------------ ----------------- ------------- -----------
DROP TABLE   SYSTEM ACTION     null          null       
DROP USER    SYSTEM ACTION     null          null       
SELECT       SYSTEM ACTION     null          null       

3 rows selected.

Useful Audit Policy

The following is an example of defining a useful audit policy.

CREATE AUDIT POLICY AUDIT_LOGON_FAILURES
       ACTIONS LOGON
;

AUDIT POLICY AUDIT_LOGON_FAILURES
      WHENEVER NOT SUCCESSFUL
;
CREATE AUDIT POLICY AUDIT_DDL
       ACTIONS DDL
;

AUDIT POLICY AUDIT_DDL
      WHENEVER SUCCESSFUL
;
CREATE AUDIT POLICY AUDIT_DATABASE_PARAMETER
       ACTIONS ALTER DATABASE
             , ALTER SYSTEM
;

AUDIT POLICY AUDIT_DATABASE_PARAMETER
      WHENEVER SUCCESSFUL
;
CREATE AUDIT POLICY AUDIT_ACCOUNT_MGMT
       ACTIONS CREATE USER
             , DROP USER
             , ALTER USER
             , CHANGE PASSWORD
             , GRANT
             , REVOKE
;

AUDIT POLICY AUDIT_ACCOUNT_MGMT
;
CREATE AUDIT POLICY AUDIT_CIS_RECOMMENDATIONS
       PRIVILEGES ALTER SYSTEM
                , ALTER DATABASE 
          ACTIONS CREATE USER
                , DROP USER
                , ALTER USER
                , CHANGE PASSWORD  
                , GRANT
                , REVOKE
                , CREATE PROFILE
                , ALTER PROFILE
                , DROP PROFILE 
                , CREATE SYNONYM
                , DROP SYNONYM 
                , CREATE PROCEDURE
                , DROP PROCEDURE
                , ALTER PROCEDURE
;

AUDIT POLICY AUDIT_CIS_RECOMMENDATIONS
      WHENEVER SUCCESSFUL
;

Managing Audit Policy

Activating Audit Poilcy

An audit policy object does not begin auditing until it is activated.

To perform auditing, the audit policy object must be activated using the AUDIT POLICY statement as follows.

CREATE AUDIT POLICY audit_t1_dml
       ACTIONS INSERT ON u1.t1
             , DELETE ON u1.t1
             , UPDATE ON u1.t1
;

Audit policy created.  

AUDIT POLICY audit_t1_dml;

Audit succeeded.

When activating an audit policy, it audits only new sessions and does not affect existing sessions.

When activating an audit policy using the AUDIT POLICY statement, you can specify the user to audit using the BY or EXCEPT clause, or you can audit success/ failure of an audit action using the WHENEVER clause.

Information about the activated audit policy can be viewed by querying the AUDIT_POLICY_ENABLED view.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME  WHEN_SUCCESS WHEN_FAILURE
------------ ----------- ---------- ------------ ------------
AUDIT_T1_DML BY          ALL USERS  YES          YES

If the auditing target user is omitted, as shown in the example above, it outputs ALL USERS, meaning all users.

Note the following when using the BY clause and EXCEPT clause.

AUDIT POLICY audit_t1_dml BY u1;

Audit succeeded.

AUDIT POLICY audit_t1_dml EXCEPT u2;

ERR-42000(16475): audit policy already applied with the BY clause
AUDIT POLICY audit_t1_dml BY u1;

Audit succeeded.

AUDIT POLICY audit_t1_dml BY u2;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          YES         
AUDIT_T1_DML BY          U2        YES          YES         

2 rows selected.
AUDIT POLICY audit_t1_dml BY u1, u2;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          YES         
AUDIT_T1_DML BY          U2        YES          YES         

2 rows selected.
AUDIT POLICY audit_t1_dml EXCEPT u1;

Audit succeeded.

AUDIT POLICY audit_t1_dml EXCEPT u2;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML EXCEPT      U2        YES          YES         

1 row selected.
AUDIT POLICY audit_t1_dml EXCEPT u1, u2;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML EXCEPT      U1        YES          YES         
AUDIT_T1_DML EXCEPT      U2        YES          YES         

2 rows selected.
AUDIT POLICY audit_t1_dml BY u1 WHENEVER SUCCESSFUL;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          NO          

1 row selected.

AUDIT POLICY audit_t1_dml BY u1 WHENEVER NOT SUCCESSFUL;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          YES         

1 row selected.
AUDIT POLICY audit_t1_dml BY u1;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          YES         

1 row selected.
AUDIT POLICY audit_t1_dml EXCEPT u1 WHENEVER SUCCESSFUL;

Audit succeeded.

AUDIT POLICY audit_t1_dml EXCEPT u1 WHENEVER NOT SUCCESSFUL;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML EXCEPT      U1        NO           YES         

1 row selected.
AUDIT POLICY audit_t1_dml EXCEPT u1;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML EXCEPT      U1        YES          YES         

1 row selected.

Deactivating Audit Policy

The NOAUDIT POLICY statement must be executed to deactivate an audit policy. 
The NOAUDIT POLICY statement applies only to a new session and does not affect existing sessions.

If all information is set to be deactivated using the query below, the audit policy will be completely deactivated.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

no rows selected.

The NOAUDIT POLICY statement deletes the individual activation information created according to the specified AUDIT POLICY method.

The following is an example of deactivating auditing only for the u1 user of audit_t1_dml.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          U1        YES          YES         
AUDIT_T1_DML BY          SYS       YES          YES         

2 rows selected.

NOAUDIT POLICY audit_t1_dml BY u1;

Noaudit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          SYS       YES          YES         

1 row selected.
If the AUDIT POLICY name BY clause is used, it must be deactivated using the NOAUDIT POLICY name BY statement. If the AUDIT POLICY name EXCEPT clause is used, it must be deactivated using the NOAUDIT POLICY name statement without the BY clause.

To deactivate each option of the AUDIT POLICY statement, the NOAUDIT POLICY statement should be used as follows, according to its usage.

Activating/ deactivating audit policy

Type

AUDIT POLICY statement

NOAUDIT POLICY statement

All users

AUDIT POLICY p1

NOAUDIT POLICY p1

Using BY

AUDIT POLICY p1 BY u1

NOAUDIT POLICY p1 BY u1

Using EXCEPT

AUDIT POLICY p1 EXCEPT u1

NOAUDIT POLICY p1

If all users are activated as follows, the NOAUDIT POLICY BY clause has no effect.

AUDIT POLICY audit_t1_dml;

Audit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          ALL USERS YES          YES         

1 row selected.

NOAUDIT POLICY audit_t1_dml BY u1;

Noaudit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'AUDIT_T1_DML'
;

POLICY_NAME  ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
------------ ----------- --------- ------------ ------------
AUDIT_T1_DML BY          ALL USERS YES          YES         

1 row selected.

If one or more users are activated separately, the NOAUDIT POLICY statement must be used according to the AUDIT POLICY configuration.

AUDIT POLICY p1 WHENEVER NOT SUCCESSFUL;
AUDIT POLICY p1 BY u1;
AUDIT POLICY p1 BY u2;
SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
----------- ----------- --------- ------------ ------------
P1          BY          ALL USERS NO           YES         
P1          BY          U1        YES          YES         
P1          BY          U2        YES          YES         

3 rows selected.
NOAUDIT POLICY p1;

Noaudit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
----------- ----------- --------- ------------ ------------
P1          BY          U1        YES          YES         
P1          BY          U2        YES          YES         

2 rows selected.

In the example above, auditing for ALL USERS is deactivated, but auditing for users u1 and u2 remains active.

If the NOAUDIT POLICY statement is used again with the BY option as follows, it will completely deactivate the audit policy p1.

NOAUDIT POLICY p1 BY u1, u2;

Noaudit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

no rows selected.
AUDIT POLICY p1 EXCEPT u1, sys;
SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

POLICY_NAME ENABLED_OPT USER_NAME WHEN_SUCCESS WHEN_FAILURE
----------- ----------- --------- ------------ ------------
P1          EXCEPT      U1        YES          YES         
P1          EXCEPT      SYS       YES          YES         

2 rows selected.
NOAUDIT POLICY p1;

Noaudit succeeded.

SELECT policy_name
     , enabled_opt
     , user_name
     , when_success
     , when_failure
  FROM audit_policy_enabled
 WHERE policy_name = 'P1';

no rows selected.

In other words, if an audit policy is activated using the EXCEPT option, a separate user can not be re activated using the NOAUDIT POLICY statement.

Authorization

Authorization-related Statements

For more information, refer to the following.

The information related to a user object and its authorization can be retrieved through the following views.

Information related to authorization objects

Schema

View

Description

DICTIONARY_SCHEMA

ALL_COL_PRIVS

Privileges on columns accessible by the user

ALL_COL_PRIVS_MADE

Column privileges where the user is the grantor

ALL_COL_PRIVS_RECD

Column privileges where the user is the grantee

ALL_DB_PRIVS

DB privileges related to the user

ALL_DB_PRIVS_MADE

DB privileges where the user is the grantor

ALL_DB_PRIVS_RECD

DB privileges where the user is the grantee

ALL_PACKAGE_PRIVS

Package privileges related to the user

ALL_PACKAGE_PRIVS_MADE

Package privileges where the user is the grantor

ALL_PACKAGE_PRIVS_RECD

Package privileges where the user is the grantee

ALL_PROC_PRIVS

Stored procedure/ function privileges related to the user

ALL_PROC_PRIVS_MADE

Stored procedure/ function privileges where the user is the grantor

ALL_PROC_PRIVS_RECD

Stored procedure/ function privileges where the user is the grantee

ALL_SCHEMA_PRIVS

Schema privileges accessible by the user

ALL_SCHEMA_PRIVS_MADE

Schema privileges where the user is the grantor

ALL_SCHEMA_PRIVS_RECD

Schema privileges where the user is the grantee

ALL_SEQ_PRIVS

Sequence privileges accessible by the user

ALL_SEQ_PRIVS_MADE

Sequence privileges where the user is the grantor

ALL_SEQ_PRIVS_RECD

Sequence privileges where the user is the grantee

ALL_TAB_PRIVS

Table privileges accessible by the user

ALL_TAB_PRIVS_MADE

Table privileges where the user is the grantor

ALL_TAB_PRIVS_RECD

Table privileges where the user is the grantee

ALL_TBS_PRIVS

Tablespace privileges accessible by the user

ALL_TBS_PRIVS_MADE

Tablespace privileges where the user is the grantor

ALL_TBS_PRIVS_RECD

Tablespace privileges where the user is the grantee

ALL_USERS

Information about users accessible by the user

USER_COL_PRIVS

Information about privileges on columns owned by the user

USER_COL_PRIVS_MADE

Information about granting privileges on the user-owned column

USER_COL_PRIVS_RECD

Information about acquiring privileges on the user-owned column

USER_PACKAGE_PRIVS

Information about package privileges owned by the user

USER_PACKAGE_PRIVS_MADE

Information about granting privileges on the user-owned package

USER_PACKAGE_PRIVS_RECD

Information about acquiring privileges on the user-owned package

USER_PROC_PRIVS

Information about stored procedure/function privileges owned by the user

USER_PROC_PRIVS_MADE

Information about granting privileges on the user-owned stored procedure/ function

USER_PROC_PRIVS_RECD

Information about acquiring privileges on the user-owned stored procedure/ function

USER_ROLE_PRIVS

Information about roles granted to the current user

USER_SCHEMA_PRIVS

Information about schema privileges owned by the user

USER_SCHEMA_PRIVS_MADE

Information about granting privileges on the user-owned schema

USER_SCHEMA_PRIVS_RECD

Information about acquiring privileges on the user-owned schema

USER_SEQ_PRIVS

Privilege information for the user-owned sequence

USER_SEQ_PRIVS_MADE

Information about granting privileges on the user-owned sequence

USER_SEQ_PRIVS_RECD

Information about acquiring privileges on the user-owned sequence

USER_SYS_PRIVS

Information about system privileges granted to a user

USER_TAB_PRIVS

Privilege information about the user-owned table

USER_TAB_PRIVS_MADE

Information about granting privileges on the user-owned table

USER_TAB_PRIVS_RECD

Information about acquiring privileges on the user-owned table

USER_USERS

Information about the current user

ROLE_COL_PRIVS

Information about column privileges granted to the activated role that are accessible to the current user

ROLE_DB_PRIVS

Information about database privileges granted to the activated role that are accessible to the current user

ROLE_LIBRARY_PRIVS

Information about library privileges granted to the activated role that are accessible to the current user

ROLE_PACKAGE_PRIVS

Information about package privileges granted to the activated role that are accessible to the current user

ROLE_PROC_PRIVS

Information about procedure/ function privileges granted to the activated role that are accessible to the current user

ROLE_ROLE_PRIVS

Information about roles granted to the activated role that are accessible to the current user

ROLE_SCHEMA_PRIVS

Information about schema privileges granted to the activated role that are accessible to the current user

ROLE_SEQ_PRIVS

Information about sequence privileges granted to the activated role that are accessible to the current user

ROLE_SYS_PRIVS

Information about system privileges granted to the activated role that are accessible to the current user

ROLE_TAB_PRIVS

Information about table privileges granted to the activated role that are accessible to the current user

ROLE_TBS_PRIVS

Information about tablespace privileges granted to the activated role that are accessible to the current user

INFORMATION_SCHEMA

ADMINISTRABLE_ROLE_AUTHORIZATIONS

Privilege information for roles with the WITH ADMIN OPTION granted to the current user or current role

COLUMN_PRIVILEGES

Privilege information for user-accessible columns

MODULE_PRIVILEGES

Privilege information for user-accessible modules (packages)

ROUTINE_PRIVILEGES

Privilege information for user-accessible stored procedures/ functions

ROLE_COLUMN_GRANTS

Information about column privileges granted to the activated role that are accessible to the current user

ROLE_MODULE_GRANTS

Information about module (package) privileges granted to the activated role that are accessible to the current user

ROLE_ROUTINE_GRANTS

Information about stored procedure/ function privileges granted to the activated role that are accessible to the current user

ROLE_TABLE_GRANTS

Information about table privileges granted to the activated role that are accessible to the current user

ROLE_USAGE_GRANTS

Information about sequence privileges granted to the activated role that are accessible to the current user

TABLE_PRIVILEGES

Privilege information for user-accessible tables

USAGE_PRIVILEGES

Privilege information for user-accessible sequences

Concept of User

A user object consists of the user's set of execution privileges. The user must have the appropriate privileges to execute SQL statements on the corresponding object.

For example, a user created using the CREATE USER statement is an object without any privileges. The user can not access the database or execute any SQL statements. To gain access, the user must have the CREATE SESSION ON DATABASE privilege, which allows the creation of sessions in the database. This privilege should be granted after executing the CREATE USER statement as follows.
CREATE USER u1 IDENTIFIED BY u1_password;
GRANT CREATE SESSION ON DATABASE TO u1;
COMMIT;

For more information about granting privileges after creating a user object, refer to the Examples in the CREATE USER and GRANT privileges TO statements.

Concept of Role

A role object consists of a set of privileges. The privileges granted to the role are the set of privileges that can be executed by the user to whom the role is granted. For a user granted the role to execute SQL statements, the necessary privileges to perform the corresponding SQL commands must be granted to the role. Alternatively, the user should be granted a role that includes the required privileges.

For example, a role created using the CREATE ROLE statement does not have any privileges, so the user to whom the role is granted is not granted any privileges either. To allow the user with the role to create a table object, the role must be granted the CREATE TABLE ON SCHEMA privilege. The appropriate privilege should be granted by executing the CREATE ROLE statement as follows.

CREATE ROLE role1;
GRANT USAGE TABLESPACE TO role1;
GRANT CREATE TABLE ON SCHEMA u1 TO role1;
GRANT role1 TO u1;
COMMIT;

Alternatively, grant the role with the CREATE TABLE ON SCHEMA privilege to the role that is granted to the user.

CREATE ROLE role1;
GRANT role1 TO u1;

CREATE ROLE role2;
GRANT USAGE TABLESPACE TO role2;
GRANT CREATE TABLE ON SCHEMA u1 TO role2;
GRANT role2 TO role1;

For more information about granting roles and privileges after creating a role object, refer to the Examples in CREATE ROLE and GRANT privileges TO, and GRANT role TO.

Creating Objects and Privileges

Creating SQL Schema Object

When creating an SQL schema object, such as a table, the user must have the privileges for the superordinate non-schema object to which the table belongs in order to execute the CREATE TABLE statement.

The following is an example of a CREATE TABLE statement.

CREATE TABLE t1 ( id BIGINT, name VARCHAR(128) );
When it is interpreted as follows,
CREATE TABLE u1.t1 ( id BIGINT, name VARCHAR(128) ) TABLESPACE mem_data_tbs;

As shown in the figure below, the owner of the table t1 is the account u1, which is also the owner of the u1 schema. The logical location for the table is the u1 schema, while the physical storage for the table is the mem_data_tbs tablespace.

CREATE TABLE and non-schema objects

CREATE TABLE and non-schema objects

In this case, the user u1, who executed the statement, needs the following privileges for the schema and tablespace to which the table t1 will belong.
One of the following privileges is required to create the table, which will be stored in its logical location (schema u1).

One of the following privileges is required to create a table in the tablespace mem_data_tbs, which is the physical storage space for tables.

The owner of the table object is determined as follows.

The owner of the table object has the following privileges to change the table structure and manipulate data in the table.

The grantor of the given privilege  is  the _SYSTEM account, which is used internally, and the grantee is the table owner. Therefore, no user, including the SYS account, is allowed to remove or change the owner's privileges using the REVOKE privileges FROM. The table owner's privileges are also removed when the table is removed.

Creating Non-schema Object

Similar to creating SQL schema objects, such as a table, appropriate privileges on the database, which is the superordinate object, are required to create non-schema objects, such as users, schemas, and tablespaces.

A user executing the following statements must have the following privileges on the database object (the superordinate object) for each statement.

Unlike when creating SQL schema objects, the owner of a non-schema object is not the user who executes the CREATE statement. Each object has the following characteristics.

Privileges

Granting Privileges

When the user is not the owner of an SQL schema object, such as a table, the user must be granted the appropriate privileges on the table using the GRANT privileges TO statement in order to INSERT, UPDATE, or SELECT data.

For example, a user who is not the owner of a table requires one of the following privileges to execute the SELECT statement. As shown in the figure below, even if the user does not have SELECT privileges on the t1 table, they can query the u1.t1 table if they have SELECT privileges on the superordinate object, such as the u1 schema or the database.
SELECT id, name FROM u1.t1 WHERE id < 100;

Privilege to execute SELECT statement

Privilege to execute SELECT statement

The user who executed the GRANT statement must be one of the following to grant the SELECT ON TABLE u1.t1 privileges to another user.

The following is an example of the object owner granting privileges to another user.
GRANT SELECT ON TABLE u1.t1 TO test;
For more information about the privilege types, refer to GRANT privileges TO.
For more information about the privileges required to execute each SQL statement, refer to the Invocation and Access Rule of each statement in the SQL References section.

Revoking Privileges

The granted privileges are revoked from a user using the REVOKE privileges FROM. The privileges of the object's owner can not be revoked until the object is removed.

For example, the user who can execute the REVOKE statement to revoke the SELECT privilege from the test user is as follows. Even if the user is the owner of the table, they cannot revoke privileges that were not granted by them.

REVOKE SELECT ON TABLE u1.t1 FROM test;

When the test user is granted the same privilege by multiple users as shown below, the test user can execute the SELECT statement until all the granted privileges are revoked.

GRANT SELECT ON TABLE u1.t1 TO test;
GRANT SELECT ON TABLE u1.t1 TO u2 WITH GRANT OPTION;
GRANT SELECT ON TABLE u1.t1 TO test;

In the example above, the test user has two SELECT ON TABLE u1.t1 privileges, granted by user u1 and user u2. The privilege information consists of {grantor, grantee, object privileges}.

PUBLIC Account

The PUBLIC account is a special account that represents every user.

For example, if the SELECT privilege is granted to the PUBLIC account as follows, every user can execute SELECT statements on the table u1.t1.

GRANT SELECT ON TABLE u1.t1 TO PUBLIC;

In other words, even a user who has not been granted the SELECT privilege can execute SELECT statements on the u1.t1 table by using the SELECT privilege granted to the PUBLIC account.

When a privilege is granted to the PUBLIC account, it is granted not to the existing users but to the PUBLIC account itself. Even newly created users can also execute SELECT statements.

Likewise, when the privilege for the PUBLIC account is revoked as shown below, it does not revoke the privilege from all users. If a user has the SELECT privilege on the u1.t1 table, the user can still execute SELECT statements.

GRANT SELECT ON TABLE u1.t1 TO test;
GRANT SELECT ON TABLE u1.t1 TO PUBLIC;
REVOKE SELECT ON TABLE u1.t1 FROM PUBLIC;

Column Privilege

By granting privileges only on specific columns of a table, it is possible to control the execution of DML or SELECT statements by other users.

Refer to the following example table.

CREATE TABLE u1.t1 
(
   id     BIGINT,
   name   VARCHAR(128),
   addr   VARCHAR(1024),
   salary NUMBER(20,0)
);

When granting the SELECT privilege on the u1.t1 table, excluding the salary column, to another user, the GRANT privileges TO statement is executed by listing the columns to which the privilege is granted, as shown below. The test user, who is the grantee of the privilege, can not query the salary column.

GRANT SELECT( id, name, addr ) ON TABLE u1.t1 TO test;

If the privilege on a table is granted as shown below, the privilege on every column in the table is automatically granted. When both column and table privileges are granted, the privilege information for the column is duplicated and not redundantly managed.

GRANT SELECT ON TABLE u1.t1 TO test;
GRANT SELECT(id) ON TABLE u1.t1 TO test;
GRANT SELECT(name) ON TABLE u1.t1 TO test;
GRANT SELECT(addr) ON TABLE u1.t1 TO test;
GRANT SELECT(salary) ON TABLE u1.t1 TO test;
The privilege on a column is revoked using the REVOKE privileges FROM statement as follows.
REVOKE SELECT( id, name, addr ) ON TABLE u1.t1 FROM test;

If the privilege on a table is revoked as shown below, the privilege on every column in the table is automatically revoked. Even if column privileges and table privileges are granted separately, the column privileges are revoked when the table privileges are revoked.

REVOKE SELECT ON TABLE u1.t1 FROM test;

When only the column privilege is revoked, if the table privilege still exists as shown below, the statement can still be executed using the table privilege. Therefore, to grant privileges on a specific column only, the table privilege should be revoked first, and then privileges should be granted on each column.

GRANT SELECT ON TABLE u1.t1 TO test;
REVOKE SELECT(salary) ON TABLE u1.t1 FROM test;

For more information about privileges on a table and columns, refer to GRANT privileges TO.

Schema

Schema-related Statements

For more information on creating and dropping a schema, refer to the following.

The information about a schema object can be retrieved through the following views.

Schema object-related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_SCHEMAS

User-accessible schema information

ALL_SCHEMA_PATH

User-accessible schema path

USER_SCHEMAS

User-owned schema information

USER_SCHEMA_PATH

User's schema path information

INFORMATION_SCHEMA

SCHEMATA

User-accessible schema information

Concept of Schema

The database consists of one or more schemas. A schema consists of objects, such as tables, indexes, views, and sequences, that handles data. Objects belonging to a schema are referred to as SQL schema objects.

A schema is a concept similar to a directory in OS, and the relationship between a schema and its tables is similar to the relationship between directories and files in OS. In other words, a schema represents the logical location of SQL schema objects and serves as a criterion for distinguishing names. Each SQL schema object must have a unique name within the schema, and the namespace within the schema is as follows

Tables with the same name can be defined in different schemas. These tables, despite having the same name, can be accessed and executed by specifying the schema name along with the table name.

gSQL> SELECT u1.t1.id, u1.t1.name, u2.t1.addr
        FROM u1.t1, u2.t1
       WHERE u1.t1.id = u2.t1.id;

The name of an SQL schema object can be specified with or without the schema name. If the schema name is omitted, it is determined by the user's schema path. For more information about the schema path, refer to the Schema Path clause.

gSQL> SELECT u1.t1.id, u1.t1.name FROM u1.t1;
gSQL> SELECT t1.id, t1.name FROM t1;

User and Schema

In GOLDILOCKS, the relationship between a user and a schema is 1:N. A user does not own a schema, but a user can have multiple schemas.

The SQL standard does not explicitly define the relationship between non-schema objects such as users, schemas, and databases. Each DBMS defines the relationship between these objects in different ways, as follows.

When establishing the database, GOLDILOCKS configures various relationships between users and schemas based on the characteristics of the client system, as follows.

Relationship between users and schemas

Relationship between users and schemas

To configure a database where each user owns its own schema as shown in figure (a), create the users and schemas as follows.

gSQL> CREATE USER u1 IDENTIFIED BY u1_password WITH SCHEMA;
gSQL> CREATE USER u2 IDENTIFIED BY u2_password;
gSQL> CREATE USER u3 IDENTIFIED BY u3_password;

To configure a database where a single user has multiple schemas, as shown in figure (b), create the users and schemas as follows.

gSQL> CREATE USER u1 IDENTIFIED BY u1_password WITHOUT SCHEMA;
gSQL> CREATE SCHEMA s1 AUTHORIZATION u1;
gSQL> CREATE SCHEMA s2 AUTHORIZATION u1;
gSQL> CREATE SCHEMA s3 AUTHORIZATION u1;
To configure a database where multiple users share a single schema without creating a new schema, as shown in figure (c), create the users as follows.
In the following example, all users share and use the PUBLIC Schema.
gSQL> CREATE USER u1 IDENTIFIED BY u1_password WITHOUT SCHEMA;
gSQL> CREATE USER u2 IDENTIFIED BY u2_password WITHOUT SCHEMA;
gSQL> CREATE USER u3 IDENTIFIED BY u3_password WITHOUT SCHEMA;

For more information about creating users and schemas, refer to CREATE USER, CREATE SCHEMA.

Schema Path

The schema path is the route used to find the schema name when an SQL schema object, such as a table, is referenced without the schema name. The concept of schema path is similar to the PATH environment variable in Unix systems. In other words, it is similar to how commands are searched in the order specified in the PATH variable when executing commands in Unix systems.

When a user owns multiple schemas and creates or queries a table without specifying a schema name, the schema path determines which schema the table will be created in.

gSQL> CREATE TABLE s1.t1 ( id INTEGER );
gSQL> CREATE TABLE s2.t1 ( name VARCHAR(128) );
gSQL> CREATE TABLE t1 ( address VARCHAR(1024) );
gSQL> SELECT * FROM t1;

The figure below illustrates an example of the schema path for user u1. The schema path for user u1 is defined in the order of {s1, s2, s3}. Schema s1 contains table t1, schema s2 contains table t2, and schema s3 contains tables t1 and t3.

Example of schema path

Example of schema path

In a SELECT statement without a schema name, the schema name is determined by the schema path as follows.

gSQL> SELECT * FROM t1;
gSQL> SELECT * FROM s1.t1;
gSQL> SELECT * FROM t2;
gSQL> SELECT * FROM s2.t2;
gSQL> SELECT * FROM t3;
gSQL> SELECT * FROM s3.t3;

When omitting the schema name to retrieve the table s3.t1, as shown in the example above, the schema path determines the table s3.t1. Therefore, the schema name must be specified as follows.

gSQL> SELECT * FROM t1;
gSQL> SELECT * FROM s3.t1;

The following CREATE TABLE statement, where the schema name is omitted, creates the table in the first schema (s1) of the schema path.

gSQL> CREATE TABLE t1 ( id INTEGER );
gSQL> CREATE TABLE s1.t1 ( id INTEGER );
gSQL> CREATE TABLE t2 ( name VARCHAR(128) );
gSQL> CREATE TABLE s1.t2 ( name VARCHAR(128) );
gSQL> CREATE TABLE t3 ( name VARCHAR(128) );
gSQL> CREATE TABLE s1.t3 ( name VARCHAR(128) );

If the current user omits the schema name when creating an object, the schema name to be used can be retrieved using CURRENT_SCHEMA, which is an SQL standard function.

gSQL> SELECT current_schema FROM dual;

CURRENT_SCHEMA
--------------
S1            

1 row selected.

The schema path information for the current user can be retrieved using the ALL SCHEMA PATH view in the DICTIONARY SCHEMA schema.

gSQL> SELECT * FROM all_schema_path;

AUTH_NAME SCHEMA_NAME             SEARCH_ORDER
--------- ----------------------- ------------
U1        S1                                 1
U1        S2                                 2
U1        S3                                 3
PUBLIC    DICTIONARY_SCHEMA                  4
PUBLIC    INFORMATION_SCHEMA                 5
PUBLIC    DEFINITION_SCHEMA                  6
PUBLIC    PERFORMANCE_VIEW_SCHEMA            7
PUBLIC    FIXED_TABLE_SCHEMA                 8
PUBLIC    BUILTIN_PACKAGE_SCHEMA             9

9 rows selected.
In the example above, the schema path for user u1 is ordered as {s1, s2, s3}, while the schema path for the PUBLIC account is ordered as {DICTIONARY_SCHEMA, INFORMATION_SCHEMA, DEFINITION_SCHEMA, PERFORMANCE_VIEW_SCHEMA, FIXED_TABLE_SCHEMA, BUILTIN_PACKAGE_SCHEMA}. 
If the schema name is omitted when retrieving table t1, the system first searches the schema path for the current user, u1. If the schema path is not found, it then searches the schema path for the PUBLIC account.
The schema path of a specific user can be altered using the ALTER USER statement as follows. The schema path for the PUBLIC account can be altered with the ALTER USER PUBLIC SCHEMA PATH statement. 
The CURRENT PATH clause is used to additionally modify other schemas along with the user's current schema.
gSQL> ALTER USER u1 SCHEMA PATH ( s3, s2, s1 );

User altered.
gSQL> ALTER USER PUBLIC SCHEMA PATH ( s1, s2, s3 );

User altered.
gSQL> ALTER USER u1 SCHEMA PATH ( s4, CURRENT PATH );

User altered.

When a user is created using the CREATE USER statement, the schema path is automatically determined. However, a schema created later using the CREATE SCHEMA statement for that user is not automatically included in the user's schema path. Therefore, if necessary, the schema should be added to the schema path using the ALTER USER statement. For more information, refer to the documentation for each statement.

PUBLIC Schema

The PUBLIC schema is a shared schema in which any user can create objects. As shown in the example below, if a user who does not own a schema creates a table without specifying a schema name, the schema of the table will be PUBLIC.

gSQL> CREATE USER u1 IDENTIFIED BY u1_password WITHOUT SCHEMA;
gSQL> GRANT CREATE SESSION TO u1;
gSQL> GRANT CREATE OBJECT ON TABLESPACE mem_data_tbs TO u1;
% gsql u1 u1_password
gSQL> CREATE TABLE t1 ( id INTEGER );
gSQL> CREATE TABLE public.t1 ( id INTEGER );
In the example above, the schema of table t1, created by user u1, is PUBLIC. The PUBLIC schema is a built-in schema that is automatically created when the database is created. It is granted privileges that allow any user to create objects in the schema, which are equivalent to the following statement.
gSQL> GRANT CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE, ADD CONSTRAINT
         ON SCHEMA PUBLIC
         TO PUBLIC;
The PUBLIC schema, a shared schema, is different from the PUBLIC account, which refers to all users. In the statement above, the privilege to create objects in the PUBLIC schema (ON SCHEMA PUBLIC) is granted to the PUBLIC account (TO PUBLIC), meaning all users. 
Any user can create or manage tables, but the appropriate privilege is required to retrieve a table created in the PUBLIC schema by another user.

The following are examples of GRANT statements using the PUBLIC account and the PUBLIC schema.

gSQL> GRANT SELECT ON TABLE u1.t1 TO PUBLIC;
gSQL> GRANT SELECT TABLE ON SCHEMA PUBLIC TO u1;

Examples of Using User and Schema

For example, if a single administrator and multiple developers are using a single schema, the schema can be managed using the following SQL statement.

The following is an example of creating the mgr_user user who manages the our_schema schema, along with multiple users such as app_user1, app_user2, and app_user3, who develop applications using our_schema.

A mgr_user user and the our_schema schema are created as follows.

gSQL> CREATE USER mgr_user IDENTIFIED BY mgr_user WITH SCHEMA our_schema;

User created.
gSQL> GRANT ALL PRIVILEGES ON DATABASE TO mgr_user;

Grant succeeded.

gSQL> COMMIT;

Commit complete.
Multiple app_user users are created as follows.
The app_user users are granted permission to execute only SELECT and DML statements on our_schema.
gSQL> CREATE USER app_user1 IDENTIFIED BY app_user1 WITHOUT SCHEMA;

User created.

gSQL> CREATE USER app_user2 IDENTIFIED BY app_user2 WITHOUT SCHEMA;

User created.

gSQL> CREATE USER app_user3 IDENTIFIED BY app_user3 WITHOUT SCHEMA;

User created.

gSQL> COMMIT;

Commit complete.
gSQL> GRANT CREATE SESSION ON DATABASE TO app_user1, app_user2, app_user3;

Grant succeeded.

gSQL> COMMIT;

Commit complete.
gSQL> GRANT SELECT TABLE, INSERT TABLE, UPDATE TABLE, DELETE TABLE ON SCHEMA our_schema TO app_user1, app_user2, app_user3;

Grant succeeded.

gSQL> COMMIT;

Commit complete.
gSQL> ALTER USER app_user1 SCHEMA PATH ( our_schema );

User altered.

gSQL>  ALTER USER app_user2 SCHEMA PATH ( our_schema );

User altered.

gSQL> ALTER USER app_user3 SCHEMA PATH ( our_schema );

User altered.

gSQL> COMMIT;

Commit complete.

Through the operations above, mgr_user has DDL privileges to create/ drop/ alter objects in our_schema, while multiple app_user users can only perform read/ write operations on the tables in our_schema.

mgr_user can perform management tasks, such as creating a table, as follows.

gSQL> \connect mgr_user mgr_user
gSQL> CREATE TABLE t1 ( c1 INTEGER );

Table created.

gSQL> INSERT INTO t1 VALUES ( 1 );

1 row created.

gSQL> INSERT INTO t1 VALUES (2), (3);

2 rows created.

gSQL> COMMIT;

Commit complete.

Multiple app_user users can perform read/ write operations on the tables in our_schema without specifying the schema name, but they are not allowed to create or drop objects, as follows.

gSQL> \connect app_user1 app_user1
gSQL> SELECT * FROM t1;

C1
--
 1
 2
 3

3 rows selected.

gSQL> INSERT INTO t1 VALUES (4);

1 row created.

gSQL> COMMIT;

Commit complete.

gSQL> DROP TABLE t1;

ERR-42000(16208): insufficient privileges

Tablespace

Tablespace-related Statements

For more information, refer to the following.

The information related to a tablespace object can be retrieved through the following views.

Tablespace object related information

Schema

View

Description

DICTIONARY_SCHEMA

USER_TABLESPACES

Information of user-accessible tablespaces

Concept of Tablespace

A tablespace is a logical concept that consists of one or more physical shared memory segments. It serves as a space for storing data such as tables and indexes.
Physical objects like tables and indexes stored in a tablespace can span across multiple shared memory segments, as shown below.
The tablespace can be extended by adding more shared memory.

Concept of tablespace

Concept of tablespace

Tablespaces are classified into three types based on the type of data they store, as follows.

Tables and indexes (LOGGING) stored in the DATA tablespace create redo logs to permanently manage data. However, indexes without logging, stored in the TEMPORARY tablespace, do not create redo logs. These non-logged indexes do not log changes. When the system is restarted, the index is rebuilt based on the table data, and the index functionality is retained.

A tablespace is a physical storage location where SQL schema objects are stored. A specific tablespace can be specified when creating a table or an index. A table, its associated index, and indexes created for constraint conditions can be stored in different tablespaces. 
For more information on specifying the tablespace when creating an object, refer to the following.
If a tablespace is not specified when creating an object, such as a table or an index, the user's default tablespace is used. 
For more information about the user's default tablespace, refer to the following.
For more information about tablespace, refer to Managing Tablespace.

Table

Table-related Statements

The statements for creating, dropping, and altering a table are as follows.

The information related to a table object can be retrieved through the following views.

Table object related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_ALL_TABLES

Information about user-accessible tables

ALL_COL_COMMENTS

Information about comments on user-accessible columns

ALL_CONSTRAINTS

Information about user-accessible constraints

ALL_CONS_COLUMNS

Column information for user-accessible constraints

ALL_HISTOGRAM_BALANCE

Information about height-balanced histogram for user-accessible tables

ALL_HISTOGRAM_FREQUENCY

Information about frequency histogram for user-accessible tables

ALL_STAT_COLUMN_GROUP

Information about column group statistics for user-accessible tables

ALL_TABLES

Information about user-accessible tables

ALL_TAB_COLS

Information about user-accessible columns

ALL_TAB_COLUMNS

Information about user-accessible columns

ALL_TAB_COMMENTS

Information about comments on user-accessible tables

ALL_TAB_IDENTITY_COLS

Information about identity columns in user-accessible tables

USER_ALL_TABLES

Information about user-owned tables

USER_COL_COMMENTS

Information about comments on user-owned columns

USER_CONSTRAINTS

Information about user-owned constraints

USER_CONS_COLUMNS

Column information for user-owned constraints

USER_HISTOGRAM_BALANCE

Information about height-balanced histogram for user-owned tables

USER_HISTOGRAM_FREQUENCY

Information about frequency histogram of user-owned tables

USER_RECYCLEBIN

Information about user-owned recycle bin objects

USER_STAT_COLUMN_GROUP

Information about column group statistics for user-owned tables

USER_TABLES

Information about user-owned tables

USER_TAB_COLS

Information about user-owned columns

USER_TAB_COLUMNS

Information about user-owned columns

USER_TAB_COMMENTS

Information about comments on user-owned tables

USER_TAB_IDENTITY_COLS

Information about identity column about user-owned tables

INFORMATION_SCHEMA

COLUMNS

Information about user-accessible columns

CONSTRAINT_COLUMN_USAGE

Column information about user-accessible constraints

CONSTRAINT_TABLE_USAGE

Table information for user-accessible constraints

KEY_COLUMN_USAGE

Column information for user-accessible key constraints

TABLES

Information about user-accessible tables

TABLE_CONSTRAINTS

Information about user-accessible constraints

Concept of Table

A table is the fundamental object that configures the structure of a database. In the SQL standard, a table is called a base table, and a view is called a viewed table.

A table consists of columns and rows. It contains multiple rows, and the number and order of columns in each row are the same. A table has one or more columns, each with a name, but a row does not have a name. The order of rows is not always the same as the order in which the data is added. A value is the data found at the intersection of a column and a row. A column is a set of values that share the same data type.
Each column of a table has a unique name that distinguishes it from other columns in the table. It has a data type that corresponds to the characteristics of the values. For more information about data types, refer to the Data Type section. 
Constraints can be added to a table to ensure data integrity. For more information about constraints, refer to CREATE TABLE and  ALTER TABLE name ADD CONSTRAINT. 
An index can be created on a table to improve the performance of queries. For more information about indexes, refer to the Index section.
The following is an example of creating a lineitem table using the CREATE TABLE statement.
CREATE TABLE lineitem
(
    l_orderkey      INTEGER    NOT NULL
  , l_partkey       INTEGER    NOT NULL
  , l_suppkey       INTEGER    NOT NULL
  , l_linenumber    INTEGER    NOT NULL
  , l_quantity      NUMERIC(12,2)
  , l_extendedprice NUMERIC(12,2)
  , l_discount      NUMERIC(12,2)
  , l_tax           NUMERIC(12,2)
  , l_returnflag    CHAR(1)    NOT NULL  DEFAULT 'F'
  , l_linestatus    CHAR(1)
  , l_shipdate      DATE
  , l_commitdate    DATE
  , l_receiptdate   DATE
  , PRIMARY KEY (l_orderkey, l_linenumber) INDEX lineitem_pk_idx TABLESPACE mem_temp_tbs
) TABLESPACE mem_data_tbs;
In the example above, the lineitem table defines multiple columns along with constraints. When defining columns with constraints, the NOT NULL constraint is applied to the columns l_orderkey, l_partkey, l_suppkey, and l_linenumber, and a PRIMARY KEY constraint is defined by combining the two columns l_orderkey and l_linenumber. Constraints that are specified alongside the column definitions are called in-line constraints, while constraints that are defined separately from the column definitions are called out-line constraints.

Using the DEFAULT clause in the l_returnflag column, the value 'F' is declared as the default value for the column. The index created with the PRIMARY KEY constraint is separately named lineitem_pk_idx, and the tablespace in which the index will be stored is specified as mem_temp_tbs. The table itself is stored in the mem_data_tbs tablespace as its physical storage.

The following is an example of adding a constraint to a table using the ALTER TABLE name ADD CONSTRAINT statement.

ALTER TABLE lineitem 
      ADD CONSTRAINT lineitem_unique_all_key 
      UNIQUE( l_orderkey ASC, l_partkey DESC, l_suppkey DESC, l_linenumber ASC);

In the example above, a UNIQUE constraint is added to the lineitem table, and the sort order (ASC/ DESC) for the columns of the index automatically created by the constraint is specified.

The following is an example of adding columns to a table using the ALTER TABLE name ADD COLUMN statement.

ALTER TABLE lineitem ADD COLUMN 
(
    l_shipinstruct  CHAR(25)
  , l_shipmode      CHAR(10)
  , l_comment       VARCHAR(44)
);

In the example above, multiple columns are added to the table. In-line constraints or default values can be specified when adding columns.

The following is an example of creating an index on a table using the CREATE INDEX statement.

CREATE INDEX lineitem_idx_shipdate ON lineitem( l_shipdate ASC NULLS LAST );

In the example above, an index is created on the l_shipdate column, which is frequently used in query conditions. The column’s sort order is specified as ascending (ASC), and if a NULL value exists, it is placed at the end.

For more information about DML statements for inserting/ deleting/ updating data in a table, refer to the Data Manipulation Language clause.
For more information about SELECT statements for querying data from a table, refer to the Data Query Language clause and the SELECT statement.

Global Temporary Table

It is a type of temporary table where the table definition is shared by all users, but the data is separated and used for each session.

The table definition is created when executing the CREATE GLOBAL TEMPORARY TABLE command, but the physical storage (segment) is created in a session-dependent state when the INSERT command is executed for the first time on that table. The storage allocated to all global temporary tables created in the session is released when the session ends. Depending on the option specified during creation, it can be determined whether the data remaining after a COMMIT or ROLLBACK will be TRUNCATED.

Except for cluster-related statements, it supports all DDL and DML operations provided by a regular table. A DDL command returns an error to a global temporary table being used by the current session. However, the TRUNCATE TABLE command for a global temporary table applies only to the current session, so it does not return an error even if the table is being used by another session.

A global temporary table can only be defined in a temporary tablespace, so it does not record a redo log for restart recovery. However, it records an undo log for MVCC and rollback, and the space where the undo log is recorded can be chosen to be either the system undo tablespace or the system temp tablespace by using the TEMP_UNDO_ENABLED option.
If TEMP_UNDO_ENABLED is set to 1, undo logs are recorded in the session's temp undo relation, separate from the transaction's undo relation. If the transaction performs only DML operations on a global temporary table, neither the transaction record nor the commit log is recorded, thus improving DML performance.

When the space used in a session is released, it is typically returned to the corresponding tablespace, and when space is reallocated, it is allocated from the tablespace. The process of allocating and releasing space in the tablespace is costly, as it involves maintaining concurrency with other sessions and managing the allocation and release of space. Therefore, though the TEMP_SEGMENT_CACHE_SIZE property, space that has been released after use in a session can be reused within the session without being returned to the tablespace.

In other words, if TEMP_SEGMENT_CACHE_SIZE is set to 0 (the default value), the segment that is released after use is immediately returned to the tablespace. If TEMP_SEGMENT_CACHE_SIZE is set to a value greater than 1 (with a maximum of 4,294,967,295), then as many segments as specified are reused within the session when returning the segment.

When a global temporary table is no longer used in a session, the segments in the segment cache can be cleaned up all at once by using the ALTER SESSION CLEANUP GLOBAL TEMPORARY SEGMENT POOL; statement.

The following is an example of creating a global temporary table using the CREATE GLOBAL TEMPORARY TABLE statement.

CREATE  GLOBAL TEMPORARY TABLE SESSION_TABLE1(
        COL1    CHAR(10)
       ,COL2    VARCHAR2(20)
       ,COL3    NUMBER(10)
)   ON  COMMIT  DELETE ROWS;

The information about the created global temporary table can be viewed in the DICTIONARY tables or views in the same way as viewing the information of a regular table.

Table Function-Derived Table

A table function-derived table is a logical table consisting of the result set returned by executing a table function. A table function is a function defined with a return table type. The definition of a table function-derived table follows the table column list specified in the return statement of the table function. Unlike a regular table, a table function-derived table cannot have indexes or constraints. The rows of a table function-derived table are the results returned by the table function. This type of table is useful when creating a subset of a specific table to retrieve the desired data from a particular table. 
For more information about the concept of table functions, refer to Stored Function.

Definition of table function-derived table

Definition of table function-derived table

Table in Cluster

For more information about tables in a cluster environment, refer to Cluster Table and Shard.

Table Recycle Bin Management

Syntax

Information about the recycle bin can be retrieved through the following views.

Information about the recycle bin

Schema

View

Description

DICTIONARY_SCHEMA

DBA_RECYCLEBIN

Information about all recycle bins in the database

USER_RECYCLEBIN

Information about the recycle bin owned by the user

RECYCLEBIN

Alias of USER_RECYCLEBIN

Description

It is a feature that stores the dropped object in the recycle bin instead of immediately removing it. Constraints and indexes associated with the table are also stored in the recycle bin.

The concept of the recycle bin is also referred to as the flashback drop feature, objects stored in the recycle bin can be either dropped or restored using the PURGE or FLASHBACK TABLE statement.

When a table is dropped and stored in the recycle bin, the names of all objects related to the table are altered and stored. The altered names take the form of BIN$unique_name, with the database generating and assigning a unique value. The unique_name is created as a 32-character string.

When restoring a table stored in the recycle bin, the constraints and indexes related to the table are restored to their original names before they were dropped. However, if a name that existed before the object was dropped already exists, the object is restored using the name it had in the recycle bin.

The RECYCLEBIN property must be activated to use the recycle bin feature. This property can be altered using ALTER SESSION or ALTER SYSTEM, with ALTER SYSTEM having a DEFERRED option. The default value is FALSE.

gSQL> ALTER SESSION SET RECYCLEBIN = ON;

Session altered.

gSQL> ALTER SYSTEM SET RECYCLEBIN = ON DEFERRED;

System altered.

Feature

Only certain DML and DDL statements are allowed for objects stored in the recycle bin. Any statements other than those listed below will result in an error.


• SELECT

• SELECT .. FOR UPDATE

• LOCK TABLE

• COMMENT ON TABLE name IS

• COMMENT ON COLUMN name IS

• COMMENT ON INDEX name IS

• COMMENT ON CONSTRAINT name IS

• GRANT privileges TO

• REVOKE privileges FROM

• CREATE TABLE AS SELECT

• CREATE GLOBAL TEMPORARY TABLE AS SELECT

• CREATE AUDIT POLICY

• ALTER AUDIT POLICY

• CREATE VIEW

• CREATE SYNONYM

• CREATE FUNCTION

• CREATE PROCEDURE

• ALTER FUNCTION

• ALTER PROCEDURE

• ALTER DATABASE MOVE SHARD

• ALTER DATABASE REBALANCE

• ALTER DATABASE REBALANCE EXCLUDE CLUSTER GROUP

• ALTER TABLE name REBALANCE

• ALTER TABLE name REBALANCE EXCLUDE CLUSTER GROUP

• ALTER TABLE name MOVE SHARD

• ALTER TABLE name SPLIT SHARD

• ALTER TABLE name MERGE SHARD

• ALTER TABLE name SYNCHRONIZE IDENTITY COLUMN

Example

The RECYCLEBIN  property must be activated to use the recycle bin feature.
gSQL> ALTER SESSION SET RECYCLEBIN = ON;

Session altered.

gSQL> CREATE TABLE t1 ( id INTEGER PRIMARY KEY, name VARCHAR(32) );

Table created.

gSQL> DROP TABLE t1;

Table dropped.

gSQL> CREATE TABLE t1 ( id INTEGER PRIMARY KEY, name VARCHAR(32) );

Table created.

gSQL> DROP TABLE t1;

Table dropped.

gSQL> COMMIT;

Commit complete.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE, DROPPED_TIME FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE DROPPED_TIME              
------------------------------------ -------------------- ----------- --------------------------
BIN$8981D28E172C11EAA7C5D51B86D72AB6 T1                   TABLE       2019-12-05 15:57:44.120000
BIN$8981D2C0172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY       CONSTRAINT  2019-12-05 15:57:44.120000
BIN$8981D2AC172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY_INDEX INDEX       2019-12-05 15:57:44.120000
BIN$8F1E9614172C11EAA7C5D51B86D72AB6 T1                   TABLE       2019-12-05 15:57:53.540000
BIN$8F1E9650172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY       CONSTRAINT  2019-12-05 15:57:53.540000
BIN$8F1E963C172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY_INDEX INDEX       2019-12-05 15:57:53.540000

6 rows selected.

gSQL> PURGE TABLE t1;

Table purged.

gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE, DROPPED_TIME FROM USER_RECYCLEBIN;

OBJECT_NAME                          ORIGINAL_NAME        OBJECT_TYPE DROPPED_TIME              
------------------------------------ -------------------- ----------- --------------------------
BIN$8F1E9614172C11EAA7C5D51B86D72AB6 T1                   TABLE       2019-12-05 15:57:53.540000
BIN$8F1E9650172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY       CONSTRAINT  2019-12-05 15:57:53.540000
BIN$8F1E963C172C11EAA7C5D51B86D72AB6 T1_PRIMARY_KEY_INDEX INDEX       2019-12-05 15:57:53.540000

3 rows selected.

gSQL> FLASHBACK TABLE t1 TO BEFORE DROP;

Flashback complete.

gSQL> DESC T1

COLUMN_NAME TYPE         IS_NULLABLE
----------- ------------ -----------
ID          NUMBER(10,0) FALSE      
NAME        VARCHAR(32)  TRUE       

INDEX_NAME           TABLESPACE_NAME INDEX_TYPE IS_UNIQUE COLUMNS
-------------------- --------------- ---------- --------- -------
T1_PRIMARY_KEY_INDEX MEM_TEMP_TBS    BTREE      TRUE      ID     

CONSTRAINT_NAME CONSTRAINT_TYPE ASSOCIATED_INDEX     COLUMNS
--------------- --------------- -------------------- -------
T1_PRIMARY_KEY  PRIMARY KEY     T1_PRIMARY_KEY_INDEX ID  


gSQL> SELECT OBJECT_NAME, ORIGINAL_NAME, OBJECT_TYPE, DROPPED_TIME FROM USER_RECYCLEBIN;

no rows selected.

Unusable Table Segment

When a table segment is in the unusable state, full table scans and all DML operations on the table fail. An unusable table segment can be created in the following situations:

A table with an unusable segment must be truncated or dropped, recreated, and the data must be reloaded.

However, if another member in the cluster has the latest usable segment, the table can be recovered to a usable state containing the latest data by performing synchronize.

For example, suppose member g1n2 in cluster group g1 is restarted, causing table t1 to become unusable. If another member in the same cluster group, g1n1, still has a usable segment, the table can be recovered to a usable state by performing table synchronize, as shown below.

gSQL> SELECT NAME, TYPE, USABLE FROM V$RELATION WHERE USABLE = FALSE;

NAME TYPE  USABLE
---- ----- ------
T1   TABLE FALSE 

1 row selected.

gSQL> ALTER TABLE t1 SYNCHRONIZE;

Table altered.

gSQL> COMMIT;

Commit complete.

gSQL> SELECT NAME, TYPE, USABLE FROM V$RELATION WHERE USABLE = FALSE;

no rows selected.

Index

Index-related Statements

The statements for creating, dropping, or altering an index are as follows.

• Creating an index: Refer to CREATE INDEX.
• Dropping an index: Refer to DROP INDEX.
• Updating an index: Refer to ALTER INDEX.

The information related to an index object can be retrieved through the following views.

Index object related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_INDEXES

Information about user-accessible indexes

ALL_IND_COLUMNS

Column information about user-accessible index

USER_INDEXES

Information about user-owned indexes

USER_IND_COLUMNS

Column information about user-owned index

Concept of Index

An index is a table-related object designed to improve data access performance when querying a table. Each index consists of key values derived from the data in one or more columns of the table. It is an object separate from the table itself. 
The database automatically constructs the index key data when index is created, and the key data of the index is automatically managed when adding/ deleting/ updating the table data.

The following is an example of a query.

SELECT data FROM t1 WHERE id = 12345;
If an index does not exist, the results that satisfy the condition are found by scanning all rows in the table. If the table consists of many rows, but the number of results that satisfy the condition is relatively small, the query will have very inefficient response times.
When an index is created on the id column using the CREATE INDEX statement as shown below, the optimizer evaluates the costs of a full table scan versus an index scan, and selects the index scan to improve query performance.
CREATE INDEX t1_idx_id ON t1(id);

When creating an index, two or more columns can be used as the index key, and an index that consists of two or more keys is called a composite index. The composite index is sorted by the first key, and if the values of the first key are the same, it is then sorted by the second key. The sorting continues for as many keys as there are.

When creating indexes, the column sort order can be specified as ascending (ASC) or descending (DESC). The sort order for NULL values can be specified as NULLS FIRST or NULLS LAST. Refer to the following example.

gSQL> CREATE TABLE t1 ( value INTEGER );

Table created.

gSQL> INSERT INTO t1 VALUES (1), (NULL), (3), (2), (NULL);

5 rows created.

gSQL> CREATE INDEX idx1 ON t1 ( value ASC NULLS LAST );

Index created.

gSQL> CREATE INDEX idx2 ON t1 ( value DESC NULLS FIRST );

Index created.

gSQL> SELECT /*+ INDEX(t1, idx1) */ * FROM t1;

VALUE
-----
    1
    2
    3
 null
 null

5 rows selected.

gSQL> SELECT /*+ INDEX(t1, idx2) */ * FROM t1;

VALUE
-----
 null
 null
    3
    2
    1

5 rows selected.
In the example above, the index idx1 is specified in ascending order (ASC), with NULLS LAST, and the index idx2 is specified in descending order (DESC), with NULLS FIRST. 
When querying the table with the same query, different index hints are provided to ensure that all rows are retrieved using each respective index. The results using index idx1 are sorted in ascending order, with NULL values placed at the end. On the other hand, the results using index idx2 are sorted in descending order, with NULL values placed at the beginning.

Concept of UNIQUE

An index can be created as a UNIQUE index or a non-unique index. If the key values are not UNIQUE when creating a UNIQUE index, an error will occur.
NULL values are allowed as key values in both UNIQUE indexes and UNIQUE constraints.
If a NULL value is included, the truth table for UNIQUE behaves as follows. In other words, if the key is one, it can have multiple null values.
Truth table for uniqueness of two values

Value1

Value2

UNIQUE

1

1

false

1

2

true

1

null

true

null

null

true

A UNIQUE index or UNIQUE constraint consisting of two or more keys can have null as a whole value or as a partial value. If NULL is included in the composite key, the truth table for UNIQUE behaves as follows.

Truth table for UNIQUE in composite key

Row1

Row2

UNIQUE

(1, 1)

(1, 1)

false

(1, 1)

(1, 2)

true

(1, null)

(1, null)

false

(1, null)

(2, null)

true

(null, null)

(null, null)

true

Note that the definition of UNIQUE has been changed in the SQL standard as follows.


GOLDILOCKS follows the SQL 2011 standard, which is the version released after SQL 2003. According to the SQL standard, UNIQUE is defined based on the uniqueness of a composite key, as shown in the following table.

Truth table for UNIQUE of a composite key in the SQL standard

Row1

Row2

Until SQL1999

After SQL2003

(1, 1)

(1, 1)

false

false

(1, 1)

(1, 2)

true

true

(1, null)

(1, null)

true

false

(1, null)

(2, null)

true

true

(null, null)

(null, null)

true

true

Each DBMS vendor follows the SQL standard for the definition of UNIQUE as follows.

• DBMSs that follow the UNIQUE definition after SQL2003: Oracle, SQL server
• DBMSs that follow the UNIQUE definition up until SQL1999: Postgres, MySQL

Unusable Index Segment

If a table contains an index segment in the unusable state, any query that uses the index fails. In addition, all DML operations on the table fail. An unusable index segment can be created in the following cases:

If an unusable index segment is created, the index must be rebuilt, or the table must be truncated or dropped and recreated, after which the data must be reloaded.
If a key integrity constraint is violated while rebuilding the index, the index segment remains in the unusable state. In this case, the index must be dropped, the records that violate the key integrity constraint must be removed, and then the index must be recreated.
gSQL> CREATE TABLE t1 ( i1 INTEGER, i2 INTEGER );

Table created.

gSQL> CREATE UNIQUE INDEX t1x ON t1 ( i1 );

Index created.

gSQL> COMMIT;

Commit complete.

gSQL> INSERT /*+ APPEND DEFERRED_INDEX_MAINTENANCE */ INTO T1 VALUES ( 1, 1 ), ( 1, 2 );

2 rows created.

gSQL> COMMIT;

Commit complete.

gSQL> SELECT i1 FROM t1 WHERE i1 = 1;

ERR-42000(14052): segment is unusable - object name(T1X), physical id(36717675413547)

gSQL> ALTER INDEX t1x REBUILD;

ERR-23001(14016): some rows of base table violate uniqueness of index

gSQL> DROP INDEX t1x;

Index dropped.

gSQL> COMMIT;

Commit complete.

gSQL> DELETE FROM t1 WHERE i1 = 1 AND i2 = 2;

1 row deleted.

gSQL> COMMIT;

Commit complete.

gSQL> CREATE UNIQUE INDEX t1x ON t1 ( i1 );

Index created.

gSQL> COMMIT;

Commit complete.

gSQL> SELECT i1 FROM t1 WHERE i1 = 1;

I1
--
 1

1 row selected.

View

View-related Statements

The statements for creating, dropping, and altering a view are as follows.

• Creating a view: Refer to CREATE VIEW.
• Dropping a view: Refer to DROP VIEW.
• Altering a view: Refer to ALTER VIEW.

The information related to a view object can be retrieved through the following views.

View object-related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_VIEWS

Information about user-accessible views

ALL_DEPENDENCIES

Information about objects related to user-accessible views

USER_VIEWS

Information about user-owned views

USER_DEPENDENCIES

Information about objects related to user-owned views

INFORMATION_SCHEMA

VIEWS

Information about user-accessible views

VIEW_TABLE_USAGE

Information about the tables used when creating a view

VIEW_ROUTINE_USAGE

Information about the stored functions used when creating a view

Concept of View

While a table is a physical relation that stores data, a view is a logical relation consisting of queries. In the SQL standard, it is referred to as a viewed table. Queries performed on a view can be used in the same way as those on a table.

A view offers the following advantages.

A view created by a CREATE VIEW statement is replaced with an in-line view when executing queries as follows.

• Creating a view

CREATE VIEW v1 ( v_id, v_sum )
AS
SELECT l_partkey, SUM( l_quantity )
  FROM lineitem
 GROUP BY l_partkey;

• Querying a view

SELECT v_id, v_sum
  FROM v1
 WHERE v_sum > 1000;

• Translating a view

SELECT v_id, v_sum
  FROM ( SELECT l_partkey, SUM( l_quantity )
           FROM lineitem
          GROUP BY l_partkey
       ) v1 ( v_id, v_sum )
 WHERE v_sum > 1000;
When the v1 view is created using the asterisk (*) in the SELECT statement to represent all columns, even after a new column addr is added to the table t1 that the view accesses, querying the v1 view will retrieve all columns, including the newly added column.
gSQL> CREATE TABLE t1 ( id INTEGER, name VARCHAR(128) );

Table created.

gSQL> INSERT INTO t1 VALUES ( 1, 'leekmo' );

1 row created.
• Creating a view using an asterisk (*)
gSQL> CREATE VIEW v1 AS SELECT * FROM t1;

View created.
• Querying the view
gSQL> SELECT * FROM v1;

ID NAME  
-- ------
 1 leekmo

1 row selected.
• Adding a column to the table referenced by the view
gSQL> ALTER TABLE t1 ADD COLUMN addr VARCHAR(1024) DEFAULT 'N/A';

Table altered.
• Querying the view after adding the column
gSQL> SELECT * FROM v1;

ID NAME   ADDR
-- ------ ----
 1 leekmo N/A 

1 row selected.

However, creating a view using the asterisk (*) as shown above is not recommended, as it can require changes to the application when the table structure is modified.

Sequence

Sequence-related Statements

The statements for creating, dropping, altering, and using a sequence are as follows.

• Creating a sequence: Refer to CREATE SEQUENCE.
• Dropping a sequence: Refer to DROP SEQUENCE.
• Altering a sequence: Refer to ALTER SEQUENCE.
• Using a sequence: Refer to  NEXTVAL, CURRVAL.

The information related to a sequence object can be retrieved through the following views.

Sequence object-related information

Schema

Vew

Description

DICTIONARY_SCHEMA

ALL_SEQUENCES

Information about user-accessible sequences

USER_SEQUENCES

Information about user-owned sequences

INFORMATION_SCHEMA

SEQUENCES

Information about user-accessible sequences

Concept of Sequence

A sequence is an object that automatically creates sequential numbers and is referred to as a sequence generator in the SQL standard. It is a useful object for automatically managing unique keys or primary keys. A sequence can be used across multiple tables.

The following is an example of using a single sequence object to automatically generate the id column values and using it across multiple tables.

gSQL> CREATE SEQUENCE seq;

Sequence created.

gSQL> INSERT INTO t1 (id, name) VALUES ( seq.NEXTVAL, 'leekmo' );

1 row created.

gSQL> INSERT INTO t2 (id, addr) VALUES ( seq.CURRVAL, 'Seoul, Korea' );

1 row created.

gSQL> SELECT * FROM t1;

ID NAME  
-- ------
 1 leekmo

1 row selected.

gSQL> SELECT * FROM t2;

ID ADDR        
-- ------------
 1 Seoul, Korea

1 row selected.
In the example above, the next number for the id column in table t1 is automatically generated using the seq.NEXTVAL function. The same value is then used for the id column in table t2 using the seq.CURRVAL function. 
When creating a sequence, you can specify the starting value incremental value, minimum value, maximum value, cycle or no cycle and the cached value for the automatically generated numbers. 
For more information, refer to the CREATE SEQUENCE statement.

An identity column is similar to a sequence, and it automatically generates numbers for a table. It can be used as follows.

gSQL> CREATE TABLE t1 ( id INTEGER GENERATED ALWAYS AS IDENTITY, name VARCHAR(128) );

Table created.

gSQL> INSERT INTO t1 (name) VALUES ( 'leekmo' );

1 row created.

gSQL> INSERT INTO t1 (name) VALUES ( 'mkkim' );

1 row created.

gSQL> INSERT INTO t1 (name) VALUES ( 'xcom73' );

1 row created.

gSQL> SELECT * FROM t1;

ID NAME  
-- ------
 1 leekmo
 2 mkkim 
 3 xcom73

3 rows selected.
In the example above, the id column is created as an identity column when creating the t1 table. The value for the id column is automatically generated by the identity column when the INSERT statement is executed. 
For more information, refer to the <identity column specification> clause of the CREATE TABLE statement.
The sequence and the identity column are functionally similar, as both generate sequential numbers. However, they differ in the following aspects.

After a sequence is created, its values can be accessed using the NEXTVAL or CURRVAL functions. The sequence values are generated independently of the transaction and are not affected by the COMMIT or ROLLBACK of the transaction.

gSQL> INSERT INTO t1(id) VALUES( seq.NEXTVAL );

1 row created.

gSQL> SELECT id FROM t1;

ID
--
 1

1 row selected.

gSQL> ROLLBACK;

Rollback complete.

gSQL> INSERT INTO t1(id) VALUES( seq.NEXTVAL );

1 row created.

gSQL> SELECT id FROM t1;

ID
--
 2

1 row selected.
In the first INSERT statement of the above example, the seq.NEXTVAL function generates the value 1. Then, after the transaction was rolled back, the seq.NEXTVAL function generated the value 2, which incremented from the next value, independent of the transaction.
The sequence value can only be used in the following statements.

The sequence value can only be used in the locations specified above. It can not be used in subqueries, as an argument to aggregation functions, or in clauses such as WHERE, DISTINCT, GROUP BY, HAVING, or ORDER BY.

Cluster Sequence

When GOLDILOCKS is used to configure a cluster system, a global sequence object is used internally. The global sequence object creates a pool of sequence values that are shared across the entire cluster system, and allocates them to each member node based on the cache size when the NEXTVAL function is called. In other words, if a specific node is allocated 20 sequence values, the other nodes will receive values starting from the next available value. Each member node loads the sequence values assigned by the global sequence object into its local cache and returns them as the result of NEXTVAL calls until all the allocated values are exhausted.

The global sequence object has the following features and constraints compared to a sequence in a standalone database.

Synonym

Synonym-related Statements

The statements for creating and dropping a synonym are as follows.

• Creating a synonym: Refer to CREATE SYNONYM.
• Dropping a synonym: Refer to DROP SYNONYM.

The information related to a synonym object can be retrieved through the following views.

Synonym object related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_SYNONYMS

All synonym information

USER_SYNONYMS

Information about user-owned synonym

Concept of Synonym

A synonym is an alias for the following objects.

Synonyms can be used as aliases in SELECT, INSERT, UPDATE, DELETE, LOCK TABLE, GRANT, REVOKE, and COMMENT statements.

Using synonyms is very convenient because only the synonym needs to be redefined, without modifying the application, even when the schema of the underlying objects changes. Database security can be improved by hiding the real name of the object and its owner. Additionally, usability is enhanced by replacing long object names with shorter ones.

Synonyms are classified into private synonyms and public synonyms. A private synonym is a schema object, while a public synonym is a non-schema object.

The following examples of creating and using private and public synonyms, as indicated in the table below, illustrate their concepts.

gSQL> \CONNECT u1 u1
gSQL> CREATE TABLE u1.t1 (col1 INTEGER );
gSQL> INSERT INTO u1.t1 VALUES(1);
gSQL> COMMIT;

Private Synonym

A private synonym is a schema object. If a synonym is created without specifying a schema name, the default schema name of the user executing the statement is used.

gSQL> \CONNECT u2 u2 
gSQL> CREATE SYNONYM u2.syn1 FOR u1.t1;

Synonym created.

gSQL> SELECT * FROM u2.syn1;

ERR-42000(16254): lacks privilege (SELECT ON TABLE "U1"."T1")

A synonym is only an alias. Therefore, if a user does not have the appropriate privileges on the underlying object u1.t1, the user can not use it, even if the user created the synonym.

gSQL> \CONNECT u1 u1
gSQL> GRANT SELECT ON TABLE u2.syn1 TO u2;
gSQL> \CONNECT u2 u2 
gSQL> SELECT * FROM u2.syn1;
COL1
----
   1

1 row selected.

gSQL> SELECT * FROM u1.t1;
COL1
----
   1

1 row selected.

gSQL> DROP SYNONYM u2.syn1;

Synonym dropped.

In the above example, the SELECT privilege on u2.syn1 is granted to u2, but this is the same as granting the SELECT privilege on u1.t1 to u2. Therefore, caution should be exercised when granting privileges to synonyms.

Public Synonym

A public synonym is a non-schema object. The schema name cannot be specified when creating or dropping it.

gSQL> \CONNECT u2 u2
gSQL> CREATE PUBLIC SYNONYM pubSyn1 FOR u1.t1;
Synonym created.
gSQL> SELECT * FROM pubSyn1;
ERR-42000(16254): lacks privilege (SELECT ON TABLE "U1"."T1")

A public synonym does not have an owner and is accessible to all users. However, a user without the appropriate privileges on the underlying objects cannot access them.

gSQL> \CONNECT u1 u1
gSQL> GRANT SELECT ON TABLE pubSyn1 TO u2;
gSQL> \CONNECT u2 u2 
gSQL> SELECT * FROM pubSyn1;
COL1
----
   1

1 row selected.

gSQL> SELECT * FROM u1.t1;
COL1
----
   1

1 row selected.

gSQL> DROP SYNONYM pubSyn1;

Synonym dropped.

Stored Procedure

Stored Procedure-related Statements

The statements for creating, dropping, and altering a stored procedure are as follows.

• Creating a stored procedure: Refer to CREATE PROCEDURE.
• Dropping a stored procedure: Refer to DROP PROCEDURE.
• Altering a stored procedure: Refer to ALTER PROCEDURE.

The information related to a stored procedure can be retrieved through the following views.

Stored procedure object related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_ARGUMENTS

Argument information for user-accessible procedures and functions

ALL_DEPENDENCIES

Information about objects related to user-accessible procedures and functions

ALL_PROCEDURES

Object information for user-accessible procedures and functions

ALL_SOURCE

Source text information for user-accessible procedures and functions

USER_ARGUMENTS

Argument information for user-owned procedures and functions

USER_DEPENDENCIES

Information about objects related to user-owned procedures and functions

USER_PROCEDURES

Object information for user-owned procedures and functions

USER_SOURCE

Source text information for user-accessible procedures and functions

INFORMATION_SCHEMA

PARAMETERS

Argument information for user-accessible procedures and functions

ROUTINES

Object information for user-accessible procedures and functions

ROUTINE_ROUTINE_USAGE

Information about procedures and functions referenced by user-accessible procedures and functions

ROUTINE_SEQUENCE_USAGE

Information about sequences referenced by user-accessible procedures and functions

ROUTINE_TABLE_USAGE

Information about tables and views referenced by user-accessible procedures and functions

Concept of Stored Procedure

A stored procedure is a type of persistent stored module in procedure form, defined and managed at the schema level, like other schema-level database objects. Since it is in procedure form, it does not have a return value. It is used by being directly called in a CALL statement, or from another stored procedure or stored function.

A stored procedure can be created with either an <SQL body> or an <external body>.
A stored procedure with an <SQL body> declares PL items, can be used within a block, and executes pl statements.
A stored procedure with an <external body> executes an external routine that is programmed in an external programming language.

For more information about a stored procedure, refer to the Schema-level Procedure.

A stored procedure with an <SQL body> is used as follows.

CREATE OR REPLACE PROCEDURE PROC1( A1 INTEGER, A2 INTEGER )
IS  
  V1 INTEGER;
BEGIN
  SELECT COUNT(*)
    INTO V1
    FROM T1
    WHERE T1.I1 >= A1 AND T1.I1 <= A2; 
  DBMS_OUTPUT.PUT_LINE( 'V1 = ' || V1 );
END;
/

BEGIN
  PROC1( 2, 4 ); -- call schema-level procedure
END;
/

V1 = 3

Anonymous PL block executed.

A stored procedure with an <external body> is used as follows.

gSQL>
CREATE OR REPLACE PROCEDURE proc1( p1 NATIVE_INTEGER,
                                   p2 NATIVE_INTEGER,
                                   p3 OUT NATIVE_INTEGER ) AS
LANGUAGE C
LIBRARY lib NAME "add"
PARAMETERS( p1 INT , 
            p2 INT , 
            p3 INT );
/

Procedure created.

gSQL>
DECLARE 
  var1 INTEGER;
BEGIN
  -- call schema-level procedure that calls an external routine 
  proc1( 5 , 3 , var1 );
  DBMS_OUTPUT.PUT_LINE( 'result of external routine : ' || var1 );
END;
/

result of external routine : 8
Anonymous PL block executed.

Stored Function

Stored Function-related Statements

The statements for creating, dropping and altering a stored function are as follows.

• Creating a stored function: Refer to CREATE FUNCTION.
• Dropping a stored function: Refer to DROP FUNCTION .
• Altering a stored function: Refer to ALTER FUNCTION.

The information related to a stored function can be retrieved through the following views.

Stored function object related information

Schema

View

Description

DICTIONARY_SCHEMA

ALL_ARGUMENTS

Argument information for user-accessible procedures and functions

ALL_DEPENDENCIES

Information about objects related to user-accessible procedures and functions

ALL_PROCEDURES

Object information for user-accessible procedures and functions

ALL_SOURCE

Source text information for user-accessible procedures and functions

USER_ARGUMENTS

Argument information for user-owned procedures and functions

USER_DEPENDENCIES

Information about objects related to user-owned procedures and functions

USER_PROCEDURES

Object information for user-owned procedures and functions

USER_SOURCE

Source text information for user-accessible procedures and functions

INFORMATION_SCHEMA

PARAMETERS

Argument information for user-accessible procedures and functions

ROUTINES

Object information for user-accessible procedures and functions

ROUTINE_ROUTINE_USAGE

Information about procedures and functions referenced by user-accessible procedures and functions

ROUTINE_SEQUENCE_USAGE

Information about sequences referenced by user-accessible procedures and functions

ROUTINE_TABLE_USAGE

Information about tables and views referenced by user-accessible procedures and functions

Concept of Stored Function

A stored function is a type of persistent stored module in function form, defined and managed within the schema unit, just like other schema-level database objects. A stored function is classified as follows, according to the definition of the RETURN clause.

For more information about a stored function, refer to the schema-level function.

RETURN <datatype> Function

The datatype of the expression returned by executing the function is defined in the RETURN clause. The function must define the result value to be returned. Such functions can be executed directly using the CALL statement, or they can be used as expressions within a stored procedure or stored function, or as expressions in SQL statements.

A stored function can be created with either an <SQL body> or an <external body>.
The execution result of a stored function with an <SQL body> is specified through the <RETURN Statement>.
The execution result of a stored function with an <external body> is the result of executing the external routine, which is programmed in an external programming language.

A stored function with an <SQL body> is used as follows.

gSQL> CREATE OR REPLACE FUNCTION FUNC1( A1 INTEGER, A2 INTEGER )
RETURN INTEGER
IS
  V1 INTEGER;
BEGIN
  SELECT COUNT(*)
    INTO V1
    FROM T1
    WHERE T1.I1 >= A1 AND T1.I1 <= A2;
  RETURN V1;
END; 
/

Function created.

gSQL> SELECT FUNC1( 2, 4 ) FROM DUAL;

FUNC1( 2, 4 )
-------------
            3

1 row selected.

A stored function with an <external body> is used as follows.

gSQL> 
CREATE OR REPLACE FUNCTION func1( p1 NATIVE_INTEGER,
                                  p2 NATIVE_INTEGER )
  RETURN NATIVE_INTEGER AS
LANGUAGE C
LIBRARY lib NAME "add"
PARAMETERS( p1 INT , 
            p2 INT , 
            RETURN INT );
/

Function created.

-- execute schema-level function that calls an external routine 
gSQL> SELECT FUNC1( 2, 4 ) FROM DUAL;

FUNC1( 2, 4 )
-------------
            6

1 row selected.

Table Function

The RETURN clause defines the table column list of the result set returned by executing the function, and such a function is referred to as a table function. The table function defines the result set to return using a select statement or a cursor variable. It can be used as a derived table in the FROM clause of a SELECT statement.

The table function executes the defined SELECT statement or the cursor query of the cursor variable and returns the resulting set to the parent SELECT statement. This returned result set forms the table function-derived table in the SELECT statement. Additionally, the columns of tables listed before the table function-derived table in the FROM clause can be referenced as arguments for the table function.

To use the table function as described above, declare the cursor variable or return the result set through the <RETURN TABLE Statement>. Therefore, the table function must be a stored function with an <SQL body>.

gSQL> CREATE TABLE t_score( c_grade INTEGER, c_score INTEGER );

Table created.

gSQL> INSERT INTO t_score VALUES ( 1 , 98 ) , ( 1 , 97 ) , ( 1 , 99 ),
                                 ( 2 , 95 ) , ( 2 , 98 ) , ( 2 , 92 ),
                                 ( 3 , 98 ) , ( 3 , 96 ) , ( 3 , 94 );

9 rows created.

gSQL> COMMIT;

Commit complete.
gSQL> 
CREATE OR REPLACE FUNCTION tf_cv( p_grade INTEGER ) 
  RETURN TABLE( rf_grade INTEGER, rf_score INTEGER ) AS
  cv SYS_REFCURSOR;
BEGIN
  OPEN cv FOR SELECT * FROM t_score WHERE c_grade = p_grade;
  
  RETURN TABLE( cv );
END;
/

Function created.

gSQL> SELECT rf_grade, rf_score FROM TABLE( tf_cv( 2 ) );

RF_GRADE RF_SCORE
-------- --------
       2       95
       2       98
       2       92

3 rows selected.
gSQL> 
CREATE OR REPLACE FUNCTION tf_select( p_grade INTEGER ) 
  RETURN TABLE( rf_grade INTEGER, rf_score INTEGER ) AS
BEGIN
  RETURN TABLE ( SELECT * FROM t_score WHERE c_grade = p_grade );
END;
/

Function created.

gSQL> SELECT rf_grade, rf_score FROM TABLE( tf_select( 2 ) );

RF_GRADE RF_SCORE
-------- --------
       2       95
       2       98
       2       92

3 rows selected.

Package

Package-related Statement

The statements for creating, dropping and altering a package are as follows.

The information related to a package object can be retrieved through the following views.

Package object-related information.

Schema

View

Description

DICTIONARY_SCHEMA

ALL_OBJECTS

Information about user-accessible objects

ALL_PACKAGE_PRIVS

Information about privileges related to user packages

ALL_PACKAGE_PRIVS_MADE

Information about privileges granted by a user to allow access to the package

ALL_PACKAGE_PRIVS_RECD

Information about privileges granted to a user to allow access to the package

ALL_SOURCE

Information about the source text of procedures, functions, and packages that are accessible by a user

USER_OBJECTS

Information about user-owned objects

USER_PACKAGE_PRIVS

Information about privileges related to user-owned packages

USER_PACKAGE_PRIVS_MADE

Information about privileges granted by a user to allow access to the user-owned packages

USER_PACKAGE_PRIVS_RECD

Information about privileges granted to a user to allow access to the user-owned packages

USER_SOURCE

Information about the source text of procedures, functions, and packages that are owned by a user

INFORMATION_SCHEMA

MODULES

Information about user-accessible SQL-server modules (packages)

MODULE_BODY

Information about user-accessible package bodies

MODULE_BODY_MODULE_USAGE

Information about other packages that are being used by user-accessible package bodies

MODULE_BODY_ROUTINE_USAGE

Information about procedures or functions that are being used by user-accessible package bodies

MODULE_BODY_SEQUENCE_USAGE

Information about sequences that are being used by user-accessible package bodies

MODULE_BODY_TABLE_USAGE

Information about tables that are being used by user-accessible package bodies

MODULE_MODULE_USAGE

Information about other packages that are being used by user-accessible packages

MODULE_PRIVILEGES

Information about privileges related to user-accessible packages

MODULE_ROUTINE_USAGE

Information about procedures or functions that are being used by user-accessible packages

MODULE_SEQUENCE_USAGE

Information about sequences that are being used by user-accessible packages

MODULE_TABLE_USAGE

Information about tables that are being used by user-accessible packages

ROUTINE_MODULE_USAGE

Information about packages that are being used by user-accessible procedures or functions

VIEW_MODULE_USAGE

Information about packages that are being used by user-accessible views

Concept of Package

A package is a schema object that groups logically related PSM types, variables, subprograms, cursors, and exceptions. The package is stored in the database after being compiled, allowing other programs (such as other packages, procedures, or external programs) to reference, share, and execute its items.

For more information about the package, refer to PSM Packages.

The following is an example of creating a package.

CREATE TABLE emp( empno NUMBER, sal NUMBER, comm NUMBER );
Table created.

INSERT INTO emp VALUES( 3548, 6000, 1000 );
1 row created.

INSERT INTO emp VALUES( 9369, 5000, NULL );
1 row created.

INSERT INTO emp VALUES( 7294, 4000, 500 );
1 row created.

COMMIT;
Commit complete.


CREATE OR REPLACE PACKAGE emp_mgmt
IS
  PROCEDURE adjust_sal(v_flag VARCHAR, v_empno NUMBER, v_pct NUMBER);
  FUNCTION get_annual_sal(v_empno NUMBER) RETURN NUMBER;
END;
/

Package created.


CREATE OR REPLACE PACKAGE BODY emp_mgmt
IS
  PROCEDURE adjust_sal(v_flag VARCHAR, v_empno NUMBER, v_pct NUMBER) IS
  BEGIN
    IF v_flag = 'INCREASE' THEN
      UPDATE emp SET sal = sal + (sal * (v_pct / 100)) WHERE empno = v_empno;
    ELSE
      UPDATE emp SET sal = sal - (sal * (v_pct / 100)) WHERE empno = v_empno;
    END IF;
  END;
  FUNCTION get_annual_sal (v_empno NUMBER) RETURN NUMBER
  IS
    v_sal NUMBER;
  BEGIN
    SELECT (sal + NVL(comm,0)) * 12 INTO v_sal FROM emp WHERE empno = v_empno;
    RETURN v_sal;
  END;
END;
/

Package created.

The following is an example of using the package.

call emp_mgmt.adjust_sal('INCREASE',7369, 10);

Procedure Call complete.


SELECT emp_mgmt.get_annual_sal(7294) FROM DUAL;
EMP_MGMT.GET_ANNUAL_SAL(7294)
-----------------------------
                        54000
1 row selected.

Library

Library-related Statement

The statements for creating and dropping a library are as follows:

Information related to library objects can be retrieved through the following views:

Information on library objects

Schema

View

Description

DICTIONARY_SCHEMA

ALL_LIBRARIES

Library information accessible to the user

ALL_OBJECTS

Object information accessible to the user

USER_LIBRARIES

Library information owned by the user

USER_OBJECTS

Object information owned by the user

Concept of Library

A Library is a schema object that refers to a shared library file composed of external C functions. The database utilizes this object to call functions contained within the external library. The Library object can specify either the filename or the full path of the shared library file. However, if only the filename is specified, the shared library must be located in the directory set by the EXTLIB_DIR property to be loaded successfully.
A library is referenced by an external routine, and when the routine is executed, the shared library specified in the library object is loaded and executed.

For more information, refer to External Routine.

The following is an example of creating a library.

CREATE LIBRARY lib_add AS '/home/user/extlib/add.so';

The following is an example of an external function that references a library.

CREATE FUNCTION func1( p1 IN NATIVE_INTEGER, 
                       p2 IN NATIVE_INTEGER )
      RETURN NATIVE_INTEGER AS
LANGUAGE C
LIBRARY lib_add NAME "add"
PARAMETERS ( p1 INT,
             p2 INT,
             RETURN INT );

That is, when an external routine is executed, the shared library is loaded and executed through the library object, as shown in the example below.

gSQL> 
SELECT func1( 6 , 7 ) FROM DUAL;

FUNC1( 6 , 7 ) 
-----------------
               13

1 row selected.

Trigger

Trigger-related Statement

The statements for creating, altering and dropping a trigger are as follows:

Information related to trigger objects can be retrieved through the following views:

Information on trigger objects

Schema

View

Description

DICTIONARY_SCHEMA

ALL_DEPENDENCIES

Dependency information of database objects, including triggers accessible to the user

ALL_OBJECTS

Information on all objects, including triggers accessible to the user

ALL_SOURCE

Source text information of objects, including triggers accessible to the user

ALL_TRIGGERS

Information on trigger objects accessible to the user

USER_DEPENDENCIES

Dependency information of database objects, including triggers owned by the user

USER_OBJECTS

Information on all objects, including triggers owned by the user

USER_SOURCE

Source text information of objects, including triggers owned by the user

USER_TRIGGERS

Information on trigger objects owned by the user

INFORMATION_SCHEMA

TRIGGERS

Information on trigger objects accessible to the user

TRIGGERED_UPDATE_COLUMNS

Information on update event columns specified in triggers accessible to the user

TRIGGER_EVENT_ORDER

Execution order information of triggers with the same event attributes, accessible to the user

TRIGGER_MODULE_USAGE

Information on packages referenced by triggers accessible to the user

TRIGGER_ROUTINE_USAGE

Information on procedures and functions referenced by triggers accessible to the user

TRIGGER_SEQUENCE_USAGE

Information on sequences referenced by triggers accessible to the user

TRIGGER_TABLE_USAGE

Information on tables referenced by triggers accessible to the user

Concept of Trigger

A trigger is a stored program unit written in PSM. It is compiled and stored in the database, and it is a schema object that is automatically executed by the database whenever an INSERT, UPDATE, or DELETE operation occurs on a specific table.

The key components of a trigger are as follows:

Component

Description

Target object

The table that the trigger continuously monitors. A trigger is always associated with a specific table and detects changes occurring in that table.

Trigger event

Refers to the DML operations executed on the target table. The trigger is activated by one or more of the following events: INSERT, UPDATE, or DELETE.

Trigger timing

Specifies when the trigger is executed. It is classified into BEFORE triggers, which execute before the event occurs on the target object, and AFTER triggers, which execute after the event has been completed.

Trigger execution Unit

Determines the frequency and scope of trigger execution. A STATEMENT-level trigger executes once per DML statement, whereas a ROW-level trigger executes individually for each affected row.

Trigger action

Defines the operation performed when the trigger is activated. It is typically written as a PSM block or executes a procedure using a CALL statement.

Proper use of triggers can improve the efficiency of database operations and help in building and deploying stable applications.

However, excessive use of triggers may create complex interdependencies, leading to unintended cascading behavior. This can make the system harder to maintain, so caution should be exercised when using triggers.

For more information, refer to the Trigger section.

The following is an example of creating a trigger using the CREATE TRIGGER statement.

gSQL>
CREATE TABLE employees( emp_id     NUMBER PRIMARY KEY,
                        name       VARCHAR(100),
                        salary     NUMBER,
                        updated_at DATE );
Table created.

gSQL>
CREATE TABLE audit_log( action    VARCHAR(20),
                        emp_id    NUMBER,     
                        timestamp DATE );
Table created.

gSQL>
CREATE TRIGGER employees_trigger
  AFTER                           --# Trigger timing
    INSERT OR UPDATE OR DELETE    --# Trigger event
  ON employees                    --# Target object
REFERENCING OLD ROW AS o_row
            NEW ROW AS n_row
  FOR EACH ROW                    --# Trigger execution unit
BEGIN                             --# Trigger action start
  IF INSERTING THEN
    INSERT INTO audit_log VALUES( 'INSERT', n_row.emp_id, SYSDATE );
  ELSIF UPDATING THEN
    INSERT INTO audit_log VALUES( 'UPDATE', n_row.emp_id, SYSDATE );
  ELSIF DELETING THEN
    INSERT INTO audit_log VALUES( 'DELETE', o_row.emp_id, SYSDATE );
  ELSE
    NULL;
  END IF;
END;
/
Trigger created.
gSQL>
SELECT TRIGGER_NAME, TRIGGERING_EVENT, TABLE_NAME, STATUS
  FROM USER_TRIGGERS
 WHERE TRIGGER_NAME = 'EMPLOYEES_TRIGGER';
TRIGGER_NAME      TRIGGERING_EVENT           TABLE_NAME STATUS
----------------- -------------------------- ---------- ------
EMPLOYEES_TRIGGER INSERT OR UPDATE OR DELETE EMPLOYEES  ENABLE
1 row selected.
gSQL> INSERT INTO employees VALUES ( 100, 'SUNJE', 1000, SYSDATE );
1 row created.
gSQL> INSERT INTO employees VALUES ( 101, 'SOFT', 2000, SYSDATE );
1 row created.
gSQL> UPDATE employees SET salary = salary * 2 WHERE emp_id = 100;
1 row updated.
gSQL> DELETE FROM employees WHERE emp_id = 101;
1 row deleted.
gSQL> COMMIT;

gSQL> SELECT * FROM audit_log;
ACTION EMP_ID TIMESTAMP 
------ ------ ----------
INSERT    100 2026-03-23
INSERT    101 2026-03-23
UPDATE    100 2026-03-23
DELETE    101 2026-03-23
4 rows selected.

The following is an example of how to enable or disable a trigger using the ALTER TRIGGER name ENABLE/DISABLE statement.

gSQL> ALTER TRIGGER employees_trigger DISABLE;
Trigger altered.

gSQL>
SELECT TRIGGER_NAME, TRIGGERING_EVENT, TABLE_NAME, STATUS
  FROM USER_TRIGGERS
 WHERE TRIGGER_NAME = 'EMPLOYEES_TRIGGER';
TRIGGER_NAME      TRIGGERING_EVENT           TABLE_NAME STATUS 
----------------- -------------------------- ---------- -------
EMPLOYEES_TRIGGER INSERT OR UPDATE OR DELETE EMPLOYEES  DISABLE
1 row selected.

gSQL> INSERT INTO employees VALUES ( 102, 'GOLDILOCKS', 3000, SYSDATE );
1 row created.
gSQL> COMMIT;

gSQL> SELECT * FROM audit_log WHERE EMP_ID = 102;
no rows selected.

A trigger can also be dropped using the DROP TRIGGER statement.

gSQL> DROP TRIGGER employees_trigger;
Trigger dropped.

gSQL>
SELECT TRIGGER_NAME, TRIGGERING_EVENT, TABLE_NAME, STATUS
  FROM USER_TRIGGERS
 WHERE TRIGGER_NAME = 'EMPLOYEES_TRIGGER';
no rows selected.