EDB Database Compatibility For Oracle Developers Reference Guide v10
EDB Database Compatibility For Oracle Developers Reference Guide v10
November 1, 2017
Database Compatibility for Oracle Developers
Reference Guide
by EnterpriseDB Corporation
Copyright 2007 - 2017 EnterpriseDB Corporation. All rights reserved.
Table of Contents
1 Introduction ............................................................................................................................................ 8
1.1 Whats New .................................................................................................................................... 9
1.2 Typographical Conventions Used in this Guide ............................................................................. 9
2 The SQL Language................................................................................................................................10
2.1 SQL Syntax ...................................................................................................................................10
2.1.1 Lexical Structure ....................................................................................................................11
2.1.2 Identifiers and Key Words .....................................................................................................12
2.1.3 Constants ...............................................................................................................................14
2.1.3.1 String Constants ................................................................................................................14
2.1.3.2 Numeric Constants ............................................................................................................14
2.1.3.3 Constants of Other Types ..................................................................................................15
2.1.4 Comments ..............................................................................................................................16
2.2 Data Types .....................................................................................................................................17
2.2.1 Numeric Types ......................................................................................................................18
2.2.1.1 Integer Types ....................................................................................................................18
2.2.1.2 Arbitrary Precision Numbers ............................................................................................18
2.2.1.3 Floating-Point Types .........................................................................................................19
2.2.2 Character Types .....................................................................................................................20
2.2.3 Binary Data ............................................................................................................................22
2.2.4 Date/Time Types ...................................................................................................................23
2.2.4.1 INTERVAL Types ............................................................................................................24
2.2.4.2 Date/Time Input ................................................................................................................25
2.2.4.2.1 Dates ........................................................................................................................25
2.2.4.2.2 Times .......................................................................................................................26
2.2.4.2.3 Time Stamps ............................................................................................................26
2.2.4.3 Date/Time Output .............................................................................................................27
2.2.4.4 Internals ............................................................................................................................27
2.2.5 Boolean Type .........................................................................................................................28
2.2.6 XML Type .............................................................................................................................29
2.3 SQL Commands ............................................................................................................................30
2.3.1 ALTER INDEX .....................................................................................................................31
2.3.2 ALTER PROCEDURE ..........................................................................................................33
2.3.3 ALTER PROFILE .................................................................................................................34
2.3.4 ALTER QUEUE ....................................................................................................................38
2.3.5 ALTER QUEUE TABLE ......................................................................................................42
2.3.6 ALTER ROLE IDENTIFIED BY .....................................................................................43
2.3.7 ALTER ROLE - Managing Database Link and DBMS_RLS Privileges ..............................45
2.3.8 ALTER SEQUENCE ............................................................................................................48
2.3.9 ALTER SESSION .................................................................................................................50
2.3.10 ALTER TABLE ....................................................................................................................52
2.3.11 ALTER TABLESPACE ........................................................................................................56
2.3.12 ALTER USER IDENTIFIED BY......................................................................................57
2.3.13 ALTER USER|ROLE PROFILE MANAGEMENT CLAUSES .......................................59
2.3.14 CALL.....................................................................................................................................62
2.3.15 COMMENT ...........................................................................................................................63
2.3.16 COMMIT ...............................................................................................................................65
2.3.17 CREATE DATABASE .........................................................................................................66
2.3.18 CREATE [PUBLIC] DATABASE LINK .............................................................................67
2.3.19 CREATE DIRECTORY ........................................................................................................79
2.3.20 CREATE FUNCTION...........................................................................................................81
2.3.21 CREATE INDEX ..................................................................................................................88
2.3.22 CREATE MATERIALIZED VIEW ......................................................................................90
1 Introduction
Database Compatibility for Oracle means that an application runs in an Oracle
environment as well as in the EDB Postgres Advanced Server (Advanced Server)
environment with minimal or no changes to the application code.
This guide provides reference material about the compatibility features offered by
Advanced Server:
Data types to define the applications database tables that are compatible with
Oracle databases
SQL statements that are compatible with Oracle SQL
System and built-in functions for use in SQL statements and procedural logic that
are compatible with Oracle databases
Stored Procedure Language (SPL) to create database server-side application logic
for stored procedures, functions, triggers, and packages
System catalog views that are compatible with Oracles data dictionary
For detailed information about Advanced Server's compatibility features and extended
functionality, please see the complete library of Advanced Server documentation,
available at:
http://www.enterprisedb.com/products-services-training/products/documentation
Advanced Server now supports usage of a composite type (created by the CREATE
TYPE AS command) referenced by a field as its data type within a user-defined
record type (declared with the TYPE IS RECORD statement). This record type
containing a composite type can only be declared in a package specification or a
package body. A composite type is not compatible with Oracle databases.
However, composite types can generally be used within all SPL programs
(functions, procedures, triggers, packages, etc.) as long as the composite type is
not part of a record type (with the exception of packages). For more information
on composite types, see Section 2.3.36.
In the following descriptions a term refers to any word or group of words which may be
language keywords, user-supplied values, literals, etc. A terms exact meaning depends
upon the context in which it is used.
Italic font introduces a new term, typically, in the sentence that defines it for the
first time.
Fixed-width (mono-spaced) font is used for terms that must be given
literally such as SQL commands, specific table and column names used in the
examples, programming language keywords, etc. For example, SELECT * FROM
emp;
Italic fixed-width font is used for terms for which the user must
substitute values in actual usage. For example, DELETE FROM table_name;
A vertical pipe | denotes a choice between the terms on either side of the pipe. A
vertical pipe is used to separate two or more alternative terms within square
brackets (optional choices) or braces (one mandatory choice).
Square brackets [ ] denote that one or none of the enclosed term(s) may be
substituted. For example, [ a | b ], means choose one of a or b or neither
of the two.
Braces {} denote that exactly one of the enclosed alternatives must be specified.
For example, { a | b }, means exactly one of a or b must be specified.
Ellipses ... denote that the proceeding term may be repeated. For example, [ a |
b ] ... means that you may have the sequence, b a a b a.
The Advanced Server documentation set includes syntax and commands for extended
functionality (functionality that does not provide database compatibility for Oracle or
support Oracle-styled applications) that is not included in this guide.
A token can be a key word, an identifier, a quoted identifier, a literal (or constant), or a
special character symbol. Tokens are normally separated by whitespace (space, tab, new
line), but need not be if there is no ambiguity (which is generally only the case if a
special character is adjacent to some other token type).
Additionally, comments can occur in SQL input. They are not tokens - they are
effectively equivalent to whitespace.
This is a sequence of three commands, one per line (although this is not required; more
than one command can be on a line, and commands can usually be split across lines).
The SQL syntax is not very consistent regarding what tokens identify commands and
which are operands or parameters. The first few tokens are generally the command name,
so in the above example we would usually speak of a SELECT, an UPDATE, and an
INSERT command. But for instance the UPDATE command always requires a SET token
to appear in a certain position, and this particular variation of INSERT also requires a
VALUES token in order to be complete. The precise syntax rules for each command are
described in Section 0.
Tokens such as SELECT, UPDATE, or VALUES in the example above are examples of key
words, that is, words that have a fixed meaning in the SQL language. The tokens
MY_TABLE and A are examples of identifiers. They identify names of tables, columns, or
other database objects, depending on the command they are used in. Therefore they are
sometimes simply called, names. Key words and identifiers have the same lexical
structure, meaning that one cannot know whether a token is an identifier or a key word
without knowing the language.
SQL identifiers and key words must begin with a letter (a-z or A-Z). Subsequent
characters in an identifier or key word can be letters, underscores, digits (0-9), dollar
signs ($), or number signs (#).
A convention often used is to write key words in upper case and names in lower case,
e.g.,
Quoted identifiers can contain any character, except the character with the numeric code
zero.
To include a double quote, use two double quotes. This allows you to construct table or
column names that would otherwise not be possible (such as ones containing spaces or
ampersands). The length limitation still applies.
2.1.3 Constants
The kinds of implicitly-typed constants in Advanced Server are strings and numbers.
Constants can also be specified with explicit types, which can enable more accurate
representation and more efficient handling by the system. These alternatives are
discussed in the following subsections.
digits
digits.[digits][e[+-]digits]
[digits].digits[e[+-]digits]
digitse[+-]digits
where digits is one or more decimal digits (0 through 9). At least one digit must be
before or after the decimal point, if one is used. At least one digit must follow the
exponent marker (e), if one is present. There may not be any spaces or other characters
embedded in the constant. Note that any leading plus or minus sign is not actually
considered part of the constant; it is an operator applied to the constant.
42
3.5
4.
.001
5e2
1.925e-3
A numeric constant that contains neither a decimal point nor an exponent is initially
presumed to be type INTEGER if its value fits in type INTEGER (32 bits); otherwise it is
presumed to be type BIGINT if its value fits in type BIGINT (64 bits); otherwise it is
taken to be type NUMBER. Constants that contain decimal points and/or exponents are
always initially presumed to be type NUMBER.
CAST('string' AS type)
The string constants text is passed to the input conversion routine for the type called
type. The result is a constant of the indicated type. The explicit type cast may be omitted
if there is no ambiguity as to the type the constant must be (for example, when it is
assigned directly to a table column), in which case it is automatically coerced.
CAST can also be used to specify runtime type conversions of arbitrary expressions.
2.1.4 Comments
/* multiline comment
* block
*/
where the comment begins with /* and extends to the matching occurrence of */.
The type, INTEGER, stores whole numbers (without fractional components) between the
values of -2,147,483,648 and +2,147,483,647. Attempts to store values outside of the
allowed range will result in an error.
Columns of the ROWID type holds fixed-length binary data that describes the physical
address of a record. ROWID is an unsigned, four-byte INTEGER that stores whole
numbers (without fractional components) between the values of 0 and 4,294,967,295.
Attempts to store values outside of the allowed range will result in an error.
The type, NUMBER, can store practically an unlimited number of digits of precision and
perform calculations exactly. It is especially recommended for storing monetary amounts
and other quantities where exactness is required. However, the NUMBER type is very slow
compared to the floating-point types described in the next section.
Both the precision and the scale of the NUMBER type can be configured. To declare a
column of type NUMBER use the syntax
NUMBER(precision, scale)
NUMBER(precision)
selects a scale of 0. Specifying NUMBER without any precision or scale creates a column
in which numeric values of any precision and scale can be stored, up to the
implementation limit on precision. A column of this kind will not coerce input values to
any particular scale, whereas NUMBER columns with a declared scale will coerce input
values to that scale. (The SQL standard requires a default scale of 0, i.e., coercion to
integer precision. For maximum portability, it is best to specify the precision and scale
explicitly.)
If the precision or scale of a value is greater than the declared precision or scale of a
column, the system will attempt to round the value. If the value cannot be rounded so as
to satisfy the declared limits, an error is raised.
The data types REAL and DOUBLE PRECISION are inexact, variable-precision numeric
types. In practice, these types are usually implementations of IEEE Standard 754 for
Binary Floating-Point Arithmetic (single and double precision, respectively), to the extent
that the underlying processor, operating system, and compiler support it.
Inexact means that some values cannot be converted exactly to the internal format and are
stored as approximations, so that storing and printing back out a value may show slight
discrepancies. Managing these errors and how they propagate through calculations is the
subject of an entire branch of mathematics and computer science and will not be
discussed further here, except for the following points:
If you require exact storage and calculations (such as for monetary amounts), use the
NUMBER type instead.
If you want to do complicated calculations with these types for anything important,
especially if you rely on certain behavior in boundary cases (infinity, underflow), you
should evaluate the implementation carefully.
On most platforms, the REAL type has a range of at least 1E-37 to 1E+37 with a precision
of at least 6 decimal digits. The DOUBLE PRECISION type typically has a range of
around 1E-307 to 1E+308 with a precision of at least 15 digits. Values that are too large
or too small will cause an error. Rounding may take place if the precision of an input
number is too high. Numbers too close to zero that are not representable as distinct from
zero will cause an underflow error.
Advanced Server also supports the SQL standard notations FLOAT and FLOAT(p) for
specifying inexact numeric types. Here, p specifies the minimum acceptable precision in
binary digits. Advanced Server accepts FLOAT(1) to FLOAT(24) as selecting the REAL
type, while FLOAT(25) to FLOAT(53) as selecting DOUBLE PRECISION. Values of p
outside the allowed range draw an error. FLOAT with no precision specified is taken to
mean DOUBLE PRECISION.
The following table lists the general-purpose character types available in Advanced
Server.
Where n is a positive integer; these types can store strings up to n characters in length.
An attempt to assign a value that exceeds the length of n will result in an error, unless the
excess characters are all spaces, in which case the string will be truncated to the
maximum length.
CHAR
If you do not specify a value for n, n will default to 1. If the string to be assigned is
shorter than n, values of type CHAR will be space-padded to the specified width (n), and
will be stored and displayed that way.
If you explicitly cast an over-length value to a CHAR(n) type, the value will be truncated
to n characters without raising an error (as specified by the SQL standard).
If you explicitly cast a value to a VARCHAR type, an over-length value will be truncated to
n characters without raising an error (as specified by the SQL standard).
CLOB
You can store a large character string in a CLOB type. CLOB is semantically equivalent to
VARCHAR2 except no length limit is specified. Generally, you should use a CLOB type if
the maximum string length is not known.
The longest possible character string that can be stored in a CLOB type is about 1 GB.
The storage requirement for data of these types is the actual string plus 1 byte if the string
is less than 127 bytes, or 4 bytes if the string is 127 bytes or greater. In the case of
CHAR, the padding also requires storage. Long strings are compressed by the system
automatically, so the physical requirement on disk may be less. Long values are stored in
background tables so they do not interfere with rapid access to the shorter column values.
The database character set determines the character set used to store textual values.
A binary string is a sequence of octets (or bytes). Binary strings are distinguished from
characters strings by two characteristics: First, binary strings specifically allow storing
octets of value zero and other "non-printable" octets (defined as octets outside the range
32 to 126). Second, operations on binary strings process the actual bytes, whereas the
encoding and processing of character strings depends on locale settings.
The following discussion of the date/time types assumes that the configuration parameter,
edb_redwood_date, has been set to TRUE whenever a table is created or altered.
Advanced Server supports the date/time types shown in the following table.
When DATE appears as the data type of a column in the data definition language (DDL)
commands, CREATE TABLE or ALTER TABLE, it is translated to TIMESTAMP(0) at the
time the table definition is stored in the database. Thus, a time component will also be
stored in the column along with the date.
When DATE appears as a data type of a variable in an SPL declaration section, or the data
type of a formal parameter in an SPL procedure or an SPL function, or the return type of
an SPL function, it is always translated to TIMESTAMP(0) and thus can handle a time
component if present.
TIMESTAMP (p) WITH TIME ZONE is similar to TIMESTAMP (p), but includes the
time zone as well.
INTERVAL values specify a period of time. Values of INTERVAL type are composed of
fields that describe the value of the data. The following table lists the fields allowed in an
INTERVAL type:
The fields must be presented in descending order from YEARS to MONTHS, and from
DAYS to HOURS, MINUTES and then SECONDS.
Advanced Server supports two INTERVAL types compatible with Oracle databases.
The second variation supported by Advanced Server that is compatible with Oracle
databases is INTERVAL YEAR TO MONTH. This variation stores a time interval in years
and months.
as 25 years.
Any date or time literal input needs to be enclosed in single quotes, like text strings. The
following SQL standard syntax is also accepted:
type 'value'
2.2.4.2.1 Dates
The date values can be assigned to a DATE or TIMESTAMP column or variable. The hour,
minute, and seconds fields will be set to zero if the date value is not appended with a time
value.
2.2.4.2.2 Times
Some examples of the time component of a date or time stamp are shown in the following
table.
Valid input for time stamps consists of a concatenation of a date and a time. The date
portion of the time stamp can be formatted according to any of the examples shown in
Table 2-7. The time portion of the time stamp can be formatted according to any of
examples shown in Table 2-8.
The following is an example of a time stamp which follows the Oracle default format.
08-JAN-99 04:05:06
The following is an example of a time stamp which follows the ISO 8601 standard.
1999-01-08 04:05:06
The following table shows examples of the output formats for the two styles, Redwood
and ISO 8601.
2.2.4.4 Internals
Advanced Server uses Julian dates for all date/time calculations. Julian dates correctly
predict or calculate any date after 4713 BC based on the assumption that the length of the
year is 365.2425 days.
Advanced Server provides the standard SQL type BOOLEAN. BOOLEAN can have one of
only two states: TRUE or FALSE. A third state, UNKNOWN, is represented by the SQL NULL
value.
The valid literal value for representing the true state is TRUE. The valid literal for
representing the false state is FALSE.
The XMLTYPE data type is used to store XML data. Its advantage over storing XML data
in a character field is that it checks the input values for well-formedness, and there are
support functions to perform type-safe operations on it.
The XML type can store well-formed documents, as defined by the XML standard, as
well as content fragments, which are defined by the production XMLDecl? content
in the XML standard. Roughly, this means that content fragments can have more than one
top-level element or character node.
Note: Oracle does not support the storage of content fragments in XMLTYPE columns.
The following example shows the creation and insertion of a row into a table with an
XMLTYPE column.
content
----------------------------------------------------------
<book><title>Manual</title><chapter>...</chapter></book>
(1 row)
Advanced Server supports other commands that are not listed here. These
commands may have no Oracle equivalent or they may provide the similar or
same functionality as an Oracle SQL command, but with different syntax.
The SQL commands in this section do not necessarily represent the full syntax,
options, and functionality available for each command. In most cases, syntax,
options, and functionality that are not compatible with Oracle databases have been
omitted from the command description and syntax.
The Advanced Server documentation set documents command functionality that
may not be compatible with Oracle databases.
Name
Synopsis
Advanced Server supports two variations of the ALTER INDEX command compatible with
Oracle databases. Use the first variation to rename an index:
Use the second variation of the ALTER INDEX command to rebuild an index:
Description
ALTER INDEX changes the definition of an existing index. The RENAME clause changes
the name of the index. The REBUILD clause reconstructs an index, replacing the old copy
of the index with an updated version based on the index's table.
The REBUILD clause invokes the PostgreSQL REINDEX command; for more information
about using the REBUILD clause, see the PostgreSQL core documentation at:
https://www.postgresql.org/docs/10/static/sql-reindex.html
Parameters
name
new_name
See Also
Name
ALTER PROCEDURE
Synopsis
Description
Parameters
procedure_name
Specify SECURITY DEFINER to instruct the server to execute the procedure with
the privileges of the user that created the procedure. The EXTERNAL keyword is
accepted for compatibility, but ignored.
Specify SECURITY INVOKER to instruct the server to execute the procedure with
the privileges of the user that is invoking the procedure. The EXTERNAL keyword
is accepted for compatibility, but ignored.
Examples
The following command specifies that the update_balance procedure should execute
with the privileges of the user invoking the procedure:
Name
Synopsis
Description
Use the ALTER PROFILE command to modify a user-defined profile; Advanced Server
supports two forms of the command:
Include the LIMIT clause and one or more space-delimited parameter/value pairs to
specify the rules enforced by Advanced Server, or use ALTER PROFILERENAME TO to
change the name of a profile.
Parameters
profile_name
new_name
parameter
value
Advanced Server supports the value shown below for each parameter:
PASSWORD_LOCK_TIME specifies the length of time that must pass before the server
unlocks an account that has been locked because of FAILED_LOGIN_ATTEMPTS.
Supported values are:
PASSWORD_LIFE_TIME specifies the number of days that the current password may
be used before the user is prompted to provide a new password. Include the
PASSWORD_GRACE_TIME clause when using the PASSWORD_LIFE_TIME clause to
specify the number of days that will pass after the password expires before
connections by the role are rejected. If PASSWORD_GRACE_TIME is not specified, the
password will expire on the day specified by the default value of
PASSWORD_GRACE_TIME, and the user will not be allowed to execute any command
until a new password is provided. Supported values are:
PASSWORD_REUSE_TIME specifies the number of days a user must wait before re-
using a password. The PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX
parameters are intended to be used together. If you specify a finite value for one of
these parameters while the other is UNLIMITED, old passwords can never be reused.
If both parameters are set to UNLIMITED there are no restrictions on password reuse.
Supported values are:
Examples
acctg_profile will count failed connection attempts when a login role attempts to
connect to the server. The profile specifies that if a user has not authenticated with the
correct password in three attempts, the account will be locked for one day.
Advanced Server includes extra syntax (not offered by Oracle) with the ALTER QUEUE
SQL command. This syntax can be used in association with the DBMS_AQADM package.
Name
Synopsis
This command is available in four forms. The first form of this command changes the
name of a queue.
Parameters
queue_name
RENAME TO
Include the RENAME TO clause and a new name for the queue to rename
the queue.
new_name
The second form of the ALTER QUEUE command modifies the attributes of the queue:
Parameters
queue_name
option_name option_value
The name of the option or options to be associated with the new queue and
the corresponding value of the option. If you provide duplicate option
names, the server will return an error.
Use the third form of the ALTER QUEUE command to enable or disable enqueuing and/or
dequeuing on a particular queue:
Parameters
queue_name
ACCESS
START | STOP
Use the START and STOP keywords to indicate the desired state of the
queue.
FOR enqueue|dequeue
Use the FOR clause to indicate if you are specifying the state of
enqueueing or dequeueing activity on the specified queue.
NOWAIT
Use the fourth form to ADD or DROP callback details for a particular queue.
Parameters
queue_name
ADD | DROP
location_name
callback_option
Example
The following example modifies a queue named work_order, setting the number of
retries to 100, the delay between retries to 2 seconds, and the length of time that the
queue will retain dequeued messages to 10 seconds:
See Also
Advanced Server includes extra syntax (not offered by Oracle) with the ALTER QUEUE
SQL command. This syntax can be used in association with the DBMS_AQADM package.
Name
Synopsis
Use ALTER QUEUE TABLE to change the name of an existing queue table:
Description
Parameters
name
new_name
Example
See Also
Name
Synopsis
Description
A role without the CREATEROLE privilege may use this command to change their own
password. An unprivileged role must include the REPLACE clause and their previous
password if PASSWORD_VERIFY_FUNCTION is not NULL in their profile. When the
REPLACE clause is used by a non-superuser, the server will compare the password
provided to the existing password and raise an error if the passwords do not match.
A database superuser can use this command to change the password associated with any
role. If a superuser includes the REPLACE clause, the clause is ignored; a non-matching
value for the previous password will not throw an error.
If the role for which the password is being changed has the SUPERUSER attribute, then a
superuser must issue this command. A role with the CREATEROLE attribute can use this
command to change the password associated with a role that is not a superuser.
Parameters
role_name
password
prev_password
Examples
Advanced Server includes extra syntax (not offered by Oracle) for the ALTER ROLE
command. This syntax can be useful when assigning privileges related to creating and
dropping database links compatible with Oracle databases, and fine-grained access
control (using DBMS_RLS).
A user who holds the CREATE DATABASE LINK privilege may create a private database
link. The following ALTER ROLE command grants privileges to an Advanced Server role
that allow the specified role to create a private database link:
A user who holds the CREATE PUBLIC DATABASE LINK privilege may create a public
database link. The following ALTER ROLE command grants privileges to an Advanced
Server role that allow the specified role to create a public database link:
A user who holds the DROP PUBLIC DATABASE LINK privilege may drop a public
database link. The following ALTER ROLE command grants privileges to an Advanced
Server role that allow the specified role to drop a public database link:
A user who holds the EXEMPT ACCESS POLICY privilege is exempt from fine-grained
access control (DBMS_RLS) policies. A user who holds these privileges will be able to
view or modify any row in a table constrained by a DBMS_RLS policy. The following
ALTER ROLE command grants privileges to an Advanced Server role that exempt the
specified role from any defined DBMS_RLS policies:
See Also
Name
Synopsis
Description
Parameters
name
increment
minvalue
maxvalue
The optional clause MAXVALUE maxvalue determines the maximum value for
the sequence. If not specified, the current maximum value will be maintained.
Note that the key words, NO MAXVALUE, may be used to set this behavior back to
cache
The optional clause CACHE cache specifies how many sequence numbers are to
be preallocated and stored in memory for faster access. The minimum value is 1
(only one value can be generated at a time, i.e., NOCACHE). If unspecified, the old
cache value will be maintained.
CYCLE
The CYCLE option allows the sequence to wrap around when the maxvalue or
minvalue has been reached by an ascending or descending sequence
respectively. If the limit is reached, the next number generated will be the
minvalue or maxvalue, respectively. If not specified, the old cycle behavior
will be maintained. Note that the key words, NO CYCLE, may be used to alter the
sequence so that it does not recycle, however, this term is not compatible with
Oracle databases.
Notes
To avoid blocking of concurrent transactions that obtain numbers from the same
sequence, ALTER SEQUENCE is never rolled back; the changes take effect immediately
and are not reversible.
ALTER SEQUENCE will not immediately affect NEXTVAL results in backends, other than
the current one, that have pre-allocated (cached) sequence values. They will use up all
cached values prior to noticing the changed sequence parameters. The current backend
will be affected immediately.
Examples
See Also
Name
Synopsis
Description
Parameters
name
value
Configuration Parameters
The following configuration parameters can be modified using the ALTER SESSION
command:
NLS_DATE_FORMAT (string)
Sets the display format for date and time values as well as the rules for
interpreting ambiguous date input values. Has the same effect as setting the
Advanced Server datestyle runtime configuration parameter.
NLS_LANGUAGE (string)
Sets the language in which messages are displayed. Has the same effect as setting
the Advanced Server lc_messages runtime configuration parameter.
Valid values are BYTE and CHAR. The default is BYTE. This parameter is provided
for syntax compatibility only and has no effect in the Advanced Server.
OPTIMIZER_MODE (string)
Sets the default optimization mode for queries. Valid values are ALL_ROWS,
CHOOSE, FIRST_ROWS, FIRST_ROWS_10, FIRST_ROWS_100, and
FIRST_ROWS_1000. The default is CHOOSE. This parameter is implemented in
Advanced Server.
QUERY_REWRITE_ENABLED (string)
Valid values are TRUE, FALSE, and FORCE. The default is FALSE. This parameter
is provided for syntax compatibility only and has no effect in Advanced Server.
QUERY_REWRITE_INTEGRITY (string)
Examples
Set the language to U.S. English in UTF-8 encoding. Note that in this example, the value,
en_US.UTF-8, is in the format that must be specified for Advanced Server. This form is
not compatible with Oracle databases.
Name
Synopsis
Description
ALTER TABLE changes the definition of an existing table. There are several subforms:
This form adds a new column to the table using the same syntax as CREATE
TABLE.
DROP COLUMN
This form drops a column from a table. Indexes and table constraints involving
the column will be automatically dropped as well.
ADD table_constraint
This form adds a new constraint to a table using the same syntax as CREATE
TABLE.
This form drops constraints on a table. Currently, constraints on tables are not
required to have unique names, so there may be more than one constraint
matching the specified name. All matching constraints will be dropped.
RENAME
The RENAME forms change the name of a table (or an index, sequence, or view) or
the name of an individual column in a table. There is no effect on the stored data.
Parameters
name
column
new_column
new_name
type
table_constraint
constraint_name
CASCADE
When you invoke ADD COLUMN, all existing rows in the table are initialized with the
columns default value (null if no DEFAULT clause is specified). Adding a column with a
non-null default will require the entire table to be rewritten. This may take a significant
amount of time for a large table; and it will temporarily require double the disk space.
Adding a CHECK or NOT NULL constraint requires scanning the table to verify that
existing rows meet the constraint.
The DROP COLUMN form does not physically remove the column, but simply makes it
invisible to SQL operations. Subsequent insert and update operations in the table will
store a null value for the column. Thus, dropping a column is quick but it will not
immediately reduce the on-disk size of your table, as the space occupied by the dropped
column is not reclaimed. The space will be reclaimed over time as existing rows are
updated.
Changing any part of a system catalog table is not permitted. Refer to CREATE TABLE
for a further description of valid parameters.
Examples
ALTER TABLE emp ADD CONSTRAINT sal_chk CHECK (sal > 500);
See Also
Name
Synopsis
Description
Parameters
name
newname
The new name of the tablespace. The new name cannot begin with pg_, as such
names are reserved for system tablespaces.
Examples
See Also
DROP TABLESPACE
Name
Synopsis
Description
A role without the CREATEROLE privilege may use this command to change their own
password. An unprivileged role must include the REPLACE clause and their previous
password if PASSWORD_VERIFY_FUNCTION is not NULL in their profile. When the
REPLACE clause is used by a non-superuser, the server will compare the password
provided to the existing password and raise an error if the passwords do not match.
A database superuser can use this command to change the password associated with any
role. If a superuser includes the REPLACE clause, the clause is ignored; a non-matching
value for the previous password will not throw an error.
If the role for which the password is being changed has the SUPERUSER attribute, then a
superuser must issue this command. A role with the CREATEROLE attribute can use this
command to change the password associated with a role that is not a superuser.
Parameters
role_name
password
prev_password
Examples
See Also
Name
ALTER USER|ROLE
Synopsis
PROFILE profile_name
| ACCOUNT {LOCK|UNLOCK}
| PASSWORD EXPIRE [AT 'timestamp']
For information about the administrative clauses of the ALTER USER or ALTER ROLE
command that are supported by Advanced Server, please see the PostgreSQL core
documentation available at:
https://www.postgresql.org/docs/10/static/sql-commands.html
Only a database superuser can use the ALTER USER|ROLE clauses that enforce profile
management. The clauses enforce the following behaviors:
Include the ACCOUNT clause and the LOCK or UNLOCK keyword to specify that the
user account should be placed in a locked or unlocked state.
Include the LOCK TIME 'timestamp' clause and a date/time value to lock the
role at the specified time, and unlock the role at the time indicated by the
PASSWORD_LOCK_TIME parameter of the profile assigned to this role. If LOCK
TIME is used with the ACCOUNT LOCK clause, the role can only be unlocked by a
database superuser with the ACCOUNT UNLOCK clause.
Each login role may only have one profile. To discover the profile that is currently
associated with a login role, query the profile column of the DBA_USERS view.
Parameters
name
The name of the role with which the specified profile will be associated.
password
profile_name
The name of the profile that will be associated with the role.
timestamp
The date and time at which the clause will be enforced. When specifying a value
for timestamp, enclose the value in single-quotes.
Notes
For information about the Postgres-compatible clauses of the ALTER USER or ALTER
ROLE command, see the PostgreSQL core documentation available at:
https://www.postgresql.org/docs/10/static/sql-alterrole.html
Examples
The following command uses the ALTER USER PROFILE command to associate a
profile named acctg with a user named john:
2.3.14 CALL
Name
CALL
Synopsis
Description
Use the CALL statement to invoke a procedure. To use the CALL statement, you must
have EXECUTE privileges on the procedure that the CALL statement is invoking.
Parameters
procedure_name
argument_list
Examples
The CALL statement may take one of several forms, depending on the arguments required
by the procedure:
CALL update_balance();
CALL update_balance(1,2,3);
2.3.15 COMMENT
Name
Synopsis
COMMENT ON
{
TABLE table_name |
COLUMN table_name.column_name
} IS 'text'
Description
COMMENT stores a comment about a database object. To modify a comment, issue a new
COMMENT command for the same object. Only one comment string is stored for each
object. To remove a comment, specify the empty string (two consecutive single quotes
with no intervening space) for text. Comments are automatically dropped when the
object is dropped.
Parameters
table_name
The name of the table to be commented. The table name may be schema-
qualified.
table_name.column_name
text
Notes
2.3.16 COMMIT
Name
Synopsis
COMMIT [ WORK ]
Description
COMMIT commits the current transaction. All changes made by the transaction become
visible to others and are guaranteed to be durable if a crash occurs.
Parameters
WORK
Notes
Use ROLLBACK to abort a transaction. Issuing COMMIT when not inside a transaction
does no harm.
Examples
COMMIT;
See Also
Name
Synopsis
Description
To create a database, you must be a superuser or have the special CREATEDB privilege.
Normally, the creator becomes the owner of the new database. Non-superusers with
CREATEDB privilege can only create databases owned by them.
The new database will be created by cloning the standard system database template1.
Parameters
name
Notes
Errors along the line of could not initialize database directory are most likely related to
insufficient permissions on the data directory, a full disk, or other file system problems.
Examples
Name
Synopsis
Description
CREATE DATABASE LINK creates a new database link. A database link is an object that
allows a reference to a table or view in a remote database within a DELETE, INSERT,
SELECT or UPDATE command. A database link is referenced by appending @dblink to
the table or view name referenced in the SQL command where dblink is the name of
the database link.
Note: It is suggested in the USING clause that the foreign data wrapper postgres_fdw
be used instead of libpq. The libpq option may be deprecated in a future Advanced
Server release.
Database links can be public or private. A public database link is one that can be used by
any user. A private database link can be used only by the database links owner.
Specification of the PUBLIC option creates a public database link. If omitted, a private
database link is created.
When the CREATE DATABASE LINK command is given, the database link name and the
given connection attributes are stored in the Advanced Server system table named,
pg_catalog.edb_dblink. When using a given database link, the database containing
the edb_dblink entry defining this database link is called the local database. The server
and database whose connection attributes are defined within the edb_dblink entry is
called the remote database
For information about high availability, load balancing, and replication for Postgres
database servers, see the PostgreSQL core documentation available at:
https://www.postgresql.org/docs/10/static/high-availability.html
Note: For Advanced Server 10, the CREATE DATABASE LINK command is tested against
and certified for use with Oracle version 10g Release 2 (10.2), Oracle version 11g
Release 2 (11.2), and Oracle version 12c Release 1 (12.1).
Parameters
PUBLIC
Create a public database link that can be used by any user. If omitted, then the
database link is private and can only be used by the database links owner.
name
username
CURRENT_USER
Include CURRENT_USER to specify that Advanced Server should use the user
mapping associated with the role that is using the link when establishing a
connection to the remote server.
password
libpq
postgres_fdw
https://www.postgresql.org/docs/10/static/sql-createextension.html
fdw_connection_string
Specify the connection information for the postgres_fdw foreign data wrapper.
The connection format is the same as libpq_connection_string.
oci
oracle_connection_string
Notes
To create a non-public database link you must have the CREATE DATABASE LINK
privilege. To create a public database link you must have the CREATE PUBLIC
DATABASE LINK privilege.
If you are executing a SQL command that references a database link to a remote Oracle
database, Advanced Server needs a way to know where the correct Oracle installation
resides on disk. Set the LD_LIBRARY_PATH environment variable on Linux (or PATH on
Windows) to the lib directory of the Oracle client installation directory.
For Windows only, you can instead set the value of the oracle_home configuration
parameter in the postgresql.conf file. The value specified in the oracle_home
configuration parameter will override the Windows PATH environment variable.
Substitute the name of the Windows directory that contains oci.dll for
lib_directory.
After setting the oracle_home configuration parameter, you must restart the server for
the changes to take effect. Restart the server from the Windows Services console.
Examples
The following example demonstrates using the CREATE DATABASE LINK command to
create a database link (named chicago) that connects an instance of Advanced Server to
an Oracle server via an oci-dblink connection. The connection information tells
Advanced Server to log in to Oracle as user admin, whose password is mypassword.
Including the oci option tells Advanced Server that this is an oci-dblink connection; the
connection string, '//127.0.0.1/acctg' specifies the server address and name of the
database.
Note: You can specify a hostname in the connection string (in place of an IP address).
The following example demonstrates using the CREATE DATABASE LINK command to
create a database link (named boston) that connects an instance of Advanced Server to a
Postgres Server via a libpq connection. The connection information tells Advanced
Server to log in to Postgres as user admin, whose password is mypassword. Including
the libpq option tells Advanced Server that this is a libpq connection; the connection
string, 'host=127.0.0.1 dbname=sales' specifies the server address and name of
the database.
The following example demonstrates using the CREATE DATABASE LINK command to
create a database link (named bedford) that connects an instance of Advanced Server to
another Advanced Server instance via a postgres_fdw foreign data wrapper
connection. The connection information tells Advanced Server to log in as user admin,
whose password is mypassword. Including the postgres_fdw option tells Advanced
Server that this is a postgres_fdw connection; the connection string, 'host=127.0.0.1
port=5444 dbname=marketing' specifies the server address and name of the
database.
Note: You can specify a hostname in the connection string (in place of an IP address).
The following examples demonstrate using a database link with Advanced Server to
connect to an Oracle database. The examples assume that a copy of the Advanced Server
sample applications emp table has been created in an Oracle database and a second
Advanced Server database cluster with the sample application is accepting connections at
port 5443.
Create a public database link named, oralink, to an Oracle database named, xe, located
at 127.0.0.1 on port 1521. Connect to the Oracle database with username, edb, and
password, password.
Issue a SELECT command on the emp table in the Oracle database using database link,
oralink.
Create a private database link named, edblink, to the Advanced Server database named,
edb, located on localhost, running on port 5443. Connect to the Advanced Server
database with username, enterprisedb, and password, password.
Display attributes of database links, oralink and edblink, from the local
edb_dblink system table:
Perform a join of the emp table from the Oracle database with the dept table from the
Advanced Server database:
The same query can be made with the Oracle database and an Advanced Server database
using the postgres_fdw foreign data wrapper to create the Advanced Server database
link.
Create a private database link named, fdwlink, to the Advanced Server database named,
edb, located on host 192.168.2.22 running on port 5444. Connect to the Advanced
Server database with username, enterprisedb, and password, password.
Display attributes of database links, oralink and fdwlink, from the local
edb_dblink system table:
Perform a join of the emp table from the Oracle database with the dept table from the
Advanced Server database:
When the oci-dblink is used to execute SQL statements on a remote Oracle database,
there are certain circumstances where pushdown of the processing occurs on the foreign
server.
Pushdown refers to the occurrence of processing on the foreign (that is, the remote)
server instead of the local client where the SQL statement was issued. Pushdown can
result in performance improvement since the data is processed on the remote server
before being returned to the local client.
Pushdown applies to statements with the standard SQL join operations (inner join, left
outer join, right outer join, and full outer join). Pushdown still occurs even when a sort is
specified on the resulting data set.
For information about the EXPLAIN command, please see the PostgreSQL Core
documentation at:
https://www.postgresql.org/docs/10/static/sql-explain.html
The following examples use the database link created as shown by the following:
QUERY PLAN
--------------------------------------------------------------------------------
Foreign Scan
Output: d.deptno, d.dname, e.empno, e.ename
Relations: (_dblink_dept_1 d) INNER JOIN (_dblink_emp_2 e)
Remote Query: SELECT r1.deptno, r1.dname, r2.empno, r2.ename FROM (dept r1 INNER
JOIN emp r2 ON ((r1.deptno = r2.deptno))) ORDER BY r1.deptno ASC NULLS LAST, r2.empno
ASC NULLS LAST
(4 rows)
Note that the INNER JOIN operation occurs under the Foreign Scan section. The output
of this join is the following:
deptno | dname | empno | ename
--------+------------+-------+--------
10 | ACCOUNTING | 7782 | CLARK
10 | ACCOUNTING | 7839 | KING
10 | ACCOUNTING | 7934 | MILLER
20 | RESEARCH | 7369 | SMITH
20 | RESEARCH | 7566 | JONES
20 | RESEARCH | 7788 | SCOTT
20 | RESEARCH | 7876 | ADAMS
20 | RESEARCH | 7902 | FORD
30 | SALES | 7499 | ALLEN
30 | SALES | 7521 | WARD
30 | SALES | 7654 | MARTIN
30 | SALES | 7698 | BLAKE
30 | SALES | 7844 | TURNER
30 | SALES | 7900 | JAMES
(14 rows)
QUERY PLAN
--------------------------------------------------------------------------------
Foreign Scan
Output: d.deptno, d.dname, e.empno, e.ename
Relations: (_dblink_dept_1 d) LEFT JOIN (_dblink_emp_2 e)
Remote Query: SELECT r1.deptno, r1.dname, r2.empno, r2.ename FROM (dept r1 LEFT JOIN
emp r2 ON ((r1.deptno = r2.deptno))) ORDER BY r1.deptno ASC NULLS LAST, r2.empno ASC
NULLS LAST
(4 rows)
The following example shows a case where the entire processing is not pushed down
because the emp joined table resides locally instead of on the same foreign server.
QUERY PLAN
------------------------------------------------------------------
Sort
Output: d.deptno, d.dname, e.empno, e.ename
Sort Key: d.deptno, e.empno
-> Hash Left Join
Output: d.deptno, d.dname, e.empno, e.ename
Hash Cond: (d.deptno = e.deptno)
-> Foreign Scan on _dblink_dept_1 d
Output: d.deptno, d.dname, d.loc
Remote Query: SELECT deptno, dname, NULL FROM dept
-> Hash
Output: e.empno, e.ename, e.deptno
-> Seq Scan on public.emp e
Output: e.empno, e.ename, e.deptno
(13 rows)
The output of this join is the same as the previous left outer join example.
Note: The procedure described in this section is not compatible with Oracle databases.
This technique can be used for either an oci-dblink connection for remote Oracle access,
or a libpq or postgres_fdw connection for remote Postgres access.
The following example shows the creation of a foreign table to access a remote Oracle
table.
First, create a database link as previously described. The following is the creation of a
database link named oralink for connecting to the Oracle database.
When you create the database link, Advanced Server creates a corresponding foreign
server. The following query displays the foreign server:
SELECT srvname, srvowner, srvfdw, srvtype, srvoptions FROM pg_foreign_server;
For more information about foreign servers, please see the CREATE SERVER command in
the PostgreSQL Core documentation at:
https://www.postgresql.org/docs/10/static/sql-createserver.html
The name specified in the SERVER clause at the end of the CREATE FOREIGN
TABLE command is the name of the foreign server, which is oralink in this
example as displayed in the srvname column from the query on
pg_foreign_server.
The table name and schema name are specified in the OPTIONS clause by the
table and schema options.
The column names specified in the CREATE FOREIGN TABLE command must
match the column names in the remote table.
Generally, CONSTRAINT clauses may not be accepted or enforced on the foreign
table as they are assumed to have been defined on the remote table.
For more information about the CREATE FOREIGN TABLE command, please see the
PostgreSQL Core documentation at:
https://www.postgresql.org/docs/10/static/sql-createforeigntable.html
In contrast, the following is a query on the same remote table, but using the database link
instead of the foreign table:
SELECT * FROM emp@oralink;
See Also
Name
Synopsis
Description
The CREATE DIRECTORY command creates an alias for a file system directory
pathname. You must be a database superuser to use this command.
When the alias is specified as the appropriate parameter to the programs of the
UTL_FILE package, the operating system files are created in, or accessed from the
directory corresponding to the given alias.
Parameters
name
pathname
The fully-qualified directory path represented by the alias name. The CREATE
DIRECTORY command does not create the operating system directory. The
physical directory must be created independently using the appropriate operating
system commands.
Notes
The operating system user id, enterprisedb, must have the appropriate read and/or
write privileges on the directory if the UTL_FILE package is to be used to create and/or
read files using the directory.
The directory alias is stored in the pg_catalog.edb_dir system catalog table. Note
that edb_dir is not a table compatible with Oracle databases.
The directory alias can also be viewed from the Oracle catalog views
SYS.ALL_DIRECTORIES and SYS.DBA_DIRECTORIES, which are compatible with
Oracle databases.
In a Windows system, the directory name separator can be specified as a forward slash
(/) or two consecutive backslashes (\\).
Examples
View the directory aliases using a view compatible with Oracle databases:
See Also
DROP DIRECTORY
Name
Synopsis
Description
If a schema name is included, then the function is created in the specified schema.
Otherwise it is created in the current schema. The name of the new function must not
match any existing function with the same argument types in the same schema. However,
functions of different input argument types may share a name (this is called overloading).
(Overloading of functions is an Advanced Server feature - overloading of stored
functions is not compatible with Oracle databases.)
The user that creates the function becomes the owner of the function.
Parameters
name
name is the identifier of the function. If you specify the [OR REPLACE] clause
and a function with the same name already exists in the schema, the new function
will replace the existing one. If you do not specify [OR REPLACE], the new
function will not replace the existing function with the same name in the same
schema.
parameters
data_type
data_type is the data type of the value returned by the functions RETURN
statement.
declarations
statements
statements are SPL program statements (the BEGIN - END block may contain
an EXCEPTION section).
IMMUTABLE
STABLE
VOLATILE
These attributes inform the query optimizer about the behavior of the function;
you can specify only one choice. VOLATILE is the default behavior.
STABLE indicates that the function cannot modify the database, and that within a
single table scan, it will consistently return the same result for the same argument
values, but that its result could change across SQL statements. This is the
appropriate selection for function that depend on database lookups, parameter
variables (such as the current time zone), etc.
VOLATILE indicates that the function value can change even within a single table
scan, so no optimizations can be made. Please note that any function that has
side-effects must be classified volatile, even if its result is quite predictable, to
prevent calls from being optimized away.
DETERMINISTIC
[ NOT ] LEAKPROOF
A LEAKPROOK function has no side effects, and reveals no information about the
values used to call the function.
CALLED ON NULL INPUT (the default) indicates that the procedure will be called
normally when some of its arguments are NULL. It is the author's responsibility to
check for NULL values if necessary and respond appropriately.
RETURNS NULL ON NULL INPUT or STRICT indicates that the procedure always
returns NULL whenever any of its arguments are NULL. If these clauses are
specified, the procedure is not executed when there are NULL arguments; instead a
NULL result is assumed automatically.
The SECURITY INVOKER clause indicates that the function will execute with the
privileges of the user that calls it. The key word EXTERNAL is allowed for SQL
conformance, but is optional.
AUTHID DEFINER
AUTHID CURRENT_USER
The PARALLEL clause enables the use of parallel sequential scans (parallel mode).
A parallel sequential scan uses multiple workers to scan a relation in parallel
during a query in contrast to a serial sequential scan.
When set to UNSAFE, the function cannot be executed in parallel mode. The
presence of such a function in a SQL statement forces a serial execution plan.
This is the default setting if the PARALLEL clause is omitted.
When set to RESTRICTED, the function can be executed in parallel mode, but the
execution is restricted to the parallel group leader. If the qualification for any
particular relation has anything that is parallel restricted, that relation won't be
chosen for parallelism.
When set to SAFE, the function can be executed in parallel mode with no
restriction.
COST execution_cost
result_rows is a positive number giving the estimated number of rows that the
planner should expect the function to return. This is only allowed when the
function is declared to return a set. The default assumption is 1000 rows.
The SET clause causes the specified configuration parameter to be set to the
specified value when the function is entered, and then restored to its prior value
when the function exits. SET FROM CURRENT saves the session's current value of
the parameter as the value to be applied when the function is entered.
Please Note: The STRICT, LEAKPROOF, PARALLEL, COST, ROWS and SET keywords
provide extended functionality for Advanced Server and are not supported by Oracle.
Notes
Advanced Server allows function overloading; that is, the same name can be used for
several different functions so long as they have distinct input (IN, IN OUT) argument
data types.
Examples
The function emp_comp takes two numbers as input and returns a computed value. The
SELECT command illustrates use of the function.
Function sal_range returns a count of the number of employees whose salary falls in
the specified range. The following anonymous block calls the function a number of times
using the arguments default values for the first two calls.
BEGIN
DBMS_OUTPUT.PUT_LINE('Number of employees with a salary: ' ||
sal_range);
DBMS_OUTPUT.PUT_LINE('Number of employees with a salary of at least '
|| '$2000.00: ' || sal_range(2000.00));
DBMS_OUTPUT.PUT_LINE('Number of employees with a salary between '
|| '$2000.00 and $3000.00: ' || sal_range(2000.00, 3000.00));
END;
The following example demonstrates using the AUTHID CURRENT_USER clause and
STRICT keyword in a function declaration:
Include the STRICT keyword to instruct the server to return NULL if any input parameter
passed is NULL; if a NULL value is passed, the function will not execute.
Pragmas
PRAGMA RESTRICT_REFERENCE
Name
Synopsis
Description
CREATE INDEX constructs an index, name, on the specified table. Indexes are primarily
used to enhance database performance (though inappropriate use will result in slower
performance).
The key field(s) for the index are specified as column names, or alternatively as
expressions written in parentheses. Multiple fields can be specified to create multicolumn
indexes.
An index field can be an expression computed from the values of one or more columns of
the table row. This feature can be used to obtain fast access to data based on some
transformation of the basic data. For example, an index computed on UPPER(col)
would allow the clause WHERE UPPER(col) = 'JIM' to use an index.
Advanced Server provides the B-tree index method. The B-tree index method is an
implementation of Lehman-Yao high-concurrency B-trees.
All functions and operators used in an index definition must be "immutable", that is, their
results must depend only on their arguments and never on any outside influence (such as
the contents of another table or the current time). This restriction ensures that the
behavior of the index is well-defined. To use a user-defined function in an index
expression remember to mark the function immutable when you create it.
Parameters
UNIQUE
name
The name of the index to be created. No schema name can be included here; the
index is always created in the same schema as its parent table.
table
column
expression
An expression based on one or more columns of the table. The expression usually
must be written with surrounding parentheses, as shown in the syntax. However,
the parentheses may be omitted if the expression has the form of a function call.
tablespace
Notes
Examples
To create the same index as above, but have it reside in the index_tblspc tablespace:
See Also
Name
Synopsis
Description
CREATE MATERIALIZED VIEW defines a view of a query that is not updated each time
the view is referenced in a query. By default, the view is populated when the view is
created; you can include the BUILD DEFERRED keywords to delay the population of the
view.
Parameters
name
subquery
A SELECT statement that specifies the contents of the view. Refer to SELECT for
more information about valid queries.
BUILD DEFERRED instructs the server to populate the view at a later time
(during a REFRESH operation).
create_mv_refresh
COMPLETE instructs the server to discard the current content and reload
the materialized view by executing the view's defining query when the
materialized view is refreshed.
Notes
Materialized views are read only - the server will not allow an INSERT, UPDATE, or
DELETE on a view.
Access to tables referenced in the view is determined by permissions of the view owner;
the user of a view must have permissions to call all functions used by the view.
For more information about the Postgres REFRESH MATERIALIZED VIEW command,
please see the PostgreSQL Core Documentation available at:
https://www.postgresql.org/docs/10/static/sql-refreshmaterializedview.html
Examples
CREATE MATERIALIZED VIEW dept_30 BUILD IMMEDIATE AS SELECT * FROM emp WHERE
deptno = 30;
Name
Synopsis
Description
If a schema name is included, then the package is created in the specified schema.
Otherwise it is created in the current schema. The name of the new package must not
match any existing package in the same schema unless the intent is to update the
definition of an existing package, in which case use CREATE OR REPLACE PACKAGE.
The user that creates the procedure becomes the owner of the package.
Parameters
name
declaration
proc_name
argname
IN | IN OUT | OUT
argtype
DEFAULT value
func_name
rettype
DETERMINISTIC
Examples
See Also
DROP PACKAGE
Name
Synopsis
Description
Parameters
name
declaration
proc_name
argname
IN | IN OUT | OUT
argtype
DEFAULT value
STRICT
The STRICT keyword specifies that the function will not be executed if called
with a NULL argument; instead the function will return NULL.
LEAKPROOF
The PARALLEL clause enables the use of parallel sequential scans (parallel mode).
A parallel sequential scan uses multiple workers to scan a relation in parallel
during a query in contrast to a serial sequential scan.
When set to SAFE, the procedure or function can be executed in parallel mode
with no restriction.
execution_cost
result_rows
result_rows is the estimated number of rows that the query planner should
expect the function to return. The default is 1000.
SET
Use the SET clause to specify a parameter value for the duration of the function:
FROM CURRENT guarantees that the parameter value is restored when the
function ends.
program_body
func_name
rettype
DETERMINISTIC
Include DETERMINISTIC to specify that the function will always return the same
result when given the same argument values. A DETERMINISTIC function must
not modify the database.
statement
Please Note: The STRICT, LEAKPROOF, PARALLEL, COST, ROWS and SET keywords
provide extended functionality for Advanced Server and are not supported by Oracle.
Examples
The following two anonymous blocks execute the procedure and function in the
empinfo package and display the public variable.
BEGIN
empinfo.get_name(7369);
DBMS_OUTPUT.PUT_LINE('Employee Name : ' || empinfo.emp_name);
DBMS_OUTPUT.PUT_LINE('Number of queries: ' || empinfo.display_counter);
END;
Initialized counter
Employee Name : SMITH
Number of queries: 1
BEGIN
empinfo.get_name(7900);
DBMS_OUTPUT.PUT_LINE('Employee Name : ' || empinfo.emp_name);
DBMS_OUTPUT.PUT_LINE('Number of queries: ' || empinfo.display_counter);
END;
See Also
Name
Synopsis
Description
If a schema name is included, then the procedure is created in the specified schema.
Otherwise it is created in the current schema. The name of the new procedure must not
match any existing procedure in the same schema unless the intent is to update the
definition of an existing procedure, in which case use CREATE OR REPLACE
PROCEDURE.
Parameters
name is the identifier of the procedure. If you specify the [OR REPLACE] clause
and a procedure with the same name already exists in the schema, the new
procedure will replace the existing one. If you do not specify [OR REPLACE],
the new procedure will not replace the existing procedure with the same name in
the same schema.
parameters
declarations
statements
statements are SPL program statements (the BEGIN - END block may contain
an EXCEPTION section).
IMMUTABLE
STABLE
VOLATILE
These attributes inform the query optimizer about the behavior of the procedure;
you can specify only one choice. VOLATILE is the default behavior.
IMMUTABLE indicates that the procedure cannot modify the database and always
reaches the same result when given the same argument values; it does not do
database lookups or otherwise use information not directly present in its argument
list. If you include this clause, any call of the procedure with all-constant
arguments can be immediately replaced with the procedure value.
STABLE indicates that the procedure cannot modify the database, and that within a
single table scan, it will consistently return the same result for the same argument
values, but that its result could change across SQL statements. This is the
appropriate selection for procedures that depend on database lookups, parameter
variables (such as the current time zone), etc.
VOLATILE indicates that the procedure value can change even within a single
table scan, so no optimizations can be made. Please note that any function that
has side-effects must be classified volatile, even if its result is quite predictable, to
prevent calls from being optimized away.
[ NOT ] LEAKPROOF
A LEAKPROOK procedure has no side effects, and reveals no information about the
values used to call the procedure.
CALLED ON NULL INPUT (the default) indicates that the procedure will be called
normally when some of its arguments are NULL. It is the author's responsibility to
check for NULL values if necessary and respond appropriately.
RETURNS NULL ON NULL INPUT or STRICT indicates that the procedure always
returns NULL whenever any of its arguments are NULL. If these clauses are
specified, the procedure is not executed when there are NULL arguments; instead a
NULL result is assumed automatically.
SECURITY DEFINER specifies that the procedure will execute with the privileges
of the user that created it; this is the default. The key word EXTERNAL is allowed
for SQL conformance, but is optional.
The SECURITY INVOKER clause indicates that the procedure will execute with the
privileges of the user that calls it. The key word EXTERNAL is allowed for SQL
conformance, but is optional.
AUTHID DEFINER
AUTHID CURRENT_USER
The PARALLEL clause enables the use of parallel sequential scans (parallel mode).
A parallel sequential scan uses multiple workers to scan a relation in parallel
during a query in contrast to a serial sequential scan.
When set to UNSAFE, the procedure cannot be executed in parallel mode. The
presence of such a procedure forces a serial execution plan. This is the default
setting if the PARALLEL clause is omitted.
When set to RESTRICTED, the procedure can be executed in parallel mode, but
the execution is restricted to the parallel group leader. If the qualification for any
particular relation has anything that is parallel restricted, that relation won't be
chosen for parallelism.
When set to SAFE, the procedure can be executed in parallel mode with no
restriction.
COST execution_cost
ROWS result_rows
result_rows is a positive number giving the estimated number of rows that the
planner should expect the procedure to return. This is only allowed when the
procedure is declared to return a set. The default assumption is 1000 rows.
The SET clause causes the specified configuration parameter to be set to the
specified value when the procedure is entered, and then restored to its prior value
when the procedure exits. SET FROM CURRENT saves the session's current value
of the parameter as the value to be applied when the procedure is entered.
Please Note: The STRICT, LEAKPROOF, PARALLEL, COST, ROWS and SET keywords
provide extended functionality for Advanced Server and are not supported by Oracle.
Examples
EXEC list_emp;
EMPNO ENAME
----- -------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
The following procedure uses IN OUT and OUT arguments to return an employees
number, name, and job based upon a search using first, the given employee number, and
if that is not found, then using the given name. An anonymous block calls the procedure.
DECLARE
v_empno emp.empno%TYPE;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
BEGIN
v_empno := 0;
v_ename := 'CLARK';
emp_job(v_empno, v_ename, v_job);
DBMS_OUTPUT.PUT_LINE('Employee No: ' || v_empno);
DBMS_OUTPUT.PUT_LINE('Name : ' || v_ename);
DBMS_OUTPUT.PUT_LINE('Job : ' || v_job);
END;
The following example demonstrates using the AUTHID DEFINER and SET clauses in a
procedure declaration. The update_salary procedure conveys the privileges of the
role that defined the procedure to the role that is calling the procedure (while the
procedure executes):
In this example, the AUTHID DEFINER clause temporarily grants privileges to a role that
might otherwise not be allowed to execute the statements within the procedure. To
instruct the server to use the privileges associated with the role invoking the procedure,
replace the AUTHID DEFINER clause with the AUTHID CURRENT_USER clause.
See Also
DROP PROCEDURE
Name
Synopsis
Description
CREATE PROFILE creates a new profile. Include the LIMIT clause and one or more
space-delimited parameter/value pairs to specify the rules enforced by Advanced
Server.
Advanced Server creates a default profile named DEFAULT. When you use the CREATE
ROLE command to create a new role, the new role is automatically associated with the
DEFAULT profile. If you upgrade from a previous version of Advanced Server to
Advanced Server 10, the upgrade process will automatically create the roles in the
upgraded version to the DEFAULT profile.
Include the LIMIT clause and one or more space-delimited parameter/value pairs to
specify the rules enforced by Advanced Server.
Parameters
profile_name
parameter
value
The value the parameter must reach before an action is taken by the server.
Advanced Server supports the value shown below for each parameter:
PASSWORD_LOCK_TIME specifies the length of time that must pass before the server
unlocks an account that has been locked because of FAILED_LOGIN_ATTEMPTS.
Supported values are:
PASSWORD_LIFE_TIME specifies the number of days that the current password may
be used before the user is prompted to provide a new password. Include the
PASSWORD_GRACE_TIME clause when using the PASSWORD_LIFE_TIME clause to
specify the number of days that will pass after the password expires before
connections by the role are rejected. If PASSWORD_GRACE_TIME is not specified, the
password will expire on the day specified by the default value of
PASSWORD_GRACE_TIME, and the user will not be allowed to execute any command
until a new password is provided. Supported values are:
PASSWORD_REUSE_TIME specifies the number of days a user must wait before re-
using a password. The PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX
parameters are intended to be used together. If you specify a finite value for one of
these parameters while the other is UNLIMITED, old passwords can never be reused.
If both parameters are set to UNLIMITED there are no restrictions on password reuse.
Supported values are:
Notes
The following command creates a profile named acctg. The profile specifies that if a
user has not authenticated with the correct password in five attempts, the account will be
locked for one day:
The following command creates a profile named sales. The profile specifies that a user
must change their password every 90 days:
If the user has not changed their password before the 90 days specified in the profile has
passed, they will be issued a warning at login. After a grace period of 3 days, their
account will not be allowed to invoke any commands until they change their password.
The following command creates a profile named accts. The profile specifies that a user
cannot re-use a password within 180 days of the last use of the password, and must
change their password at least 5 times before re-using the password:
The following command creates a profile named resources; the profile calls a user-
defined function named password_rules that will verify that the password provided
meets their standards for complexity:
Advanced Server includes extra syntax (not offered by Oracle) with the CREATE QUEUE
SQL command. This syntax can be used in association with DBMS_AQADM.
Name
Synopsis
RETRIES [INTEGER]
Description
The CREATE QUEUE command allows a database superuser or any user with the system-
defined aq_administrator_role privilege to create a new queue in the current
database.
If the name of the queue is schema-qualified, the queue is created in the specified
schema. If a schema is not included in the CREATE QUEUE command, the queue is
created in the current schema. A queue may only be created in the schema in which the
queue table resides. The name of the queue must be unique from the name of any other
queue in the same schema.
Parameters
name
queue_table_name
The name of the queue table with which this queue is associated.
option_name option_value
The name of any options that will be associated with the new queue, and the
corresponding value for the option. If the call to CREATE QUEUE includes
duplicate option names, the server will return an error. The following values are
supported:
Example
The following command creates a queue named work_order that is associated with a
queue table named work_order_table:
The server will allow 5 attempts to remove a message from the queue, and enforce a retry
delay of 2 seconds between attempts.
See Also
Advanced Server includes extra syntax (not offered by Oracle) with the CREATE QUEUE
TABLE SQL command. This syntax can be used in association with DBMS_AQADM.
Name
Synopsis
option_name option_value
SORT_LIST priority, enq_time
MULTIPLE_CONSUMERS FALSE, TRUE
MESSAGE_GROUPING NONE, TRANSACTIONAL
STORAGE_CLAUSE TABLESPACE tablespace_name, PCTFREE integer,
PCTUSED integer, INITRANS integer, MAXTRANS
integer, STORAGE storage_option
Where storage_option is one or more of the following:
MINEXTENTS integer, MAXEXTENTS integer,
PCTINCREASE integer, INITIAL size_clause, NEXT,
FREELISTS integer, OPTIMAL size_clause,
BUFFER_POOL {KEEP|RECYCLE|DEFAULT}.
Description
If the call to CREATE QUEUE TABLE includes a schema name, the queue table is created in
the specified schema. If no schema name is provided, the new queue table is created in
the current schema.
The name of the queue table must be unique from the name of any other queue table in
the same schema.
name
type_name
The name of an existing type that describes the payload of each entry in the queue
table. For information about defining a type, see CREATE TYPE.
option_name option_value
The name of any options that will be associated with the new queue table, and the
corresponding value for the option. If the call to CREATE QUEUE TABLE includes
duplicate option names, the server will return an error. The following values are
accepted:
SORT_LIST Use the SORT_LIST option to control the dequeueing order of the
queue; specify the names of the column(s) that will be used to sort the
queue (in ascending order). The currently accepted values are the
following combinations of enq_time and priority:
enq_time. priority
priority. enq_time
priority
enq_time
Any other value will return an ERROR.
MULTIPLE_CONSUMERS A BOOLEAN value that indicates if a message can have more than one
consumer (TRUE), or are limited to one consumer per message ( FALSE).
MESSAGE_GROUPING Specify none to indicate that each message should be dequeued
individually, or transactional to indicate that messages that are
added to the queue as a result of one transaction should be dequeued as
a group.
STORAGE_CLAUSE Use STORAGE_CLAUSE to specify table attributes.
STORAGE_CLAUSE may be TABLESPACE tablespace_name,
PCTFREE integer, PCTUSED integer, INITRANS integer,
MAXTRANS integer, STORAGE storage_option
Please note that only the TABLESPACE option is enforced; all others are
accepted for compatibility and ignored. Use the TABLESPACE clause to
specify the name of a tablespace in which the table will be created.
You must create a user-defined type before creating a queue table; the type describes the
columns and data types within the table. The following command creates a type named
work_order:
The following command uses the work_order type to create a queue table named
work_order_table:
See Also
Name
Synopsis
Description
CREATE ROLE adds a new role to the Advanced Server database cluster. A role is an
entity that can own database objects and have database privileges; a role can be
considered a user, a group, or both depending on how it is used. The newly created
role does not have the LOGIN attribute, so it cannot be used to start a session. Use the
ALTER ROLE command to give the role LOGIN rights. You must have CREATEROLE
privilege or be a database superuser to use the CREATE ROLE command.
If the IDENTIFIED BY clause is specified, the CREATE ROLE command also creates a
schema owned by, and with the same name as the newly created role.
Note that roles are defined at the database cluster level, and so are valid in all databases
in the cluster.
Parameters
name
IDENTIFIED BY password
Sets the roles password. (A password is only of use for roles having the LOGIN
attribute, but you can nonetheless define one for roles without it.) If you do not
plan to use password authentication you can omit this option.
Notes
Use ALTER ROLE to change the attributes of a role, and DROP ROLE to remove a role. The
attributes specified by CREATE ROLE can be modified by later ALTER ROLE commands.
The maximum length limit for role name and password is 63 characters.
Examples
See Also
Name
Synopsis
Description
This variation of the CREATE SCHEMA command creates a new schema owned by
username and populated with one or more objects. The creation of the schema and
objects occur within a single transaction so either all objects are created or none of them
including the schema. (Please note: if you are using an Oracle database, no new schema
is created username, and therefore the schema, must pre-exist.)
CREATE SCHEMA includes subcommands to create objects within the schema. The
subcommands are treated essentially the same as separate commands issued after creating
the schema. All the created objects will be owned by the specified user.
Parameters
username
The name of the user who will own the new schema. The schema will be named
the same as username. Only superusers may create schemas owned by users
other than themselves. (Please note: In Advanced Server the role, username,
must already exist, but the schema must not exist. In Oracle, the user
(equivalently, the schema) must exist.)
schema_element
Notes
To create a schema, the invoking user must have the CREATE privilege for the current
database. (Of course, superusers bypass this check.)
In Advanced Server, there are other forms of the CREATE SCHEMA command that are not
compatible with Oracle databases.
Examples
Name
Synopsis
Description
CREATE SEQUENCE creates a new sequence number generator. This involves creating
and initializing a new special single-row table with the name, name. The generator will
be owned by the user issuing the command.
If a schema name is given then the sequence is created in the specified schema, otherwise
it is created in the current schema. The sequence name must be distinct from the name of
any other sequence, table, index, or view in the same schema.
After a sequence is created, use the functions NEXTVAL and CURRVAL to operate on the
sequence. These functions are documented in Section 2.4.9.
Parameters
name
increment
The optional clause INCREMENT BY increment specifies the value to add to the
current sequence value to create a new value. A positive value will make an
ascending sequence, a negative one a descending sequence. The default value is 1.
The optional clause MAXVALUE maxvalue determines the maximum value for
the sequence. If this clause is not supplied, then default values will be used. The
defaults are 263-1 and -1 for ascending and descending sequences, respectively.
Note that the key words, NOMAXVALUE, may be used to set this behavior to the
default.
start
The optional clause START WITH start allows the sequence to begin anywhere.
The default starting value is minvalue for ascending sequences and maxvalue
for descending ones.
cache
The optional clause CACHE cache specifies how many sequence numbers are to
be preallocated and stored in memory for faster access. The minimum value is 1
(only one value can be generated at a time, i.e., NOCACHE), and this is also the
default.
CYCLE
The CYCLE option allows the sequence to wrap around when the maxvalue or
minvalue has been reached by an ascending or descending sequence
respectively. If the limit is reached, the next number generated will be the
minvalue or maxvalue, respectively.
If CYCLE is omitted (the default), any calls to NEXTVAL after the sequence has
reached its maximum value will return an error. Note that the key words, NO
CYCLE, may be used to obtain the default behavior, however, this term is not
compatible with Oracle databases.
Notes
Sequences are based on big integer arithmetic, so the range cannot exceed the range of an
eight-byte integer (-9223372036854775808 to 9223372036854775807). On some older
platforms, there may be no compiler support for eight-byte integers, in which case
sequences use regular INTEGER arithmetic (range -2147483648 to +2147483647).
Unexpected results may be obtained if a cache setting greater than one is used for a
sequence object that will be used concurrently by multiple sessions. Each session will
allocate and cache successive sequence values during one access to the sequence object
Examples
nextval
---------
101
(1 row)
nextval
---------
1
(1 row)
See Also
Name
Synopsis
Description
CREATE SYNONYM defines a synonym for certain types of database objects. Advanced
Server supports synonyms for:
tables
views
materialized views
sequences
packages
stored procedures
stored functions
types
objects that are accessible through a database link
other synonyms
Parameters:
syn_name
syn_name is the name of the synonym. A synonym name must be unique within
a schema.
schema
schema specifies the name of the schema that the synonym resides in. If you do
not specify a schema name, the synonym is created in the first existing schema in
your search path.
object_name
object_schema specifies the name of the schema that the referenced object
resides in.
dblink_name
dblink_name specifies the name of the database link through which an object is
accessed.
Include the REPLACE clause to replace an existing synonym definition with a new
synonym definition.
Include the PUBLIC clause to create the synonym in the public schema. The CREATE
PUBLIC SYNONYM command, compatible with Oracle databases, creates a synonym that
resides in the public schema:
Notes
Access to the object referenced by the synonym is determined by the permissions of the
current user of the synonym; the synonym user must have the appropriate permissions on
the underlying database object.
Examples
See Also
DROP SYNONYM
Name
Synopsis
[ CONSTRAINT constraint_name ]
{ NOT NULL |
NULL |
UNIQUE [ USING INDEX TABLESPACE tablespace ] |
PRIMARY KEY [ USING INDEX TABLESPACE tablespace ] |
CHECK (expression) |
REFERENCES reftable [ ( refcolumn ) ]
[ ON DELETE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED |
INITIALLY IMMEDIATE ]
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ...] )
[ USING INDEX TABLESPACE tablespace ] |
PRIMARY KEY ( column_name [, ...] )
[ USING INDEX TABLESPACE tablespace ] |
CHECK ( expression ) |
FOREIGN KEY ( column_name [, ...] )
REFERENCES reftable [ ( refcolumn [, ...] ) ]
[ ON DELETE action ] }
[ DEFERRABLE | NOT DEFERRABLE ]
[ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
Description
CREATE TABLE will create a new, initially empty table in the current database. The table
will be owned by the user issuing the command.
CREATE TABLE also automatically creates a data type that represents the composite type
corresponding to one row of the table. Therefore, tables cannot have the same name as
any existing data type in the same schema.
A table cannot have more than 1600 columns. (In practice, the effective limit is lower
because of tuple-length constraints).
The optional constraint clauses specify constraints (or tests) that new or updated rows
must satisfy for an insert or update operation to succeed. A constraint is an SQL object
that helps define the set of valid values in the table in various ways.
There are two ways to define constraints: table constraints and column constraints. A
column constraint is defined as part of a column definition. A table constraint definition
is not tied to a particular column, and it can encompass more than one column. Every
column constraint can also be written as a table constraint; a column constraint is only a
notational convenience if the constraint only affects one column.
Parameters
GLOBAL TEMPORARY
table_name
column_name
data_type
The data type of the column. This may include array specifiers. For more
information on the data types included with Advanced Server, refer to Section 0.
DEFAULT default_expr
The DEFAULT clause assigns a default data value for the column whose column
definition it appears within. The value is any variable-free expression (subqueries
and cross-references to other columns in the current table are not allowed). The
data type of the default expression must match the data type of the column.
The default expression will be used in any insert operation that does not specify a
value for the column. If there is no default for a column, then the default is null.
CONSTRAINT constraint_name
An optional name for a column or table constraint. If not specified, the system
generates a name.
NOT NULL
NULL
This clause is only available for compatibility with non-standard SQL databases.
Its use is discouraged in new applications.
The UNIQUE constraint specifies that a group of one or more distinct columns of a
table may contain only unique values. The behavior of the unique table constraint
is the same as that for column constraints, with the additional capability to span
multiple columns.
For the purpose of a unique constraint, null values are not considered equal.
Each unique table constraint must name a set of columns that is different from the
set of columns named by any other unique or primary key constraint defined for
the table. (Otherwise it would just be the same constraint listed twice.)
The primary key constraint specifies that a column or columns of a table may
contain only unique (non-duplicate), non-null values. Technically, PRIMARY KEY
is merely a combination of UNIQUE and NOT NULL, but identifying a set of
columns as primary key also provides metadata about the design of the schema, as
a primary key implies that other tables may rely on this set of columns as a unique
identifier for rows.
Only one primary key can be specified for a table, whether as a column constraint
or a table constraint.
The primary key constraint should name a set of columns that is different from
other sets of columns named by any unique constraint defined for the same table.
CHECK (expression)
The CHECK clause specifies an expression producing a Boolean result which new
or updated rows must satisfy for an insert or update operation to succeed.
Expressions evaluating to TRUE or unknown succeed. Should any row of an
insert or update operation produce a FALSE result an error exception is raised and
the insert or update does not alter the database. A check constraint specified as a
column constraint should reference that columns value only, while an expression
appearing in a table constraint may reference multiple columns.
These clauses specify a foreign key constraint, which requires that a group of one
or more columns of the new table must only contain values that match values in
the referenced column(s) of some row of the referenced table. If refcolumn is
omitted, the primary key of the reftable is used. The referenced columns must
be the columns of a unique or primary key constraint in the referenced table.
In addition, when the data in the referenced columns is changed, certain actions
are performed on the data in this tables columns. The ON DELETE clause
specifies the action to perform when a referenced row in the referenced table is
being deleted. Referential actions cannot be deferred even if the constraint is
deferrable. Here are the following possible actions for each clause:
Delete any rows referencing the deleted row, or update the value of the
referencing column to the new value of the referenced column,
respectively.
SET NULL
DEFERRABLE
NOT DEFERRABLE
This controls whether the constraint can be deferred. A constraint that is not
deferrable will be checked immediately after every command. Checking of
constraints that are deferrable may be postponed until the end of the transaction
(using the SET CONSTRAINTS command). NOT DEFERRABLE is the default. Only
foreign key constraints currently accept this clause. All other constraint types are
not deferrable.
INITIALLY IMMEDIATE
INITIALLY DEFERRED
If a constraint is deferrable, this clause specifies the default time to check the
constraint. If the constraint is INITIALLY IMMEDIATE, it is checked after each
statement. This is the default. If the constraint is INITIALLY DEFERRED, it is
checked only at the end of the transaction. The constraint check time can be
altered with the SET CONSTRAINTS command.
ON COMMIT
PRESERVE ROWS
All rows in the temporary table will be deleted at the end of each
transaction block. Essentially, an automatic TRUNCATE is done at each
commit.
TABLESPACE tablespace
The tablespace is the name of the tablespace in which the new table is to be
created. If not specified, default tablespace is used, or the databases default
tablespace if default_tablespace is an empty string.
This clause allows selection of the tablespace in which the index associated with a
UNIQUE or PRIMARY KEY constraint will be created. If not specified, default
tablespace is used, or the databases default tablespace if
default_tablespace is an empty string.
Notes
Advanced Server automatically creates an index for each unique constraint and primary
key constraint to enforce the uniqueness. Thus, it is not necessary to create an explicit
index for primary key columns. (See CREATE INDEX for more information.)
Examples
Define a unique table constraint for the table dept. Unique table constraints can be
defined on one or more columns of the table.
Define a primary key table constraint for the table jobhist. Primary key table
constraints can be defined on one or more columns of the table.
This assigns a literal constant default value for the column, job and makes the default
value of hiredate be the date at which the row is inserted.
See Also
Name
Synopsis
Description
CREATE TABLE AS creates a table and fills it with data computed by a SELECT
command. The table columns have the names and data types associated with the output
columns of the SELECT (except that you can override the column names by giving an
explicit list of new column names).
CREATE TABLE AS bears some resemblance to creating a view, but it is really quite
different: it creates a new table and evaluates the query just once to fill the new table
initially. The new table will not track subsequent changes to the source tables of the
query. In contrast, a view re-evaluates its defining SELECT statement whenever it is
queried.
Parameters
GLOBAL TEMPORARY
If specified, the table is created as a temporary table. Refer to CREATE TABLE for
details.
table_name
column_name
The name of a column in the new table. If column names are not provided, they
are taken from the output column names of the query.
Name
Synopsis
Description
CREATE TRIGGER defines a new trigger. CREATE OR REPLACE TRIGGER will either
create a new trigger, or replace an existing definition.
If you are using the CREATE TRIGGER keywords to create a new trigger, the name of the
new trigger must not match any existing trigger defined on the same table. New triggers
will be created in the same schema as the table on which the triggering event is defined.
If you are updating the definition of an existing trigger, use the CREATE OR REPLACE
TRIGGER keywords.
When you use syntax that is compatible with Oracle to create a trigger, the trigger runs as
a SECURITY DEFINER function.
Parameters
name
Determines whether the trigger is fired before or after the triggering event.
table
condition
If the trigger definition includes the FOR EACH ROW keywords, the WHEN clause
can refer to columns of the old and/or new row values by writing
OLD.column_name or NEW.column_name respectively. INSERT triggers cannot
refer to OLD and DELETE triggers cannot refer to NEW.
If the trigger includes the INSTEAD OF keywords, it may not include a WHEN
clause. A WHEN clause cannot contain subqueries.
REFERENCING clause to reference old rows and new rows, but restricted in that
old may only be replaced by an identifier named old or any equivalent that is
saved in all lowercase (for example, REFERENCING OLD AS old,
REFERENCING OLD AS OLD, or REFERENCING OLD AS "old"). Also, new
may only be replaced by an identifier named new or any equivalent that is saved
in all lowercase (for example, REFERENCING NEW AS new, REFERENCING
NEW AS NEW, or REFERENCING NEW AS "new").
Either one, or both phrases OLD AS old and NEW AS new may be specified in
the REFERENCING clause (for example, REFERENCING NEW AS New OLD AS
Old).
This clause is not compatible with Oracle databases in that identifiers other than
old or new may not be used.
Determines whether the trigger should be fired once for every row affected by the
triggering event, or just once per SQL statement. If specified, the trigger is fired
declaration
statement
exception
Examples
The following is a statement-level trigger that fires after the triggering statement (insert,
update, or delete on table emp) is executed.
The following is a row-level trigger that fires before each row is either inserted, updated,
or deleted on table emp.
See Also
DROP TRIGGER
Name
CREATE TYPE -- define a new user-defined type, which can be an object type, a
collection type (a nested table type or a varray type), or a composite type.
Synopsis
Object Type
{ MEMBER | STATIC }
{ PROCEDURE proc_name
[ ( [ SELF [ IN | IN OUT ] name ]
[, argname [ IN | IN OUT | OUT ] argtype
[ DEFAULT value ]
] ...)
]
|
FUNCTION func_name
[ ( [ SELF [ IN | IN OUT ] name ]
[, argname [ IN | IN OUT | OUT ] argtype
[ DEFAULT value ]
] ...)
]
RETURN rettype
}
Varray Type
Composite Type
Description
CREATE TYPE defines a new, user-defined data type. The types that can be created are an
object type, a nested table type, a varray type, or a composite type. Nested table and
varray types belong to the category of types known as collections.
Composite types are not compatible with Oracle databases. However, composite types
can be accessed by SPL programs as with other types described in this section.
Note: For packages only, a composite type can be included in a user-defined record type
declared with the TYPE IS RECORD statement within the package specification or
package body. Such nested structure is not permitted in other SPL programs such as
functions, procedures, triggers, etc.
In the CREATE TYPE command, if a schema name is included, then the type is created in
the specified schema, otherwise it is created in the current schema. The name of the new
type must not match any existing type in the same schema unless the intent is to update
the definition of an existing type, in which case use CREATE OR REPLACE TYPE.
Note: The OR REPLACE option cannot be currently used to add, delete, or modify the
attributes of an existing object type. Use the DROP TYPE command to first delete the
existing object type. The OR REPLACE option can be used to add, delete, or modify the
methods in an existing object type.
Note: The PostgreSQL form of the ALTER TYPE ALTER ATTRIBUTE command can be
used to change the data type of an attribute in an existing object type. However, the
ALTER TYPE command cannot add or delete attributes in the object type.
The user that creates the type becomes the owner of the type.
name
DEFINER | CURRENT_USER
Specifies whether the privileges of the object type owner (DEFINER) or the
privileges of the current user executing a method in the object type
(CURRENT_USER) are to be used to determine whether or not access is allowed to
database objects referenced in the object type. DEFINER is the default.
attribute
datatype
The data type that defines an attribute of the object type or composite type, or the
elements of the collection type that is being created.
objtype
The name of an object type that defines an attribute of the object type or the
elements of the collection type that is being created.
collecttype
The name of a collection type that defines an attribute of the object type or the
elements of the collection type that is being created.
FINAL
NOT FINAL
For an object type, specifies whether or not a subtype can be derived from the
object type. FINAL (subtype cannot be derived from the object type) is the
default.
INSTANTIABLE
NOT INSTANTIABLE
For an object type, specifies whether or not an object instance can be created of
this object type. INSTANTIABLE (an instance of this object type can be created) is
For method_spec, specifies whether or not the object type definition provides an
implementation for the method. INSTANTIABLE (the CREATE TYPE BODY
command for the object type provides the implementation of the method) is the
default. If NOT INSTANTIABLE is specified, then the CREATE TYPE BODY
command for the object type must not contain the implementation of the method.
OVERRIDING
MEMBER
STATIC
proc_name
For a member method there is an implicit, built-in parameter named SELF whose
data type is that of the object type being defined. SELF refers to the object
instance that is currently invoking the method. SELF can be explicitly declared as
an IN or IN OUT parameter in the parameter list. If explicitly declared, SELF
must be the first parameter in the parameter list. If SELF is not explicitly declared,
its parameter mode defaults to IN OUT for member procedures and IN for
member functions.
argname
The name of an argument. The argument is referenced by this name within the
method body.
argtype
DEFAULT value
Supplies a default value for an input argument if one is not supplied in the method
call. DEFAULT may not be specified for arguments with modes IN OUT or OUT.
func_name
rettype
The return data type, which may be any of the types listed for argtype. As for
argtype, a length must not be specified for rettype.
maxsize
Examples
The following example shows the usage of a composite type accessed from an
anonymous block.
The following is the anonymous block that accesses the composite type:
DECLARE
v_emphist EMPHIST_TYP;
BEGIN
v_emphist.empno := 9001;
v_emphist.ename := 'SMITH';
v_emphist.hiredate := '01-AUG-17';
v_emphist.job := 'SALESMAN';
v_emphist.sal := 8000.00;
DBMS_OUTPUT.PUT_LINE(' EMPNO: ' || v_emphist.empno);
DBMS_OUTPUT.PUT_LINE(' ENAME: ' || v_emphist.ename);
DBMS_OUTPUT.PUT_LINE('HIREDATE: ' || v_emphist.hiredate);
DBMS_OUTPUT.PUT_LINE(' JOB: ' || v_emphist.job);
DBMS_OUTPUT.PUT_LINE(' SAL: ' || v_emphist.sal);
END;
EMPNO: 9001
ENAME: SMITH
HIREDATE: 01-AUG-17 00:00:00
JOB: SALESMAN
SAL: 8000.00
The following example shows the usage of a composite type accessed from a user-
defined record type, declared within a package body.
PROCEDURE fetch_emp (
p_empno IN NUMBER
)
IS
CURSOR emp_cur IS SELECT e.empno, e.ename, h.startdate, h.job, h.sal
FROM emp e, jobhist h
WHERE e.empno = p_empno
AND e.empno = h.empno;
i INTEGER := 0;
BEGIN
DBMS_OUTPUT.PUT_LINE('EMPNO ENAME STARTDATE JOB ' ||
'SAL ');
DBMS_OUTPUT.PUT_LINE('----- ------- --------- --------- ' ||
'---------');
Note that in the declaration of the TYPE emprec_typ IS RECORD data structure in the
package body, the salhist field is defined with the SALHIST_TYP composite type as
created by the CREATE TYPE salhist_typ statement.
Invocation of the package procedure that loads the array from a join of the emp and
jobhist tables, then displays the array content is shown by the following:
EXEC emp_salhist.fetch_emp(7788);
See Also
Name
Synopsis
subprogram_spec
{ MEMBER | STATIC }
{ PROCEDURE proc_name
[ ( [ SELF [ IN | IN OUT ] name ]
[, argname [ IN | IN OUT | OUT ] argtype
[ DEFAULT value ]
] ...)
]
{ IS | AS }
program_body
END;
|
FUNCTION func_name
[ ( [ SELF [ IN | IN OUT ] name ]
[, argname [ IN | IN OUT | OUT ] argtype
[ DEFAULT value ]
] ...)
]
RETURN rettype
{ IS |AS }
program_body
END;
}
Description
CREATE TYPE BODY defines a new object type body. CREATE OR REPLACE TYPE
BODY will either create a new object type body, or replace an existing body.
Parameters
name
The name (optionally schema-qualified) of the object type for which a body is to
be created.
MEMBER
STATIC
proc_name
For a member method there is an implicit, built-in parameter named SELF whose
data type is that of the object type being defined. SELF refers to the object
instance that is currently invoking the method. SELF can be explicitly declared as
an IN or IN OUT parameter in the parameter list. If explicitly declared, SELF
must be the first parameter in the parameter list. If SELF is not explicitly declared,
its parameter mode defaults to IN OUT for member procedures and IN for
member functions.
argname
The name of an argument. The argument is referenced by this name within the
method body.
argtype
The data type(s) of the methods arguments. The argument types may be a base
data type or a user-defined type such as a nested table or an object type. A length
must not be specified for any base type - for example, specify VARCHAR2, not
VARCHAR2(10).
Supplies a default value for an input argument if one is not supplied in the method
call. DEFAULT may not be specified for arguments with modes IN OUT or OUT.
program_body
The declarations and SPL statements that comprise the body of the function or
procedure.
func_name
rettype
The return data type, which may be any of the types listed for argtype. As for
argtype, a length must not be specified for rettype.
Examples
Create the object type body for object type emp_obj_typ given in the example for the
CREATE TYPE command.
Create the object type body for object type dept_obj_typ given in the example for the
CREATE TYPE command.
See Also
Name
Synopsis
Description
CREATE USER adds a new user to an Advanced Server database cluster. You must be a
database superuser to use this command.
When the CREATE USER command is given, a schema will also be created with the same
name as the new user and owned by the new user. Objects with unqualified names
created by this user will be created in this schema.
Parameters
name
password
The users password. The password can be changed later using ALTER USER.
Notes
The maximum length allowed for the user name and password is 63 characters.
Examples
See Also
DROP USER
Name
CREATE USER|ROLE
Synopsis
PROFILE profile_name
| ACCOUNT {LOCK|UNLOCK}
| PASSWORD EXPIRE [AT 'timestamp']
For information about the administrative clauses of the CREATE USER or CREATE ROLE
command that are supported by Advanced Server, please see the PostgreSQL core
documentation available at:
https://www.postgresql.org/docs/10/static/sql-commands.html
Description
Roles created with the CREATE USER command are (by default) login roles. Roles
created with the CREATE ROLE command are (by default) not login roles. To create a
login account with the CREATE ROLE command, you must include the LOGIN keyword.
Only a database superuser can use the CREATE USER|ROLE clauses that enforce profile
management; these clauses enforce the following behaviors:
Include the LOCK TIME 'timestamp' clause and a date/time value to lock the
role at the specified time, and unlock the role at the time indicated by the
PASSWORD_LOCK_TIME parameter of the profile assigned to this role. If LOCK
TIME is used with the ACCOUNT LOCK clause, the role can only be unlocked by a
database superuser with the ACCOUNT UNLOCK clause.
Each login role may only have one profile. To discover the profile that is currently
associated with a login role, query the profile column of the DBA_USERS view.
Parameters
name
profile_name
timestamp
The date and time at which the clause will be enforced. When specifying a value
for timestamp, enclose the value in single-quotes.
Examples
The following example uses CREATE USER to create a login role named john who is
associated with the acctg_profile profile:
The following example uses CREATE ROLE to create a login role named john who is
associated with the acctg_profile profile:
Name
Synopsis
Description
CREATE VIEW defines a view of a query. The view is not physically materialized.
Instead, the query is run every time the view is referenced in a query.
CREATE OR REPLACE VIEW is similar, but if a view of the same name already exists, it
is replaced.
If a schema name is given (for example, CREATE VIEW myschema.myview ...) then the
view is created in the specified schema. Otherwise it is created in the current schema. The
view name must be distinct from the name of any other view, table, sequence, or index in
the same schema.
Parameters
name
column_name
An optional list of names to be used for columns of the view. If not given, the
column names are deduced from the query.
query
A query (that is, a SELECT statement) which will provide the columns and rows
of the view.
Currently, views are read only - the system will not allow an insert, update, or delete on a
view. You can get the effect of an updatable view by creating rules that rewrite inserts,
etc. on the view into appropriate actions on other tables.
Access to tables referenced in the view is determined by permissions of the view owner.
However, functions called in the view are treated the same as if they had been called
directly from the query using the view. Therefore the user of a view must have
permissions to call all functions used by the view.
Examples
See Also
DROP VIEW
2.3.41 DELETE
Name
Synopsis
Description
DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE
clause is absent, the effect is to delete all rows in the table. The result is a valid, but
empty table.
Note: The TRUNCATE command provides a faster mechanism to remove all rows from a
table.
The RETURNING BULK COLLECT INTO collection [, ...] clause may only be
specified if the DELETE command is used within an SPL program. If more than one
collection is specified as the target of the BULK COLLECT INTO clause, then each
collection must consist of a single, scalar field i.e., collection must not be a
record. The result set of the DELETE command may contain none, one, or more rows.
return_expression evaluated for each row of the result set, becomes an element in
collection starting with the first element. Any existing rows in collection are
deleted. If the result set is empty, then collection will be empty.
You must have the DELETE privilege on the table to delete from it, as well as the SELECT
privilege for any table whose values are read in the condition.
optimizer_hint
table
dblink
Database link name identifying a remote database. See the CREATE DATABASE
LINK command for information on database links.
condition
A value expression that returns a value of type BOOLEAN that determines the rows
which are to be deleted.
return_expression
An expression that may include one or more columns from table. If a column
name from table is specified in return_expression, the value substituted for
the column when return_expression is evaluated is the value from the
deleted row.
record
variable
collection
Examples
Delete all rows for employee 7900 from the jobhist table:
See Also
TRUNCATE
Name
Synopsis
Description
DROP DATABASE LINK drops existing database links. To execute this command you
must be a superuser or the owner of the database link.
Parameters
name
PUBLIC
Examples
See Also
Name
DROP DIRECTORY -- remove a directory alias for a file system directory path
Synopsis
Description
DROP DIRECTORY drops an existing alias for a file system directory path that was
created with the CREATE DIRECTORY command. To execute this command you must be
a superuser.
When a directory alias is deleted, the corresponding physical file system directory is not
affected. The file system directory must be deleted using the appropriate operating
system commands.
Parameters
name
Examples
See Also
CREATE DIRECTORY
Name
Synopsis
Description
Parameters
name
argmode
The mode of an argument: IN, IN OUT, or OUT. If omitted, the default is IN. Note
that DROP FUNCTION does not actually pay any attention to OUT arguments, since
only the input arguments are needed to determine the functions identity. So it is
sufficient to list only the IN and IN OUT arguments. (Specification of argmode is
not compatible with Oracle databases and applies only to Advanced Server.)
argname
The name of an argument. Note that DROP FUNCTION does not actually pay any
attention to argument names, since only the argument data types are needed to
determine the functions identity. (Specification of argname is not compatible
with Oracle databases and applies only to Advanced Server.)
Examples
See Also
CREATE FUNCTION
Name
Synopsis
Description
DROP INDEX drops an existing index from the database system. To execute this
command you must be a superuser or the owner of the index. If any objects depend on the
index, an error will be given and the index will not be dropped.
Parameters
name
Examples
See Also
Name
Synopsis
Description
DROP PACKAGE drops an existing package. To execute this command you must be a
superuser or the owner of the package. If BODY is specified, only the package body is
removed the package specification is not dropped. If BODY is omitted, both the package
specification and body are removed.
Parameters
name
Examples
See Also
Name
Synopsis
Description
Parameters
name
Examples
See Also
CREATE PROCEDURE
Name
Synopsis
Description
Include the IF EXISTS clause to instruct the server to not throw an error if the specified
profile does not exist. The server will issue a notice if the profile does not exist.
Include the optional CASCADE clause to reassign any users that are currently associated
with the profile to the default profile, and then drop the profile. Include the optional
RESTRICT clause to instruct the server to not drop any profile that is associated with a
role. This is the default behavior.
Parameters
profile_name
Example
The command first re-associates any roles associated with the acctg_profile profile
with the default profile, and then drops the acctg_profile profile.
The RESTRICT clause in the command instructs the server to not drop acctg_profile
if there are any roles associated with the profile.
Advanced Server includes extra syntax (not offered by Oracle) with the DROP QUEUE
SQL command. This syntax can be used in association with DBMS_AQADM.
Name
Synopsis
Description
Parameters
name
IF EXISTS
Include the IF EXISTS clause to instruct the server to not return an error if the
queue does not exist. The server will issue a notice.
Examples
See Also
Advanced Server includes extra syntax (not offered by Oracle) with the DROP QUEUE
TABLE SQL command. This syntax can be used in association with DBMS_AQADM.
Name
Synopsis
Description
Parameters
name
The name (possibly schema-qualified) of the queue table that will be deleted.
IF EXISTS
Include the IF EXISTS clause to instruct the server to not return an error if the
queue table does not exist. The server will issue a notice.
CASCADE
Include the CASCADE keyword to automatically delete any objects that depend
on the queue table.
RESTRICT
Include the RESTRICT keyword to instruct the server to refuse to delete the
queue table if any objects depend on it. This is the default.
The following example deletes a queue table named work_order_table and any
objects that depend on it:
See Also
Name
Synopsis
Description
DROP SYNONYM deletes existing synonyms. To execute this command you must be a
superuser or the owner of the synonym, and have USAGE privileges on the schema in
which the synonym resides.
Parameters:
syn_name
syn_name is the name of the synonym. A synonym name must be unique within
a schema.
schema
schema specifies the name of the schema that the synonym resides in.
Like any other object that can be schema-qualified, you may have two synonyms with the
same name in your search path. To disambiguate the name of the synonym that you are
dropping, include a schema name. Unless a synonym is schema qualified in the DROP
SYNONYM command, Advanced Server deletes the first instance of the synonym it finds in
your search path.
You can optionally include the PUBLIC clause to drop a synonym that resides in the
public schema. The DROP PUBLIC SYNONYM command, compatible with Oracle
databases, drops a synonym that resides in the public schema:
Name
Synopsis
Description
DROP ROLE removes the specified role. To drop a superuser role, you must be a
superuser yourself; to drop non-superuser roles, you must have CREATEROLE privilege.
A role cannot be removed if it is still referenced in any database of the cluster; an error
will be raised if so. Before dropping the role, you must drop all the objects it owns (or
reassign their ownership) and revoke any privileges the role has been granted.
It is not necessary to remove role memberships involving the role; DROP ROLE
automatically revokes any memberships of the target role in other roles, and of other
roles in the target role. The other roles are not dropped nor otherwise affected.
Alternatively, if the only objects owned by the role belong within a schema that is owned
by the role and has the same name as the role, the CASCADE option can be specified. In
this case the issuer of the DROP ROLE name CASCADE command must be a superuser
and the named role, the schema, and all objects within the schema will be deleted.
Parameters
name
CASCADE
If specified, also drops the schema owned by, and with the same name as the role
(and all objects owned by the role belonging to the schema) as long as no other
dependencies on the role or the schema exist.
To drop a role:
See Also
Name
Synopsis
Description
DROP SEQUENCE removes sequence number generators. To execute this command you
must be a superuser or the owner of the sequence.
Parameters
name
Examples
See Also
Name
Synopsis
Description
DROP TABLE removes tables from the database. Only its owner may destroy a table. To
empty a table of rows, without destroying the table, use DELETE. DROP TABLE always
removes any indexes, rules, triggers, and constraints that exist for the target table.
Parameters
name
Include the RESTRICT keyword to specify that the server should refuse to drop the table
if any objects depend on it. This is the default behavior; the DROP TABLE command will
report an error if any objects depend on the table.
Include the CASCADE clause to drop any objects that depend on the table.
Include the CASCADE CONSTRAINTS clause to specify that Advanced Server should drop
any dependent constraints (excluding other object types) on the specified table.
Examples
The following command drops a table named emp that has no dependencies:
The outcome of a DROP TABLE command will vary depending on whether the table has
any dependencies - you can control the outcome by specifying a drop behavior. For
example, if you create two tables, orders and items, where the items table is
dependent on the orders table:
Advanced Server will perform one of the following actions when dropping the orders
table, depending on the drop behavior that you specify:
If you specify DROP TABLE orders RESTRICT, Advanced Server will report an
error.
If you specify DROP TABLE orders CASCADE, Advanced Server will drop the
orders table and the items table.
See Also
Name
Synopsis
Description
A tablespace can only be dropped by its owner or a superuser. The tablespace must be
empty of all database objects before it can be dropped. It is possible that objects in other
databases may still reside in the tablespace even if no objects in the current database are
using the tablespace.
Parameters
tablespacename
Examples
See Also
ALTER TABLESPACE
Name
Synopsis
Description
DROP TRIGGER removes a trigger from its associated table. The command must be run
by a superuser or the owner of the table on which the trigger is defined.
Parameters
name
Examples
See Also
CREATE TRIGGER
Name
Synopsis
Description
DROP TYPE removes the type definition. To execute this command you must be a
superuser or the owner of the type.
The optional BODY qualifier applies only to object type definitions, not to collection types
nor to composite types. If BODY is specified, only the object type body is removed the
object type specification is not dropped. If BODY is omitted, both the object type
specification and body are removed.
The type will not be deleted if there are other database objects dependent upon the named
type.
Parameters
name
Examples
See Also
Name
Synopsis
Description
DROP USER removes the specified user. To drop a superuser, you must be a superuser
yourself; to drop non-superusers, you must have CREATEROLE privilege.
A user cannot be removed if it is still referenced in any database of the cluster; an error
will be raised if so. Before dropping the user, you must drop all the objects it owns (or
reassign their ownership) and revoke any privileges the user has been granted.
However, it is not necessary to remove role memberships involving the user; DROP USER
automatically revokes any memberships of the target user in other roles, and of other
roles in the target user. The other roles are not dropped nor otherwise affected.
Alternatively, if the only objects owned by the user belong within a schema that is owned
by the user and has the same name as the user, the CASCADE option can be specified. In
this case the issuer of the DROP USER name CASCADE command must be a superuser
and the named user, the schema, and all objects within the schema will be deleted.
Parameters
name
CASCADE
If specified, also drops the schema owned by, and with the same name as the user
(and all objects owned by the user belonging to the schema) as long as no other
dependencies on the user or the schema exist.
To drop a user account who owns no objects nor has been granted any privileges on other
objects:
To drop user account, john, who has not been granted any privileges on any objects, and
does not own any objects outside of a schema named, john, that is owned by user, john:
See Also
Name
Synopsis
Description
DROP VIEW drops an existing view. To execute this command you must be a database
superuser or the owner of the view. The named view will not be deleted if other objects
are dependent upon this view (such as a view of a view).
The form of the DROP VIEW command compatible with Oracle does not support a
CASCADE clause; to drop a view and it's dependencies, use the PostgreSQL-compatible
form of the DROP VIEW command. For more information, see the PostgreSQL core
documentation at:
https://www.postgresql.org/docs/10/static/sql-dropview.html
Parameters
name
Examples
See Also
CREATE VIEW
2.3.60 EXEC
Name
EXEC
Synopsis
Description
EXECUTE .
Parameters
procedure_name
argument_list
Examples
The EXEC statement may take one of several forms, depending on the arguments required
by the function:
EXEC update_balance;
EXEC update_balance();
EXEC update_balance(1,2,3);
2.3.61 GRANT
Name
Synopsis
Description
The GRANT command has three basic variants: one that grants privileges on a database
object (table, view, sequence, or program), one that grants membership in a role, and one
that grants system privileges. These variants are similar in many ways, but they are
different enough to be described separately.
In Advanced Server, the concept of users and groups has been unified into a single type
of entity called a role. In this context, a user is a role that has the LOGIN attribute the
role may be used to create a session and connect to an application. A group is a role that
does not have the LOGIN attribute the role may not be used to create a session or
connect to an application.
A role may be a member of one or more other roles, so the traditional concept of users
belonging to groups is still valid. However, with the generalization of users and groups,
users may belong to users, groups may belong to groups, and groups may belong
to users, forming a general multi-level hierarchy of roles. User names and group names
share the same namespace therefore it is not necessary to distinguish whether a grantee is
a user or a group in the GRANT command.
This variant of the GRANT command gives specific privileges on a database object to a
role. These privileges are added to those already granted, if any.
The key word PUBLIC indicates that the privileges are to be granted to all roles,
including those that may be created later. PUBLIC may be thought of as an implicitly
defined group that always includes all roles. Any particular role will have the sum of
privileges granted directly to it, privileges granted to any role it is presently a member of,
and privileges granted to PUBLIC.
If the WITH GRANT OPTION is specified, the recipient of the privilege may in turn grant
it to others. Without a grant option, the recipient cannot do that. Grant options cannot be
granted to PUBLIC.
There is no need to grant privileges to the owner of an object (usually the user that
created it), as the owner has all privileges by default. (The owner could, however, choose
to revoke some of his own privileges for safety.) The right to drop an object or to alter its
definition in any way is not described by a grantable privilege; it is inherent in the owner,
and cannot be granted or revoked. The owner implicitly has all grant options for the
object as well.
Depending on the type of object, the initial default privileges may include granting some
privileges to PUBLIC. The default is no public access for tables and EXECUTE privilege
for functions, procedures, and packages. The object owner may of course revoke these
privileges. (For maximum security, issue the REVOKE in the same transaction that creates
the object; then there is no window in which another user may use the object.)
SELECT
Allows SELECT from any column of the specified table, view, or sequence. For
sequences, this privilege also allows the use of the currval function.
INSERT
UPDATE
Allows UPDATE of a column of the specified table. SELECT ... FOR UPDATE
also requires this privilege (besides the SELECT privilege).
REFERENCES
To create a foreign key constraint, it is necessary to have this privilege on both the
referencing and referenced tables.
EXECUTE
Allows the use of the specified package, procedure, or function. When applied to
a package, allows the use of all of the packages public procedures, public
functions, public variables, records, cursors and other public objects and object
types. This is the only type of privilege that is applicable to functions, procedures,
and packages.
The Advanced Server syntax for granting the EXECUTE privilege is not fully
compatible with Oracle databases. Advanced Server requires qualification of the
program name by one of the keywords, FUNCTION, PROCEDURE, or PACKAGE
whereas these keywords must be omitted in Oracle. For functions, Advanced
Server requires all input (IN, IN OUT) argument data types after the function
name (including an empty parenthesis if there are no function arguments). For
procedures, all input argument data types must be specified if the procedure has
one or more input arguments. In Oracle, function and procedure signatures must
be omitted. This is due to the fact that all programs share the same namespace in
Oracle, whereas functions, procedures, and packages have their own individual
namespace in Advanced Server to allow program name overloading to a certain
extent.
ALL PRIVILEGES
The privileges required by other commands are listed on the reference page of the
respective command.
This variant of the GRANT command grants membership in a role to one or more other
roles. Membership in a role is significant because it conveys the privileges granted to a
role to each of its members.
If the WITH ADMIN OPTION is specified, the member may in turn grant membership in
the role to others, and revoke membership in the role as well. Without the admin option,
ordinary users cannot do that.
Database superusers can grant or revoke membership in any role to anyone. Roles having
the CREATEROLE privilege can grant or revoke membership in any role that is not a
superuser.
There are three pre-defined roles that have the following meanings:
CONNECT
Granting the CONNECT role is equivalent to giving the grantee the LOGIN
privilege. The grantor must have the CREATEROLE privilege.
RESOURCE
Granting the RESOURCE role is equivalent to granting the CREATE and USAGE
privileges on a schema that has the same name as the grantee. This schema must
exist before the grant is given. The grantor must have the privilege to grant
CREATE or USAGE privileges on this schema to the grantee.
DBA
Granting the DBA role is equivalent to making the grantee a superuser. The grantor
must be a superuser.
Notes
When a non-owner of an object attempts to GRANT privileges on the object, the command
will fail outright if the user has no privileges whatsoever on the object. As long as a
privilege is available, the command will proceed, but it will grant only those privileges
for which the user has grant options. The GRANT ALL PRIVILEGES forms will issue a
warning message if no grant options are held, while the other forms will issue a warning
if grant options for any of the privileges specifically named in the command are not held.
It should be noted that database superusers can access all objects regardless of object
privilege settings. This is comparable to the rights of root in a Unix system. As with
root, its unwise to operate as a superuser except when absolutely necessary.
GRANT and REVOKE can also be done by a role that is not the owner of the affected
object, but is a member of the role that owns the object, or is a member of a role that
holds privileges WITH GRANT OPTION on the object. In this case the privileges will be
recorded as having been granted by the role that actually owns the object or holds the
privileges WITH GRANT OPTION.
For example, if table t1 is owned by role g1, of which role u1 is a member, then
u1 can grant privileges on t1 to u2, but those privileges will appear to have been
granted directly by g1. Any other member of role g1 could revoke them later.
If the role executing GRANT holds the required privileges indirectly via more than one
role membership path, it is unspecified which containing role will be recorded as having
done the grant. In such cases it is best practice to use SET ROLE to become the specific
role you want to do the GRANT as.
Currently, Advanced Server does not support granting or revoking privileges for
individual columns of a table. One possible workaround is to create a view having just
the desired columns and then grant privileges to that view.
Examples
Note that while the above will indeed grant all privileges if executed by a superuser or the
owner of emp, when executed by someone else it will only grant those permissions for
which the someone else has grant options.
See Also
This variant of the GRANT command gives a role the ability to perform certain system
operations within a database. System privileges relate to the ability to create or delete
certain database objects that are not necessarily within the confines of one schema. Only
database superusers can grant system privileges.
The CREATE [PUBLIC] DATABASE LINK privilege allows the specified role to create a
database link. Include the PUBLIC keyword to allow the role to create public database
links; omit the PUBLIC keyword to allow the specified role to create private database
links.
The DROP PUBLIC DATABASE LINK privilege allows a role to drop a public database
link. System privileges are not required to drop a private database link. A private
database link may be dropped by the link owner or a database superuser.
The EXEMPT ACCESS POLICY privilege allows a role to execute a SQL command
without invoking any policy function that may be associated with the target database
object. That is, the role is exempt from all security policies in the database.
The EXEMPT ACCESS POLICY privilege is not inheritable by membership to a role that
has the EXEMPT ACCESS POLICY privilege. For example, the following sequence of
GRANT commands does not result in user joe obtaining the EXEMPT ACCESS POLICY
privilege even though joe is granted membership to the enterprisedb role, which has
been granted the EXEMPT ACCESS POLICY privilege:
The rolpolicyexempt column of the system catalog table pg_authid is set to true
if a role has the EXEMPT ACCESS POLICY privilege.
Examples
The Advanced Server ALTER ROLE command also supports syntax that you can use to
assign:
See Also
2.3.65 INSERT
Name
Synopsis
Description
INSERT allows you to insert new rows into a table. You can insert a single row at a time
or several rows as a result of a query.
The columns in the target list may be listed in any order. Each column not present in the
target list will be inserted using a default value, either its declared default value or null.
If the expression for each column is not of the correct data type, automatic type
conversion will be attempted.
The RETURNING BULK COLLECT INTO collection [, ...] clause may only be
specified if the INSERT command is used within an SPL program. If more than one
collection is specified as the target of the BULK COLLECT INTO clause, then each
collection must consist of a single, scalar field i.e., collection must not be a
record. return_expression evaluated for each inserted row, becomes an element in
collection starting with the first element. Any existing rows in collection are
deleted. If the result set is empty, then collection will be empty.
You must have INSERT privilege to a table in order to insert into it. If you use the query
clause to insert rows from a query, you also need to have SELECT privilege on any table
used in the query.
table
dblink
Database link name identifying a remote database. See the CREATE DATABASE
LINK command for information on database links.
column
expression
DEFAULT
query
A query (SELECT statement) that supplies the rows to be inserted. Refer to the
SELECT command for a description of the syntax.
return_expression
An expression that may include one or more columns from table. If a column
name from table is specified in return_expression, the value substituted for
the column when return_expression is evaluated is determined as follows:
record
variable
collection
Examples
In this second example, the column, comm, is omitted and therefore it will have the
default value of null:
INSERT INTO emp (empno, ename, job, mgr, hiredate, sal, deptno)
VALUES (8022,'PETERS','CLERK',7698,'03-DEC-06',950,30);
The third example uses the DEFAULT clause for the hiredate and comm columns rather
than specifying a value:
This example creates a table for the department names and then inserts into the table by
selecting from the dname column of the dept table:
2.3.66 LOCK
Name
Synopsis
Description
LOCK TABLE obtains a table-level lock, waiting if necessary for any conflicting locks to
be released. If NOWAIT is specified, LOCK TABLE does not wait to acquire the desired
lock: if it cannot be acquired immediately, the command is aborted and an error is
emitted. Once obtained, the lock is held for the remainder of the current transaction.
(There is no UNLOCK TABLE command; locks are always released at transaction end.)
When acquiring locks automatically for commands that reference tables, Advanced
Server always uses the least restrictive lock mode possible. LOCK TABLE provides for
cases when you might need more restrictive locking. For example, suppose an application
runs a transaction at the isolation level read committed and needs to ensure that data in a
table remains stable for the duration of the transaction. To achieve this you could obtain
SHARE lock mode over the table before querying. This will prevent concurrent data
changes and ensure subsequent reads of the table see a stable view of committed data,
because SHARE lock mode conflicts with the ROW EXCLUSIVE lock acquired by writers,
and your LOCK TABLE name IN SHARE MODE statement will wait until any concurrent
holders of ROW EXCLUSIVE mode locks commit or roll back. Thus, once you obtain the
lock, there are no uncommitted writes outstanding; furthermore none can begin until you
release the lock.
To achieve a similar effect when running a transaction at the isolation level serializable,
you have to execute the LOCK TABLE statement before executing any data modification
statement. A serializable transactions view of data will be frozen when its first data
modification statement begins. A later LOCK TABLE will still prevent concurrent writes -
but it wont ensure that what the transaction reads corresponds to the latest committed
values.
This ensures that only one transaction of this type runs at a time. Without this, a deadlock
is possible: two transactions might both acquire SHARE mode, and then be unable to also
acquire ROW EXCLUSIVE mode to actually perform their updates. (Note that a
transactions own locks never conflict, so a transaction can acquire ROW EXCLUSIVE
mode when it holds SHARE mode - but not if anyone else holds SHARE mode.) To avoid
deadlocks, make sure all transactions acquire locks on the same objects in the same order,
and if multiple lock modes are involved for a single object, then transactions should
always acquire the most restrictive mode first.
Parameters
name
lockmode
The lock mode specifies which locks this lock conflicts with.
If no lock mode is specified, then the server uses the most restrictive mode,
ACCESS EXCLUSIVE. (ACCESS EXCLUSIVE is not compatible with Oracle
databases. In Advanced Server, this configuration mode ensures that no other
transaction can access the locked table in any manner.)
NOWAIT
Specifies that LOCK TABLE should not wait for any conflicting locks to be
released: if the specified lock cannot be immediately acquired without waiting,
the transaction is aborted.
Notes
LOCK TABLE is useful only inside a transaction block since the lock is dropped as soon
as the transaction ends. A LOCK TABLE command appearing outside any transaction
block forms a self-contained transaction, so the lock will be dropped as soon as it is
obtained.
2.3.67 REVOKE
Name
Synopsis
Description
The REVOKE command revokes previously granted privileges from one or more roles.
The key word PUBLIC refers to the implicitly defined group of all roles.
See the description of the GRANT command for the meaning of the privilege types.
Note that any particular role will have the sum of privileges granted directly to it,
privileges granted to any role it is presently a member of, and privileges granted to
PUBLIC. Thus, for example, revoking SELECT privilege from PUBLIC does not
necessarily mean that all roles have lost SELECT privilege on the object: those who have
it granted directly or via another role will still have it.
If the privilege had been granted with the grant option, the grant option for the privilege
is revoked as well as the privilege, itself.
If a user holds a privilege with grant option and has granted it to other users then the
privileges held by those other users are called dependent privileges. If the privilege or the
grant option held by the first user is being revoked and dependent privileges exist, those
dependent privileges are also revoked if CASCADE is specified, else the revoke action will
fail. This recursive revocation only affects privileges that were granted through a chain of
users that is traceable to the user that is the subject of this REVOKE command. Thus, the
affected users may effectively keep the privilege if it was also granted through other
users.
Note: CASCADE is not an option compatible with Oracle databases. By default Oracle
always cascades dependent privileges, but Advanced Server requires the CASCADE
keyword to be explicitly given, otherwise the REVOKE command will fail.
When revoking membership in a role, GRANT OPTION is instead called ADMIN OPTION,
but the behavior is similar.
Notes
A user can only revoke privileges that were granted directly by that user. If, for example,
user A has granted a privilege with grant option to user B, and user B has in turned
granted it to user C, then user A cannot revoke the privilege directly from C. Instead, user
A could revoke the grant option from user B and use the CASCADE option so that the
privilege is in turn revoked from user C. For another example, if both A and B have
granted the same privilege to C, A can revoke his own grant but not Bs grant, so C will
still effectively have the privilege.
REVOKE can also be done by a role that is not the owner of the affected object, but is a
member of the role that owns the object, or is a member of a role that holds privileges
WITH GRANT OPTION on the object. In this case the command is performed as though it
were issued by the containing role that actually owns the object or holds the privileges
WITH GRANT OPTION. For example, if table t1 is owned by role g1, of which role u1 is
a member, then u1 can revoke privileges on t1 that are recorded as being granted by g1.
This would include grants made by u1 as well as by other members of role g1.
If the role executing REVOKE holds privileges indirectly via more than one role
membership path, it is unspecified which containing role will be used to perform the
command. In such cases it is best practice to use SET ROLE to become the specific role
you want to do the REVOKE as. Failure to do so may lead to revoking privileges other
than the ones you intended, or not revoking anything at all.
Please Note: The Advanced Server ALTER ROLE command also supports syntax that
revokes the system privileges required to create a public or private database link, or
exemptions from fine-grained access control policies (DBMS_RLS). The ALTER ROLE
syntax is functionally equivalent to the respective REVOKE command, compatible with
Oracle databases.
Examples
Note that this actually means revoke all privileges that I granted.
See Also
2.3.68 ROLLBACK
Name
Synopsis
ROLLBACK [ WORK ]
Description
ROLLBACK rolls back the current transaction and causes all the updates made by the
transaction to be discarded.
Parameters
WORK
Notes
Examples
ROLLBACK;
See Also
Name
Synopsis
Description
Roll back all commands that were executed after the savepoint was established. The
savepoint remains valid and can be rolled back to again later, if needed.
ROLLBACK TO SAVEPOINT implicitly destroys all savepoints that were established after
the named savepoint.
Parameters
savepoint_name
Notes
Examples
To undo the effects of the commands executed savepoint depts was established:
See Also
2.3.70 SAVEPOINT
Name
Synopsis
SAVEPOINT savepoint_name
Description
A savepoint is a special mark inside a transaction that allows all commands that are
executed after it was established to be rolled back, restoring the transaction state to what
it was at the time of the savepoint.
Parameters
savepoint_name
Notes
Savepoints can only be established when inside a transaction block. There can be
multiple savepoints defined within a transaction.
When another savepoint is established with the same name as a previous savepoint, the
old savepoint is kept, though only the more recent one will be used when rolling back.
Examples
To establish a savepoint and later undo the effects of all commands executed after it was
established:
The above transaction will commit a row into the dept table, but the inserts into the emp
and jobhist tables are rolled back.
See Also
2.3.71 SELECT
Name
Synopsis
table_name[@dblink ] [ alias ]
( select ) alias
from_item [ NATURAL ] join_type from_item
[ ON join_condition | USING ( join_column [, ...] ) ]
Description
SELECT retrieves rows from one or more tables. The general processing of SELECT is as
follows:
1. All elements in the FROM list are computed. (Each element in the FROM list is a
real or virtual table.) If more than one element is specified in the FROM list, they
are cross-joined together. (See FROM clause, below.)
2. If the WHERE clause is specified, all rows that do not satisfy the condition are
eliminated from the output. (See WHERE clause, below.)
3. If the GROUP BY clause is specified, the output is divided into groups of rows that
match on one or more values. If the HAVING clause is present, it eliminates groups
that do not satisfy the given condition. (See GROUP BY clause and HAVING clause
below.)
You must have SELECT privilege on a table to read its values. The use of FOR UPDATE
requires UPDATE privilege as well.
Parameters
optimizer_hint
The FROM clause specifies one or more source tables for a SELECT statement. The syntax
is:
table_name[@dblink ]
alias
A substitute name for the FROM item containing the alias. An alias is used for
brevity or to eliminate ambiguity for self-joins (where the same table is scanned
multiple times). When an alias is provided, it completely hides the actual name of
the table or function; for example given FROM foo AS f, the remainder of the
SELECT must refer to this FROM item as f not foo.
select
A sub-SELECT can appear in the FROM clause. This acts as though its output were
created as a temporary table for the duration of this single SELECT command.
Note that the sub-SELECT must be surrounded by parentheses, and an alias must
be provided for it.
join_type
[ INNNER ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
CROSS JOIN
For the INNER and OUTER join types, a join condition must be specified, namely
exactly one of NATURAL, ON join_condition, or USING (join_column [,
...] ). See below for the meaning. For CROSS JOIN, none of these clauses
may appear.
CROSS JOIN and INNER JOIN produce a simple Cartesian product, the same
result as you get from listing the two items at the top level of FROM, but restricted
by the join condition (if any). CROSS JOIN is equivalent to INNER JOIN ON
(TRUE), that is, no rows are removed by qualification. These join types are just a
notational convenience, since they do nothing you couldnt do with plain FROM
and WHERE.
Conversely, RIGHT OUTER JOIN returns all the joined rows, plus one row for
each unmatched right-hand row (extended with nulls on the left). This is just a
notational convenience, since you could convert it to a LEFT OUTER JOIN by
switching the left and right inputs.
FULL OUTER JOIN returns all the joined rows, plus one row for each unmatched
left-hand row (extended with nulls on the right), plus one row for each unmatched
right-hand row (extended with nulls on the left).
ON join_condition
NATURAL
NATURAL is shorthand for a USING list that mentions all columns in the two tables
that have the same names.
If multiple sources are specified, the result is the Cartesian product (cross join) of all the
sources. Usually qualification conditions are added to restrict the returned rows to a small
subset of the Cartesian product.
Example
The following example selects all of the entries from the dept table:
WHERE condition
where condition is any expression that evaluates to a result of type BOOLEAN. Any row
that does not satisfy this condition will be eliminated from the output. A row satisfies the
condition if it returns TRUE when the actual row values are substituted for any variable
references.
Example
The following example joins the contents of the emp and dept tables, WHERE the value of
the deptno column in the emp table is equal to the value of the deptno column in the
deptno table:
GROUP BY will condense into a single row all selected rows that share the same values
for the grouped expressions. expression can be an input column name, or the name or
ordinal number of an output column (SELECT list item), or an arbitrary expression
formed from input-column values. In case of ambiguity, a GROUP BY name will be
interpreted as an input-column name rather than an output column name.
ROLLUP, CUBE, and GROUPING SETS are extensions to the GROUP BY clause for
supporting multidimensional analysis. See Section 2.3.71.3 for information on using
these extensions.
Aggregate functions, if any are used, are computed across all rows making up each
group, producing a separate value for each group (whereas without GROUP BY, an
aggregate produces a single value computed across all the selected rows). When GROUP
BY is present, it is not valid for the SELECT list expressions to refer to ungrouped
columns except within aggregate functions, since there would be more than one possible
value to return for an ungrouped column.
Example
The following example computes the sum of the sal column in the emp table, grouping
the results by department number:
deptno | total
--------+----------
10 | 8750.00
20 | 10875.00
30 | 9400.00
(3 rows)
HAVING condition
HAVING eliminates group rows that do not satisfy the specified condition. HAVING is
different from WHERE; WHERE filters individual rows before the application of GROUP BY,
while HAVING filters group rows created by GROUP BY. Each column referenced in
Example
To sum the column, sal of all employees, group the results by department number and
show those group totals that are less than 10000:
deptno | total
--------+---------
10 | 8750.00
30 | 9400.00
(2 rows)
The SELECT list (between the key words SELECT and FROM) specifies expressions that
form the output rows of the SELECT statement. The expressions can (and usually do)
refer to columns computed in the FROM clause. Using the clause AS output_name,
another name can be specified for an output column. This name is primarily used to label
the column for display. It can also be used to refer to the columns value in ORDER BY
and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write
out the expression instead.
Instead of an expression, * can be written in the output list as a shorthand for all the
columns of the selected rows.
Example
The SELECT list in the following example specifies that the result set should include the
empno column, the ename column, the mgr column and the hiredate column:
The UNION operator computes the set union of the rows returned by the involved SELECT
statements. A row is in the set union of two result sets if it appears in at least one of the
result sets. The two SELECT statements that represent the direct operands of the UNION
must produce the same number of columns, and corresponding columns must be of
compatible data types.
The result of UNION does not contain any duplicate rows unless the ALL option is
specified. ALL prevents elimination of duplicates.
Multiple UNION operators in the same SELECT statement are evaluated left to right,
unless otherwise indicated by parentheses.
Currently, FOR UPDATE may not be specified either for a UNION result or for any input
of a UNION.
Multiple INTERSECT operators in the same SELECT statement are evaluated left to right,
unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION. That is,
A UNION B INTERSECT C will be read as A UNION (B INTERSECT C).
The MINUS operator computes the set of rows that are in the result of the left SELECT
statement but not in the result of the right one.
Multiple MINUS operators in the same SELECT statement are evaluated left to right,
unless parentheses dictate otherwise. MINUS binds at the same level as UNION.
The following optional clauses may be specified in conjunction with the CONNECT BY
clause:
Sibling rows of the hierarchy are ordered by expression in the result set.
Note: Advanced Server does not support the use of AND (or other operators) in the
CONNECT BY clause.
expression can be the name or ordinal number of an output column (SELECT list item),
or it can be an arbitrary expression formed from input-column values.
The ORDER BY clause causes the result rows to be sorted according to the specified
expressions. If two rows are equal according to the leftmost expression, they are
compared according to the next expression and so on. If they are equal according to all
specified expressions, they are returned in an implementation-dependent order.
The ordinal number refers to the ordinal (left-to-right) position of the result column. This
feature makes it possible to define an ordering on the basis of a column that does not
have a unique name. This is never absolutely necessary because it is always possible to
assign a name to a result column using the AS clause.
It is also possible to use arbitrary expressions in the ORDER BY clause, including columns
that do not appear in the SELECT result list. Thus the following statement is valid:
A limitation of this feature is that an ORDER BY clause applying to the result of a UNION,
INTERSECT, or MINUS clause may only specify an output column name or number, not
an expression.
If an ORDER BY expression is a simple name that matches both a result column name and
an input column name, ORDER BY will interpret it as the result column name. This is the
Optionally one may add the key word ASC (ascending) or DESC (descending) after any
expression in the ORDER BY clause. If not specified, ASC is assumed by default.
The null value sorts higher than any other value. In other words, with ascending sort
order, null values sort at the end, and with descending sort order, null values sort at the
beginning.
Character-string data is sorted according to the locale-specific collation order that was
established when the database cluster was initialized.
Examples
The following two examples are identical ways of sorting the individual results according
to the contents of the second column (dname):
If a SELECT statement specifies DISTINCT, all duplicate rows are removed from the
result set (one row is kept from each group of duplicates). The ALL keyword specifies
the opposite: all rows are kept; that is the default.
FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though
for update. This prevents a row from being modified or deleted by other transactions
until the current transaction ends; any transaction that attempts to UPDATE, DELETE, or
SELECT FOR UPDATE a selected row will be blocked until the current transaction ends.
If an UPDATE, DELETE, or SELECT FOR UPDATE from another transaction has already
locked a selected row or rows, SELECT FOR UPDATE will wait for the first transaction to
complete, and will then lock and return the updated row (or no row, if the row was
deleted).
FOR UPDATE cannot be used in contexts where returned rows cannot be clearly identified
with individual table rows (for example, with aggregation).
Include the WAIT n keywords to specify the number of seconds (or fractional
seconds) that the SELECT statement will wait for a row locked by another session.
Use a decimal form to specify fractional seconds; for example, WAIT 1.5
instructs the server to wait one and a half seconds. Specify up to 4 digits to the
right of the decimal.
Include SKIP LOCKED to instruct the server to lock rows if possible, and skip
rows that are already locked by another session.
Name
SET CONSTRAINTS -- set constraint checking modes for the current transaction
Synopsis
Description
SET CONSTRAINTS sets the behavior of constraint checking within the current
transaction. IMMEDIATE constraints are checked at the end of each statement. DEFERRED
constraints are not checked until transaction commit. Each constraint has its own
IMMEDIATE or DEFERRED mode.
SET CONSTRAINTS with a list of constraint names changes the mode of just those
constraints (which must all be deferrable). If there are multiple constraints matching any
given name, all are affected. SET CONSTRAINTS ALL changes the mode of all
deferrable constraints.
Currently, only foreign key constraints are affected by this setting. Check and unique
constraints are always effectively not deferrable.
This command only alters the behavior of constraints within the current transaction.
Thus, if you execute this command outside of a transaction block it will not appear to
have any effect.
Name
SET ROLE -- set the current user identifier of the current session
Synopsis
Description
This command sets the current user identifier of the current SQL session context to be
rolename. After SET ROLE, permissions checking for SQL commands is carried out as
though the named role were the one that had logged in originally.
The specified rolename must be a role that the current session user is a member of. (If
the session user is a superuser, any role can be selected.)
NONE resets the current user identifier to be the current session user identifier. These
forms may be executed by any user.
Notes
Using this command, it is possible to either add privileges or restrict ones privileges. If
the session user role has the INHERITS attribute, then it automatically has all the
privileges of every role that it could SET ROLE to; in this case SET ROLE effectively
drops all the privileges assigned directly to the session user and to the other roles it is a
member of, leaving only the privileges available to the named role. On the other hand, if
the session user role has the NOINHERITS attribute, SET ROLE drops the privileges
assigned directly to the session user and instead acquires the privileges available to the
named role. In particular, when a superuser chooses to SET ROLE to a non-superuser
role, she loses her superuser privileges.
Examples
Name
Synopsis
Description
The SET TRANSACTION command sets the characteristics of the current transaction. It
has no effect on any subsequent transactions. The available transaction characteristics are
the transaction isolation level and the transaction access mode (read/write or read-only).
The isolation level of a transaction determines what data the transaction can see when
other transactions are running concurrently:
READ COMMITTED
A statement can only see rows committed before it began. This is the default.
SERIALIZABLE
All statements of the current transaction can only see rows committed before the
first query or data-modification statement was executed in this transaction.
The transaction isolation level cannot be changed after the first query or data-
modification statement (SELECT, INSERT, DELETE, UPDATE, or FETCH) of a transaction
has been executed. The transaction access mode determines whether the transaction is
read/write or read-only. Read/write is the default.
When a transaction is read-only, the following SQL commands are disallowed: INSERT,
UPDATE, and DELETE if the table they would write to is not a temporary table; all
CREATE, ALTER, and DROP commands; COMMENT, GRANT, REVOKE, TRUNCATE; and
EXECUTE if the command it would execute is among those listed. This is a high-level
notion of read-only that does not prevent all writes to disk.
2.3.75 TRUNCATE
Name
Synopsis
Description
TRUNCATE quickly removes all rows from a table. It has the same effect as an unqualified
DELETE but since it does not actually scan the table, it is faster. This is most useful on
large tables.
Parameters
name
Notes
TRUNCATE cannot be used if there are foreign-key references to the table from other
tables. Checking validity in such cases would require table scans, and the whole point is
not to do one.
TRUNCATE will not run any user-defined ON DELETE triggers that might exist for the
table.
Examples
See Also
2.3.76 UPDATE
Name
Synopsis
Description
UPDATE changes the values of the specified columns in all rows that satisfy the condition.
Only the columns to be modified need be mentioned in the SET clause; columns not
explicitly modified retain their previous values.
The RETURNING BULK COLLECT INTO collection [, ...] clause may only be
specified if the UPDATE command is used within an SPL program. If more than one
collection is specified as the target of the BULK COLLECT INTO clause, then each
collection must consist of a single, scalar field i.e., collection must not be a
record. The result set of the UPDATE command may contain none, one, or more rows.
return_expression evaluated for each row of the result set, becomes an element in
collection starting with the first element. Any existing rows in collection are
deleted. If the result set is empty, then collection will be empty.
You must have the UPDATE privilege on the table to update it, as well as the SELECT
privilege to any table whose values are read in expression or condition.
Parameters
optimizer_hint
dblink
Database link name identifying a remote database. See the CREATE DATABASE
LINK command for information on database links.
column
expression
An expression to assign to the column. The expression may use the old values of
this and other columns in the table.
DEFAULT
Set the column to its default value (which will be null if no specific default
expression has been assigned to it).
condition
An expression that returns a value of type BOOLEAN. Only rows for which this
expression returns true will be updated.
return_expression
An expression that may include one or more columns from table. If a column
name from table is specified in return_expression, the value substituted for
the column when return_expression is evaluated is determined as follows:
record
variable
collection
Examples
For all employees with job = SALESMAN in the emp table, update the salary by 10% and
increase the commission by 500.
UPDATE emp SET sal = sal * 1.1, comm = comm + 500 WHERE job = 'SALESMAN';
SQL uses a three-valued Boolean logic where the null value represents "unknown".
Observe the following truth tables:
The operators AND and OR are commutative, that is, you can switch the left and right
operand without affecting the result.
Comparison operators are available for all data types where this makes sense. All
comparison operators are binary operators that return values of type BOOLEAN;
expressions like 1 < 2 < 3 are not valid (because there is no < operator to compare a
Boolean value with 3).
a BETWEEN x AND y
is equivalent to
Similarly,
is equivalent to
a < x OR a > y
There is no difference between the two respective forms apart from the CPU cycles
required to rewrite the first one into the second one internally.
expression IS NULL
expression IS NOT NULL
Some applications may expect that expression = NULL returns true if expression
evaluates to the null value. It is highly recommended that these applications be modified
to comply with the SQL standard.
Mathematical operators are provided for many Advanced Server types. For types without
common mathematical conventions for all possible permutations (e.g., date/time types)
the actual behavior is described in subsequent sections.
This behavior is compatible with Oracle databases where there is no native INTEGER data
type, and any INTEGER data type specification is internally converted to NUMBER(38),
which results in retaining any fractional result.
This behavior is compatible with PostgreSQL databases where division involving any
pair of INTEGER, SMALLINT, or BIGINT data types results in truncation of the result.
The same truncated result is returned by Advanced Server when db_dialect is set to
postgres as shown in the previous example.
Note however, that even when db_dialect is set to redwood, only division with a pair
of INTEGER data types results in no truncation of the result. Division that includes only
SMALLINT or BIGINT data types, with or without an INTEGER data type, does result in
truncation in the PostgreSQL fashion without retaining the fractional portion as shown by
the following where INTEGER and SMALLINT are involved in the division:
The following table shows the available mathematical functions. Many of these functions
are provided in multiple forms with different argument types. Except where noted, any
given form of a function returns the same data type as its argument. The functions
working with DOUBLE PRECISION data are mostly implemented on top of the host
systems C library; accuracy and behavior in boundary cases may therefore vary
depending on the host system.
TRUNC(v NUMBER, s
NUMBER
Truncate to s decimal TRUNC(42.4382, 2) 42.43
INTEGER) places
Return the bucket to
which op would be
WIDTH_BUCKET(op
assigned in an WIDTH_BUCKET(5.35,
NUMBER, b1 NUMBER, b2 INTEGER 3
NUMBER, count INTEGER) equidepth histogram 0.024, 10.06, 5)
with count buckets,
in the range b1 to b2
The following table shows the available trigonometric functions. All trigonometric
functions take arguments and return values of type DOUBLE PRECISION.
This section describes functions and operators for examining and manipulating string
values. Strings in this context include values of the types CHAR, VARCHAR2, and CLOB.
Unless otherwise noted, all of the functions listed below work on all of these types, but be
wary of potential effects of automatic padding when using the CHAR type. Generally, the
functions described here also work on data of non-string types by converting that data to
a string representation first.
Additional string manipulation functions are available and are listed in the following
table. Some of them are used internally to implement the SQL-standard string functions
listed in Table 2-17.
LENGTHC
functionality to LENGTH; the
function name is supported
for compatibility.
INTEGER This function is identical in LENGTH2('Cte d''Azur') 11
LENGTH2
functionality to LENGTH; the
function name is supported
for compatibility.
INTEGER This function is identical in LENGTH4('Cte d''Azur') 11
LENGTH4
functionality to LENGTH; the
function name is supported
for compatibility.
INTEGER Returns the number of bytes LENGTHB('Cte d''Azur') 12
LENGTHB required to hold the given
value.
Fill up string to size,
length by prepending the
characters, fill (a space by
LPAD(string, length
CLOB default). If string is LPAD('hi', 5, 'xy') xyxhi
INTEGER [, fill ])
already longer than length
then it is truncated (on the
right).
Replaces one value in a
string with another. If you
REPLACE(string,
do not specify a value for REPLACE( 'GEORGE',
search_string [, CLOB EGOREG
replace_string, the 'GE', 'EG')
replace_string ]
search_string value
when found, is removed.
Fill up string to size,
length by appending the
RPAD(string, length
CLOB
characters, fill (a space by RPAD('hi', 5, 'xy') hixyx
INTEGER [, fill ]) default). If string is
already longer than length
then it is truncated.
Any character in string
that matches a character in
TRANSLATE(string, from, TRANSLATE('12345',
to)
CLOB the from set is replaced by '14', 'ax')
a23x5
the corresponding character
in the to set.
https://www.postgresql.org/docs/10/static/functions-matching.html
2.4.5.1 REGEXP_COUNT
REGEXP_COUNT searches a string for a regular expression, and returns a count of the
times that the regular expression occurs. The signature is:
INTEGER REGEXP_COUNT
(
srcstr TEXT,
pattern TEXT,
position DEFAULT 1
modifier DEFAULT NULL
)
Parameters
srcstr
pattern
pattern specifies the regular expression for which REGEXP_COUNT will search.
position
position is an integer value that indicates the position in the source string at
which REGEXP_COUNT will begin searching. The default value is 1.
modifier specifies values that control the pattern matching behavior. The
default value is NULL. For a complete list of the modifiers supported by
Advanced Server, see the PostgreSQL core documentation available at:
https://www.postgresql.org/docs/10/static/functions-matching.html
Example
In the following simple example, REGEXP_COUNT returns a count of the number of times
the letter i is used in the character string 'reinitializing':
In the first example, the command instructs REGEXP_COUNT begins counting in the first
position; if we modify the command to start the count on the 6th position:
REGEXP_COUNT returns 3; the count now excludes any occurrences of the letter i that
occur before the 6th position.
2.4.5.2 REGEXP_INSTR
INTEGER REGEXP_INSTR
(
srcstr TEXT,
pattern TEXT,
position INT DEFAULT 1,
occurrence INT DEFAULT 1,
returnparam INT DEFAULT 0,
modifier TEXT DEFAULT NULL,
subexpression INT DEFAULT 0,
)
srcstr
pattern
pattern specifies the regular expression for which REGEXP_INSTR will search.
position
position specifies an integer value that indicates the start position in a source
string. The default value is 1.
occurrence
returnparam
returnparam is an integer value that specifies the location within the string that
REGEXP_INSTR should return. The default value is 0. Specify:
0 to return the location within the string of the first character that matches
pattern.
modifier
modifier specifies values that control the pattern matching behavior. The
default value is NULL. For a complete list of the modifiers supported by
Advanced Server, see the PostgreSQL core documentation available at:
https://www.postgresql.org/docs/10/static/functions-matching.html
subexpression
Example
In the following simple example, REGEXP_INSTR searches a string that contains the a
phone number for the first occurrence of a pattern that contains three consecutive digits:
The command instructs REGEXP_INSTR to return the position of the first occurrence. If
we modify the command to return the start of the second occurrence of three consecutive
digits:
REGEXP_INSTR returns 5; the second occurrence of three consecutive digits begins in the
5th position.
2.4.5.3 REGEXP_SUBSTR
TEXT REGEXP_SUBSTR
(
srcstr TEXT,
pattern TEXT,
position INT DEFAULT 1,
occurrence INT DEFAULT 1,
modifier TEXT DEFAULT NULL,
subexpression INT DEFAULT 0
)
srcstr
pattern
pattern specifies the regular expression for which REGEXP_SUBSTR will search.
position
position specifies an integer value that indicates the start position in a source
string. The default value is 1.
occurrence
modifier
modifier specifies values that control the pattern matching behavior. The
default value is NULL. For a complete list of the modifiers supported by
Advanced Server, see the PostgreSQL core documentation available at:
https://www.postgresql.org/docs/10/static/functions-matching.html
subexpression
If you specify a value for subexpression, you must include one (or more) set
of parentheses in the pattern that isolate a portion of the value being searched
for. The value specified by subexpression indicates which set of parentheses
should be returned; for example, if subexpression is 2, REGEXP_SUBSTR will
return the value contained within the second set of parentheses.
Example
It locates the first occurrence of three digits and returns the string (800); if we modify the
command to check for the second occurrence of three consecutive digits:
Advanced Server provides pattern matching using the traditional SQL LIKE operator.
The syntax for the LIKE operator is as follows.
Every pattern defines a set of strings. The LIKE expression returns TRUE if string is
contained in the set of strings represented by pattern. As expected, the NOT LIKE
expression returns FALSE if LIKE returns TRUE, and vice versa. An equivalent expression
is NOT (string LIKE pattern).
If pattern does not contain percent signs or underscore, then the pattern only represents
the string itself; in that case LIKE acts like the equals operator. An underscore (_) in
pattern stands for (matches) any single character; a percent sign (%) matches any string
of zero or more characters.
Some examples:
LIKE pattern matches always cover the entire string. To match a pattern anywhere within
a string, the pattern must therefore start and end with a percent sign.
To match a literal underscore or percent sign without matching other characters, the
respective character in pattern must be preceded by the escape character. The default
escape character is the backslash but a different one may be selected by using the
ESCAPE clause. To match the escape character itself, write two escape characters.
Note that the backslash already has a special meaning in string literals, so to write a
pattern constant that contains a backslash you must write two backslashes in an SQL
statement. Thus, writing a pattern that actually matches a literal backslash means writing
four backslashes in the statement. You can avoid this by selecting a different escape
character with ESCAPE; then a backslash is not special to LIKE anymore. (But it is still
special to the string literal parser, so you still need two of them.)
Its also possible to select no escape character by writing ESCAPE ''. This effectively
disables the escape mechanism, which makes it impossible to turn off the special
meaning of underscore and percent signs in the pattern.
The Advanced Server formatting functions described in the following table provide a
powerful set of tools for converting various data types (date/time, integer, floating point,
numeric) to formatted strings and for converting from formatted strings to specific data
types. These functions all follow a common calling convention: the first argument is the
value to be formatted and the second argument is a string template that defines the output
or input format.
In an output template string (for TO_CHAR), there are certain patterns that are recognized
and replaced with appropriately-formatted data from the value to be formatted. Any text
that is not a template pattern is simply copied verbatim. Similarly, in an input template
The following table shows the template patterns available for formatting date values
using the TO_CHAR and TO_DATE functions.
If the given 2-digit year is >= 50 and the last 2 digits of the current year is < 50, then the first
2 digits for the given year is 1 less than the first 2 digits of the current year.
Only affects TO_DATE function. Allows specification of 2-digit or 4-digit year. If 2-digit
RRRR year given, then returns first 2 digits of year like RR format. If 4-digit year given, returns the
given 4-digit year.
Certain modifiers may be applied to any template pattern to alter its behavior. For
example, FMMonth is the Month pattern with the FM modifier. The following table shows
the modifier patterns for date/time formatting.
FM suppresses leading zeroes and trailing blanks that would otherwise be added to
make the output of a pattern fixed-width.
TO_TIMESTAMP and TO_DATE skip multiple blank spaces in the input string if the
FX option is not used. FX must be specified as the first item in the template. For
example TO_TIMESTAMP('2000 JUN', 'YYYY MON') is correct, but
The following table shows the template patterns available for formatting numeric values.
9 results in a value with the same number of digits as there are 9s. If a digit is not
available it outputs a space.
TH does not convert values less than zero and does not convert fractional
numbers.
V effectively multiplies the input values by 10n, where n is the number of digits following
V. TO_CHAR does not support the use of V combined with a decimal point. (E.g.,
99.9V99 is not allowed.)
The following table shows some examples of the use of the TO_CHAR and TO_DATE
functions.
There are certain cases of the TO_CHAR function that can result in usage of an
IMMUTABLE form of the function. Basically, a function is IMMUTABLE if the function
does not modify the database, and the function returns the same, consistent value
dependent upon only its input parameters. That is, the settings of configuration
parameters, the locale, the content of the database, etc. do not affect the results returned
by the function.
For more information about function volatility categories VOLATILE, STABLE, and
IMMUTABLE, please see the PostgreSQL Core documentation at:
https://www.postgresql.org/docs/10/static/xfunc-volatility.html
In order for the TO_CHAR function to use the IMMUTABLE form the following conditions
must be satisfied:
The first parameter of the TO_CHAR function must be of data type TIMESTAMP.
Format patterns that result in a non-immutable function include any variations of spelled
out or abbreviated months (MONTH, MON), days (DAY, DY), median indicators (AM, PM), or
era indicators (BC, AD).
The following shows the successful creation of an index with the IMMUTABLE form of the
TO_CHAR function.
The following results in an error because the format specified in the TO_CHAR function
prevents the use of the IMMUTABLE form since the 3-character month abbreviation, MON,
may result in different return values based on the locale setting.
Table 2-25 shows the available functions for date/time value processing, with details
appearing in the following subsections. The following table illustrates the behaviors of
the basic arithmetic operators (+, -). For formatting functions, refer to Section 2.4.7. You
should be familiar with the background information on date/time data types from Section
2.2.4.
In the date/time functions of the following table the use of the DATE and TIMESTAMP
data types are interchangeable.
Converts a number to a
SELECT
NUMTODSINTERVAL(NUMB specified day or second 4 days
INTERVAL numtodsinterval(100,
ER, INTERVAL) interval; see Section 04:00:00
hour);
2.4.8.9.
Converts a number to a
SELECT
NUMTOYMINTERVAL(NUMB specified year or month 8 years 4
INTERVAL numtoyminterval(100,
ER, INTERVAL) interval; see Section mons
month);
2.4.8.10.
Date rounded according to
ROUND(DATE [, format ROUND(TO_DATE('29-MAY- 01-JUN-05
])
DATE format; see Section 05'),'MON') 00:00:00
2.4.8.6
SYS_EXTRACT_UTC(CAST('24
SYS_EXTRACT_UTC(TIME
STAMP WITH TIME TIMESTAMP
Returns Coordinated -MAR-11 12:30:00PM - 24-MAR-11
Universal Time 04:00' AS TIMESTAMP WITH 16:30:00
ZONE)
TIME ZONE))
Returns current date and 01-AUG-12
SYSDATE DATE SYSDATE
time 11:12:34
01-AUG-12
Returns current date and
SYSTIMESTAMP() TIMESTAMP SYSTIMESTAMP 11:11:23.665
time 229 -07:00
Truncate according to 01-MAY-05
TRUNC(TO_DATE('29-MAY-
TRUNC(DATE [format]) DATE format; see Section 05'), 'MON')
2.4.8.7 00:00:00
2.4.8.1 ADD_MONTHS
The ADD_MONTHS functions adds (or subtracts if the second parameter is negative) the
specified number of months to the given date. The resulting day of the month is the same
as the day of the month of the given date except when the day is the last day of the month
in which case the resulting date always falls on the last day of the month.
Any fractional portion of the number of months parameter is truncated before performing
the calculation.
If the given date contains a time portion, it is carried forward to the result unchanged.
add_months
--------------------
13-OCT-07 00:00:00
add_months
--------------------
28-FEB-07 00:00:00
(1 row)
add_months
--------------------
29-FEB-04 00:00:00
(1 row)
2.4.8.2 EXTRACT
The EXTRACT function retrieves subfields such as year or hour from date/time values.
The EXTRACT function returns values of type DOUBLE PRECISION. The following are
valid field names:
YEAR
date_part
-----------
2001
(1 row)
MONTH
date_part
-----------
2
(1 row)
DAY
date_part
-----------
16
(1 row)
date_part
-----------
20
(1 row)
MINUTE
date_part
-----------
38
(1 row)
SECOND
date_part
-----------
40
(1 row)
2.4.8.3 MONTHS_BETWEEN
The MONTHS_BETWEEN function returns the number of months between two dates. The
result is a numeric value which is positive if the first date is greater than the second date
or negative if the first date is less than the second date.
The result is always a whole number of months if the day of the month of both date
parameters is the same, or both date parameters fall on the last day of their respective
months.
months_between
----------------
2
(1 row)
months_between
----------------
-2
(1 row)
months_between
----------------
0.967741935
(1 row)
months_between
----------------
12
(1 row)
2.4.8.4 NEXT_DAY
The NEXT_DAY function returns the first occurrence of the given weekday strictly greater
than the given date. At least the first three letters of the weekday must be specified - e.g.,
SAT. If the given date contains a time portion, it is carried forward to the result
unchanged.
next_day
--------------------
19-AUG-07 00:00:00
(1 row)
next_day
--------------------
20-AUG-07 00:00:00
(1 row)
2.4.8.5 NEW_TIME
The NEW_TIME function converts a date and time from one time zone to another.
NEW_TIME returns a value of type DATE. The syntax is:
2.4.8.6 ROUND
The ROUND function returns a date rounded according to a specified template pattern. If
the template pattern is omitted, the date is rounded to the nearest day. The following table
shows the template patterns for the ROUND function.
Century
-------------
01-JAN-1901
(1 row)
Century
-------------
01-JAN-2001
(1 row)
SELECT TO_CHAR(ROUND(TO_DATE('30-JUN-1999','DD-MON-YYYY'),'Y'),'DD-MON-YYYY')
"Year" FROM DUAL;
Year
-------------
01-JAN-1999
(1 row)
SELECT TO_CHAR(ROUND(TO_DATE('01-JUL-1999','DD-MON-YYYY'),'Y'),'DD-MON-YYYY')
"Year" FROM DUAL;
The following examples round to the nearest ISO year. The first example rounds to 2004
and the ISO year for 2004 begins on December 29th of 2003. The second example rounds
to 2005 and the ISO year for 2005 begins on January 3rd of that same year.
(An ISO year begins on the first Monday from which a 7 day span, Monday thru Sunday,
contains at least 4 days of the new year. Thus, it is possible for the beginning of an ISO
year to start in December of the prior year.)
SELECT TO_CHAR(ROUND(TO_DATE('30-JUN-2004','DD-MON-YYYY'),'IYYY'),'DD-MON-
YYYY') "ISO Year" FROM DUAL;
ISO Year
-------------
29-DEC-2003
(1 row)
SELECT TO_CHAR(ROUND(TO_DATE('01-JUL-2004','DD-MON-YYYY'),'IYYY'),'DD-MON-
YYYY') "ISO Year" FROM DUAL;
ISO Year
-------------
03-JAN-2005
(1 row)
Quarter
--------------------
01-JAN-07 00:00:00
(1 row)
Quarter
--------------------
01-APR-07 00:00:00
(1 row)
Month
--------------------
01-DEC-07 00:00:00
(1 row)
The following examples round to the nearest week. The first day of 2007 lands on a
Monday so in the first example, January 18th is closest to the Monday that lands on
January 15th. In the second example, January 19th is closer to the Monday that falls on
January 22nd.
Week
--------------------
15-JAN-07 00:00:00
(1 row)
Week
--------------------
22-JAN-07 00:00:00
(1 row)
The following examples round to the nearest ISO week. An ISO week begins on a
Monday. In the first example, January 1, 2004 is closest to the Monday that lands on
December 29, 2003. In the second example, January 2, 2004 is closer to the Monday that
lands on January 5, 2004.
ISO Week
--------------------
29-DEC-03 00:00:00
(1 row)
ISO Week
--------------------
05-JAN-04 00:00:00
(1 row)
The following examples round to the nearest week where a week is considered to start on
the same day as the first day of the month.
Week
--------------------
08-MAR-07 00:00:00
(1 row)
Week
--------------------
Day
--------------------
04-AUG-07 00:00:00
(1 row)
Day
--------------------
05-AUG-07 00:00:00
(1 row)
The following examples round to the start of the nearest day of the week (Sunday).
Day of Week
--------------------
05-AUG-07 00:00:00
(1 row)
Day of Week
--------------------
12-AUG-07 00:00:00
(1 row)
Hour
--------------------
09-AUG-07 08:00:00
(1 row)
Hour
--------------------
09-AUG-07 09:00:00
(1 row)
Minute
--------------------
09-AUG-07 08:30:00
(1 row)
Minute
--------------------
09-AUG-07 08:31:00
(1 row)
2.4.8.7 TRUNC
The TRUNC function returns a date truncated according to a specified template pattern. If
the template pattern is omitted, the date is truncated to the nearest day. The following
table shows the template patterns for the TRUNC function.
WW
Returns the largest date just prior to, or the same as the given date that corresponds
to the same day of the week as the first day of the year
IW Returns the start of the ISO week containing the given date
W
Returns the largest date just prior to, or the same as the given date that corresponds
to the same day of the week as the first day of the month
DDD, DD, J Returns the start of the day for the given date
DAY, DY, D Returns the start of the week (Sunday) containing the given date
HH, HH12, HH24 Returns the start of the hour
MI Returns the start of the minute
Century
-------------
01-JAN-1901
SELECT TO_CHAR(TRUNC(TO_DATE('01-JUL-1999','DD-MON-YYYY'),'Y'),'DD-MON-YYYY')
"Year" FROM DUAL;
Year
-------------
01-JAN-1999
(1 row)
The following example truncates down to the beginning of the ISO year.
SELECT TO_CHAR(TRUNC(TO_DATE('01-JUL-2004','DD-MON-YYYY'),'IYYY'),'DD-MON-
YYYY') "ISO Year" FROM DUAL;
ISO Year
-------------
29-DEC-2003
(1 row)
The following example truncates down to the start date of the quarter.
Quarter
--------------------
01-JAN-07 00:00:00
(1 row)
Month
--------------------
01-DEC-07 00:00:00
(1 row)
The following example truncates down to the start of the week determined by the first
day of the year. The first day of 2007 lands on a Monday so the Monday just prior to
January 19th is January 15th.
Week
--------------------
15-JAN-07 00:00:00
(1 row)
ISO Week
--------------------
29-DEC-03 00:00:00
(1 row)
The following example truncates to the start of the week where a week is considered to
start on the same day as the first day of the month.
Week
--------------------
15-MAR-07 00:00:00
(1 row)
Day
--------------------
04-AUG-07 00:00:00
(1 row)
Day of Week
--------------------
05-AUG-07 00:00:00
(1 row)
Hour
--------------------
09-AUG-07 08:00:00
(1 row)
CURRENT_DATE
CURRENT_TIMESTAMP
LOCALTIMESTAMP
LOCALTIMESTAMP(precision)
CURRENT_DATE returns the current date and time based on the start time of the current
transaction. The value of CURRENT_DATE will not change if called multiple times within
a transaction.
date
-----------
06-AUG-07
CURRENT_TIMESTAMP returns the current date and time. When called from a single SQL
statement, it will return the same value for each occurrence within the statement. If
called from multiple statements within a transaction, may return different values for each
occurrence. If called from a function, may return a different value than the value
returned by current_timestamp in the caller.
current_timestamp | current_timestamp
----------------------------------+----------------------------------
02-SEP-13 17:52:29.261473 +05:00 | 02-SEP-13 17:52:29.261474 +05:00
LOCALTIMESTAMP can optionally be given a precision parameter which causes the result
to be rounded to that many fractional digits in the seconds field. Without a precision
parameter, the result is given to the full available precision.
timestamp
------------------------
06-AUG-07 16:11:35.973
(1 row)
Since these functions return the start time of the current transaction, their values do not
change during the transaction. This is considered a feature: the intent is to allow a single
transaction to have a consistent notion of the current time, so that multiple
modifications within the same transaction bear the same time stamp. Other database
systems may advance these values more frequently.
2.4.8.9 NUMTODSINTERVAL
The following example converts a numeric value to a time interval that includes days and
hours:
The following example converts a numeric value to a time interval that includes minutes
and seconds:
2.4.8.10 NUMTOYMINTERVAL
The following example converts a numeric value to a time interval that includes years
and months:
The following example converts a numeric value to a time interval that includes years
only:
This section describes Advanced Servers functions for operating on sequence objects.
Sequence objects (also called sequence generators or just sequences) are special single-
row tables created with the CREATE SEQUENCE command. A sequence object is usually
used to generate unique identifiers for rows of a table. The sequence functions, listed
below, provide simple, multiuser-safe methods for obtaining successive sequence values
from sequence objects.
sequence.NEXTVAL
sequence.CURRVAL
NEXTVAL
Advance the sequence object to its next value and return that value. This is done
atomically: even if multiple sessions execute NEXTVAL concurrently, each will
safely receive a distinct sequence value.
CURRVAL
Return the value most recently obtained by NEXTVAL for this sequence in the
current session. (An error is reported if NEXTVAL has never been called for this
sequence in this session.) Notice that because this is returning a session-local
value, it gives a predictable answer whether or not other sessions have executed
NEXTVAL since the current session did.
If a sequence object has been created with default parameters, NEXTVAL calls on it will
return successive values beginning with 1. Other behaviors can be obtained by using
special parameters in the CREATE SEQUENCE command.
Important: To avoid blocking of concurrent transactions that obtain numbers from the
same sequence, a NEXTVAL operation is never rolled back; that is, once a value has been
fetched it is considered used, even if the transaction that did the NEXTVAL later aborts.
This means that aborted transactions may leave unused "holes" in the sequence of
assigned values.
2.4.10.1 CASE
An example:
a
---
1
2
3
(3 rows)
SELECT a,
CASE WHEN a=1 THEN 'one'
WHEN a=2 THEN 'two'
ELSE 'other'
END
FROM test;
a | case
---+-------
1 | one
2 | two
3 | other
(3 rows)
The data types of all the result expressions must be convertible to a single output type.
CASE expression
WHEN value THEN result
[ WHEN ... ]
[ ELSE result ]
END
The expression is computed and compared to all the value specifications in the WHEN
clauses until one is found that is equal. If no match is found, the result in the ELSE
clause (or a null value) is returned.
The example above can be written using the simple CASE syntax:
SELECT a,
CASE a WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'other'
END
FROM test;
a | case
---+-------
1 | one
2 | two
3 | other
(3 rows)
A CASE expression does not evaluate any subexpressions that are not needed to determine
the result. For example, this is a possible way of avoiding a division-by-zero failure:
SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
2.4.10.2 COALESCE
The COALESCE function returns the first of its arguments that is not null. Null is returned
only if all arguments are null.
It is often used to substitute a default value for null values when data is retrieved for
display or further computation. For example:
Like a CASE expression, COALESCE will not evaluate arguments that are not needed to
determine the result; that is, arguments to the right of the first non-null argument are not
evaluated. This SQL-standard function provides capabilities similar to NVL and IFNULL,
which are used in some other database systems.
The NULLIF function returns a null value if value1 and value2 are equal; otherwise it
returns value1.
NULLIF(value1, value2)
This can be used to perform the inverse operation of the COALESCE example given
above:
2.4.10.4 NVL
The NVL function returns the first of its arguments that is not null. NVL evaluates the first
expression; if that expression evaluates to NULL, NVL returns the second expression.
NVL(expr1, expr2)
The return type is the same as the argument types; all arguments must have the same data
type (or be coercible to a common type). NVL returns NULL if all arguments are NULL.
2.4.10.5 NVL2
NVL2 evaluates an expression, and returns either the second or third expression,
depending on the value of the first expression. If the first expression is not NULL, NVL2
returns the value in expr2; if the first expression is NULL, NVL2 returns the value in
expr3.
The return type is the same as the argument types; all arguments must have the same data
type (or be coercible to a common type).
The GREATEST and LEAST functions select the largest or smallest value from a list of any
number of expressions.
The expressions must all be convertible to a common data type, which will be the type of
the result. Null values in the list are ignored. The result will be null only if all the
expressions evaluate to null.
Note that GREATEST and LEAST are not in the SQL standard, but are a common
extension.
Aggregate functions compute a single result value from a set of input values. The built-in
aggregate functions are listed in the following tables.
It should be noted that except for COUNT, these functions return a null value when no
rows are selected. In particular, SUM of no rows returns null, not zero as one might
expect. The COALESCE function may be used to substitute zero for null when necessary.
The following table shows the aggregate functions typically used in statistical analysis.
(These are separated out merely to avoid cluttering the listing of more-commonly-used
aggregates.) Where the description mentions N, it means the number of input rows for
which all the input expressions are non-null. In all cases, null is returned if the
computation is meaningless, for example when N is zero.
2.4.12.1 EXISTS
EXISTS(subquery)
The subquery can refer to variables from the surrounding query, which will act as
constants during any one evaluation of the subquery.
The subquery will generally only be executed far enough to determine whether at least
one row is returned, not all the way to completion. It is unwise to write a subquery that
has any side effects (such as calling sequence functions); whether the side effects occur
or not may be difficult to predict.
Since the result depends only on whether any rows are returned, and not on the contents
of those rows, the output list of the subquery is normally uninteresting. A common
coding convention is to write all EXISTS tests in the form EXISTS(SELECT 1 WHERE
...). There are exceptions to this rule however, such as subqueries that use INTERSECT.
This simple example is like an inner join on deptno, but it produces at most one output
row for each dept row, even though there are multiple matching emp rows:
SELECT dname FROM dept WHERE EXISTS (SELECT 1 FROM emp WHERE emp.deptno =
dept.deptno);
dname
------------
ACCOUNTING
RESEARCH
SALES
(3 rows)
2.4.12.2 IN
The right-hand side is a parenthesized subquery, which must return exactly one column.
The left-hand expression is evaluated and compared to each row of the subquery result.
expression IN (subquery)
Note that if the left-hand expression yields NULL, or if there are no equal right-hand
values and at least one right-hand row yields NULL, the result of the IN construct will be
NULL, not FALSE. This is in accordance with SQLs normal rules for Boolean
combinations of null values.
As with EXISTS, its unwise to assume that the subquery will be evaluated completely.
2.4.12.3 NOT IN
The right-hand side is a parenthesized subquery, which must return exactly one column.
The left-hand expression is evaluated and compared to each row of the subquery result.
The result of NOT IN is TRUE if only unequal subquery rows are found (including the
special case where the subquery returns no rows). The result is FALSE if any equal row is
found.
Note that if the left-hand expression yields NULL, or if there are no equal right-hand
values and at least one right-hand row yields NULL, the result of the NOT IN construct
will be NULL, not TRUE. This is in accordance with SQLs normal rules for Boolean
combinations of null values.
As with EXISTS, its unwise to assume that the subquery will be evaluated completely.
2.4.12.4 ANY/SOME
The right-hand side is a parenthesized subquery, which must return exactly one column.
The left-hand expression is evaluated and compared to each row of the subquery result
using the given operator, which must yield a Boolean result. The result of ANY is TRUE if
any true result is obtained. The result is FALSE if no true result is found (including the
special case where the subquery returns no rows).
As with EXISTS, its unwise to assume that the subquery will be evaluated completely.
2.4.12.5 ALL
The right-hand side is a parenthesized subquery, which must return exactly one column.
The left-hand expression is evaluated and compared to each row of the subquery result
using the given operator, which must yield a Boolean result. The result of ALL is TRUE if
all rows yield true (including the special case where the subquery returns no rows). The
result is FALSE if any false result is found. The result is NULL if the comparison does not
return FALSE for any row, and it returns NULL for at least one row.
NOT IN is equivalent to <> ALL. As with EXISTS, its unwise to assume that the
subquery will be evaluated completely.
3.1 ALL_ALL_TABLES
The ALL_ALL_TABLES view provides information about the tables accessible by the
current user.
3.2 ALL_CONS_COLUMNS
3.4 ALL_DB_LINKS
The ALL_DB_LINKS view provides information about the database links accessible by
the current user.
The ALL_DIRECTORIES view provides information about all directories created with the
CREATE DIRECTORY command.
3.6 ALL_IND_COLUMNS
3.7 ALL_INDEXES
The ALL_INDEXES view provides information about the indexes on tables that may be
accessed by the current user.
3.8 ALL_JOBS
The ALL_JOBS view provides information about all jobs that reside in the database.
The ALL_OBJECTS view provides information about all objects that reside in the
database.
3.10 ALL_PART_KEY_COLUMNS
The ALL_PART_KEY_COLUMNS view provides information about the key columns of the
partitioned tables that reside in the database.
The ALL_PART_TABLES view provides information about all of the partitioned tables
that reside in the database.
The ALL_POLICIES view provides information on all policies in the database. This view
is accessible only to superusers.
3.13 ALL_QUEUES
The ALL_QUEUES view provides information about any currently defined queues.
retention
CHARACTER The number of seconds that a processed message is retained in
VARYING the queue.
CHARACTER
user_comment
VARYING A user-specified comment.
CHARACTER
network_name
VARYING The name of the network on which the queue resides.
CHARACTER YES if the queue resides on a sharded network; NO if the queue
sharded
VARYING does not.
3.14 ALL_QUEUE_TABLES
The ALL_QUEUE_TABLES view provides information about all of the queue tables in the
database.
cache_size NUMERIC
The number of pre-allocated sequence numbers stored in
memory.
last_number NUMERIC The value of the last sequence number saved to disk.
3.16 ALL_SOURCE
The ALL_SOURCE view provides a source code listing of the following program types:
functions, procedures, triggers, package specifications, and package bodies.
3.18 ALL_SYNONYMS
The ALL_SYNONYMS view provides information on all synonyms that may be referenced
by the current user.
The ALL_TAB_PARTITIONS view provides information about all of the partitions that
reside in the database.
3.23 ALL_TRIGGERS
The ALL_TRIGGERS view provides information about the triggers on tables that may be
accessed by the current user.
The ALL_TYPES view provides information about the object types available to the
current user.
3.25 ALL_USERS
3.27 ALL_VIEWS
The DBA_ALL_TABLES view provides information about all tables in the database.
3.29 DBA_CONS_COLUMNS
The DBA_CONS_COLUMNS view provides information about all columns that are included
in constraints that are specified in on all tables in the database.
The DBA_CONSTRAINTS view provides information about all constraints on tables in the
database.
3.31 DBA_DB_LINKS
The DBA_DB_LINKS view provides information about all database links in the database.
The DBA_DIRECTORIES view provides information about all directories created with the
CREATE DIRECTORY command.
3.33 DBA_IND_COLUMNS
3.34 DBA_INDEXES
The DBA_INDEXES view provides information about all indexes in the database.
3.35 DBA_JOBS
The DBA_JOBS view provides information about all jobs in the database.
The DBA_OBJECTS view provides information about all objects in the database.
3.37 DBA_PART_KEY_COLUMNS
The DBA_PART_KEY_COLUMNS view provides information about the key columns of the
partitioned tables that reside in the database.
The DBA_PART_TABLES view provides information about all of the partitioned tables in
the database.
The DBA_POLICIES view provides information on all policies in the database. This view
is accessible only to superusers.
The DBA_PROFILES view provides information about existing profiles. The table
includes a row for each profile/resource combination.
3.41 DBA_QUEUES
The DBA_QUEUES view provides information about any currently defined queues.
retention
CHARACTER The number of seconds that a processed message is retained in
VARYING the queue.
CHARACTER
user_comment
VARYING A user-specified comment.
CHARACTER
network_name
VARYING The name of the network on which the queue resides.
CHARACTER YES if the queue resides on a sharded network; NO if the queue
sharded
VARYING does not.
The DBA_QUEUE_TABLES view provides information about all of the queue tables in the
database.
3.43 DBA_ROLE_PRIVS
The DBA_ROLE_PRIVS view provides information on all roles that have been granted to
users. A row is created for each role to which a user has been granted.
3.44 DBA_ROLES
The DBA_ROLES view provides information on all roles with the NOLOGIN attribute
(groups).
3.45 DBA_SEQUENCES
3.46 DBA_SOURCE
The DBA_SOURCE view provides the source code listing of all objects in the database.
3.48 DBA_SYNONYMS
The DBA_SYNONYM view provides information about all synonyms in the database.
The DBA_TAB_COLUMNS view provides information about all columns in the database.
The DBA_TAB_PARTITIONS view provides information about all of the partitions that
reside in the database.
The DBA_TABLES view provides information about all tables in the database.
3.53 DBA_TRIGGERS
The DBA_TRIGGERS view provides information about all triggers in the database.
The DBA_TYPES view provides information about all object types in the database.
The DBA_USERS view provides information about all users of the database.
3.57 DBA_VIEWS
The DBA_VIEWS view provides information about all views in the database.
The USER_ALL_TABLES view provides information about all tables owned by the current
user.
3.59 USER_CONS_COLUMNS
The USER_CONS_COLUMNS view provides information about all columns that are
included in constraints in tables that are owned by the current user.
3.61 USER_DB_LINKS
The USER_DB_LINKS view provides information about all database links that are owned
by the current user.
3.63 USER_INDEXES
The USER_INDEXES view provides information about all indexes on tables that are
owned by the current user.
The USER_JOBS view provides information about all jobs owned by the current user.
3.65 USER_OBJECTS
The USER_OBJECTS view provides information about all objects that are owned by the
current user.
The USER_PART_TABLES view provides information about all of the partitioned tables in
the database that are owned by the current user.
The USER_QUEUES view provides information about any queue on which the current user
has usage privileges.
3.70 USER_QUEUE_TABLES
The USER_QUEUE_TABLES view provides information about all of the queue tables
accessible by the current user.
3.71 USER_ROLE_PRIVS
The USER_ROLE_PRIVS view provides information about the privileges that have been
granted to the current user. A row is created for each role to which a user has been
granted.
3.72 USER_SEQUENCES
The USER_SEQUENCES view provides information about all user-defined sequences that
belong to the current user.
The USER_SOURCE view provides information about all programs owned by the current
user.
3.74 USER_SUBPART_KEY_COLUMNS
3.75 USER_SYNONYMS
The USER_SYNONYMS view provides information about all synonyms owned by the
current user.
The USER_TAB_COLUMNS view displays information about all columns in tables and
views owned by the current user.
The USER_TAB_PARTITIONS view provides information about all of the partitions that
are owned by the current user.
The USER_TABLES view displays information about all tables owned by the current user.
3.80 USER_TRIGGERS
The USER_TRIGGERS view displays information about all triggers on tables owned by
the current user.
The USER_TYPES view provides information about all object types owned by the current
user.
The USER_VIEW_COLUMNS view provides information about all columns in views owned
by the current user.
3.84 USER_VIEWS
The USER_VIEWS view provides information about all views owned by the current user.
3.85 V$VERSION
4.1 dual
dual is a single-row, single-column table that is provided for compatibility with Oracle
databases only.
4.2 edb_dir
The edb_dir table contains one row for each alias that points to a directory created with
the CREATE DIRECTORY command. A directory is an alias for a pathname that allows a
user limited access to the host file system.
You can use a directory to fence a user into a specific directory tree within the file
system. For example, the UTL_FILE package offers functions that permit a user to read
and write files and directories in the host file system, but only allows access to paths that
the database administrator has granted access to via a CREATE DIRECTORY command.
4.3 edb_password_history
The edb_password_history table contains one row for each password change. The
table is shared across all databases within a cluster.
4.4 edb_policy
4.5 edb_profile
The edb_profile table stores information about the available profiles. edb_profiles
is shared across all databases within a cluster.
4.6 edb_variable
The edb_variable table contains one row for each package level variable (each
variable declared within a package).
4.7 pg_synonym
The pg_synonym table contains one row for each synonym created with the CREATE
SYNONYM command or CREATE PUBLIC SYNONYM command.
4.8 product_component_version
5 Acknowledgements
The PostgreSQL 8.3, 8.4, 9.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, and 10 Documentation provided
the baseline for the portions of this guide that are common to PostgreSQL, and is hereby
acknowledged:
Portions of this EnterpriseDB Software and Documentation may utilize the following
copyrighted material, the use of which is hereby acknowledged.
Permission to use, copy, modify, and distribute this software and its documentation for
any purpose, without fee, and without a written agreement is hereby granted, provided
that the above copyright notice and this paragraph and the following two paragraphs
appear in all copies.