PK *Aoa,mimetypeapplication/epub+zipPK*AiTunesMetadata.plistV artistName Oracle Corporation book-info cover-image-hash 59028027 cover-image-path OEBPS/dcommon/oracle-logo.jpg package-file-hash 74365909 publisher-unique-id E21642-04 unique-id 790596340 genre Oracle Documentation itemName Oracle® TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2) releaseDate 2012-09-19T19:40:10Z year 2012 PKeJ[VPK*AMETA-INF/container.xml PKYuPK*AOEBPS/cover.htmO Cover

Oracle Corporation

PK[pTOPK*AOEBPS/whatsnew.htmP# What's New

What's New

This section lists new features for Release 11.2.2 that are documented in this reference and provides cross-references to additional information.

New features in Release 11.2.2.4.0

New features in Release 11.2.2.1.0

New features in Release 11.2.2.0.0

PK{U#P#PK*AOEBPS/types.htm Data Types

1 Data Types

A data type defines a set of values. A reference to a data type specifies the set of values that can occur in a given context. A data type is associated with each value retrieved from a table or computed in an expression and each constant.

TimesTen follows the ODBC standard for type conversion. For more information, refer to ODBC API reference documentation, which is available from Microsoft or a variety of third parties. The following site contains Microsoft's ODBC API reference documentation:

http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx

If you are using IMDB Cache, see "Mappings between Oracle and TimesTen data types" in Oracle In-Memory Database Cache User's Guide. This section compares valid data types for creating cache group columns, as well as type conversions for passthrough queries.

The following subjects describe data types in TimesTen:

Type specifications

TimesTen supports the data types in Table 1-1 in the default Oracle type mode. Type mode is a data store attribute, where TypeMode=0 indicates Oracle type mode and TypeMode=1 indicates TimesTen mode. For more information on data type modes, see "TimesTen type mode (backward compatibility)" and "TypeMode" in Oracle TimesTen In-Memory Database Reference.

Table 1-1 Data types supported in Oracle type mode

Data typeDescription

BINARY(n)

Fixed-length binary value of n bytes. Legal values for n range from 1 to 8300. BINARY data is padded to the maximum column size with trailing zeroes. Alternatively, specify TT_BINARY(n).

For more details, see "BINARY and VARBINARY data types".

BINARY_DOUBLE

A 64-bit floating-point number. BINARY_DOUBLE is a double-precision native floating point number that supports +Inf, -Inf, and NaN values. BINARY_DOUBLE is an approximate numeric value consisting of an exponent and mantissa. You can use exponential or E-notation. BINARY_DOUBLE has binary precision 53.

Minimum positive finite value: 2.22507485850720E-308

Maximum positive finite value: 1.79769313486231E+308

For more details, see "BINARY_DOUBLE".

BINARY_FLOAT

A 32-bit floating-point number. BINARY_FLOAT is a single-precision native floating-point type that supports +Inf, -Inf, and NaN values. BINARY_FLOAT is an approximate numeric value consisting of an exponent and mantissa. You can use exponential or E-notation. BINARY_FLOAT has binary precision 24.

Minimum positive finite value: 1.17549E-38F

Maximum positive finite value: 3.40282E+38F

For more details, see "BINARY_FLOAT".

BLOB

A binary large object. Variable-length binary value with a maximum size of 16 MB.

For more details, see "BLOB".

CHAR[ACTER][(n[BYTE|CHAR])]

Fixed-length character string of length n bytes or characters. Default is one byte.

BYTE indicates that the column has byte-length semantics. Legal values for n range from a minimum of one byte to a maximum of 8300 bytes.

CHAR indicates that the column has character-length semantics. The minimum CHAR length is one character. The maximum CHAR length depends on how many characters fit in 8300 bytes. This is determined by the database character set in use. For character set AL32UTF8, up to four bytes per character may be needed, so the CHAR length limit ranges from 2075 to 8300 depending on the character set.

A zero-length string is interpreted as NULL.

CHAR data is padded to the maximum column size with trailing blanks. Blank-padded comparison semantics are used.

Alternatively, specify ORA_CHAR[(n[BYTE|CHAR])].

For more details, see "CHAR".

CLOB

A character large object containing single-byte or multibyte characters. Variable-length large object with a maximum size of 4 MB.

For more details, see "CLOB".

DATE

Stores date and time information: century, year, month, day, hour, minute, and second. Format is:

YYYY-MM-DD HHMMSS.

Valid date range is from January 1, 4712 BC to December 31, 9999 AD.

There are no fractional seconds.

Alternatively, specify ORA_DATE.

For more details, see "DATE".

INTERVAL [+/-] IntervalQualifier

TimesTen partially supports interval types, expressed with the type INTERVAL and an IntervalQualifier. An IntervalQualifier can only specify a single field type with no precision. The default leading precision is eight digits for all interval types. The single field type can be: year, month, day, hour, minute, or second. Currently, interval types can be specified only with a constant.

Note: You cannot specify a column of an interval type. These are non-persistent types used in SQL expressions at runtime. In addition, for those comparisons where an interval data type is returned, the interval data type cannot be the final result of a complete expression. The EXTRACT function must be used to extract the desired component of this interval result.

For more details, see "TimesTen intervals".

NCHAR[(n)]

Fixed-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NCHAR character limits are half the byte limits so the maximum size is 4150.

A zero-length string is interpreted as NULL.

NCHAR data is padded to the maximum column size with U+0020 SPACE. Blank-padded comparison semantics are used.

Alternatively, specify ORA_NCHAR[(n)].

For more details, see "NCHAR".

NCLOB

A national character large object containing Unicode characters. Variable-length character value with a maximum size of 4 MB.

For more details, see "NCLOB".

NUMBER[(p [,s])]

Number having precision and scale. The precision ranges from 1 to 38 decimal. The scale ranges from -84 to 127. Both precision and scale are optional.

If you do not specify a precision or a scale, TimesTen assumes the maximum precision of 38 and flexible scale.

NUMBER supports negative scale and scale greater than precision.

NUMBER stores zero as well as positive and negative fixed numbers with absolute values from 1.0 x 10-130 to (but not including) 1.0 x 10126. If you specify an arithmetic expression whose value has an absolute value greater than or equal to 1.0 x 10126, then TimesTen returns an error.

For more details, see "NUMBER".

NVARCHAR2(n)

Variable-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NVARCHAR2 character limits are half the byte limits so the maximum size is 2,097,152 (221). You must specify n.

A zero-length string is interpreted as NULL.

Nonpadded comparison semantics are used.

Alternatively, specify ORA_NVARCHAR2(n).

For more details, see "NVARCHAR2".

ROWID

An 18-byte character string that represents the address of a table row or materialized view row.

Specify a literal ROWID value as a CHAR constant enclosed in single quotes.

For more details, see "ROWID data type".

TIME

A time of day between 00:00:00 (midnight) and 23:59:59 (11:59:59 pm), inclusive. The format is: HH:MI:SS.

Alternatively, specify TT_TIME.

For more details, see "TIME".

TIMESTAMP

[(fractional_seconds_precision)]

Stores year, month, and day values of the date plus hour, minute, and second values of the time. The fractional_seconds_precision is the number of digits in the fractional part of the seconds field. Valid date range is from January 1, 4712 BC to December 31, 9999 AD.

TT_TIMESTAMP has a smaller storage size than TIMESTAMP. TT_TIMESTAMP is faster than TIMESTAMP because TT_TIMESTAMP is an eight-byte integer containing the number of microseconds since January 1, 1754. Comparisons are very fast. TIMESTAMP has a larger range than TT_TIMESTAMP in that TIMESTAMP can store date and time data as far back as 4712 BC. TIMESTAMP also supports up to nine digits of fractional second precision whereas TT_TIMESTAMP supports six digits of fractional second precision.

The fractional seconds precision range is 0 to 9. The default is 6. Format is:

YYYY-MM-DD HH:MI:SS [.FFFFFFFFF]

Alternatively, specify ORA_TIMESTAMP[(fractional_seconds_precision)]

For more details, see "TIMESTAMP".

TT_BIGINT

A signed eight-byte integer in the following range:

-9,223,372,036,854,775,808 (-263) to

9,223,372,036,854,775,807 (263-1).

Use TT_BIGINT rather than the NUMBER data type. TT_BIGINT is more compact and offers faster performance than the NUMBER type. If you need to store greater than 19-digit integers, use NUMBER(p) where p > 19.

For more details, see "TT_BIGINT".

TT_DATE

Stores date information: century, year, month, and day. The format is YYYY-MM-DD, where MM is expressed as an integer such as 2006-10-28.

Valid dates are between 1753-01-01 (January 1, 1753) and 9999-12-31 (December 31, 9999).

For more details, see "TT_DATE".

TT_INTEGER

A signed integer in the range -2,147,483,648 (-231) to 2,147,483,647 (231-1).

TT_INTEGER is a native signed integer data type. Use TT_INTEGER rather than INTEGER. INTEGER maps to the NUMBER data type. TT_INTEGER is more compact and offers faster performance than the NUMBER type. If you need to store greater than 19-digit integers, use NUMBER(p) where p > 19.

For more details, see "TT_INTEGER".

TT_SMALLINT

A native signed 16-bit integer in the range -32,768 (-215) to 32,767 (215-1).

Use TT_SMALLINT rather than SMALLINT. SMALLINT maps to the NUMBER data type.

TT_SMALLINT is more compact and offers faster performance than the NUMBER type. If you need to store greater than 19-digit integers, use NUMBER(p) where p > 19.

For more details, see "TT_SMALLINT".

TT_TIMESTAMP

A date and time between 1753-01-01 00:00:00 (midnight on January 1, 1753) and 9999-12-31 23:59:59 pm (11:59:59 pm on December 31, 9999), inclusive. Any values for the fraction not specified in full microseconds result in a "Data Truncated" error. The format is YYYY-MM-DD HH:MI:SS [.FFFFFFFFF].

TT_TIMESTAMP has a smaller storage size than TIMESTAMP and is faster than TIMESTAMP because TT_TIMESTAMP is an eight-byte integer containing the number of microseconds since January 1, 1754. Comparisons are very fast. TIMESTAMP has a larger range than TT_TIMESTAMP in that TIMESTAMP can store date and time data as far back as 4712 BC. TIMESTAMP also supports up to nine digits of fractional second precision whereas TT_TIMESTAMP supports six digits of fractional second precision.

You can specify TT_TIMESTAMP(6).

For more details, see "TT_TIMESTAMP".

TT_TINYINT

Unsigned integer ranging from 0 to 255 (28-1).

Use TT_TINYINT rather than the NUMBER data type. TT_TINYINT is more compact and offers faster performance than the NUMBER type. If you need to store greater than 19-digit integers, use NUMBER(p) where p > 19.

Since TT_TINYINT is unsigned, the negation of a TT_TINYINT is a TT_SMALLINT.

For more details, see "TT_TINYINT".

VARBINARY(n)

Variable-length binary value having maximum length n bytes. Legal values for n range from 1 to 4194304 (222).

Alternatively, specify TT_VARBINARY(n).

For more details, see "BINARY and VARBINARY data types".

VARCHAR[2](n[BYTE|CHAR])

Variable-length character string having maximum length n bytes or characters.

BYTE indicates that the column has byte-length semantics. Legal values for n range from a minimum of one byte to a maximum 4194304 (222) bytes. You must specify n.

CHAR indicates that the column has character-length semantics.

A zero-length string is interpreted as NULL.

Nonpadded comparison semantics are used.

Do not use the VARCHAR type. Although it is currently synonymous with VARCHAR2, the VARCHAR type is scheduled to be redefined.

Alternatively, specify ORA_VARCHAR2(n[BYTE|CHAR]).

For more details, see "VARCHAR2".


ANSI SQL data types

TimesTen supports ANSI SQL data types in Oracle type mode. These data types are converted to TimesTen data types with data stored as TimesTen data types. Table 1-2 shows how the ANSI SQL data types are mapped to TimesTen data types.

Table 1-2 Data type mapping: ANSI SQL to TImesTen

ANSI SQL data typeTimesTen data type

CHARACTER VARYING(n[BYTE|CHAR]) or

CHAR VARYING(n[BYTE|CHAR])

VARCHAR2(n[BYTE|CHAR])

Character semantics is supported.

DOUBLE [PRECISION]

NUMBER

Floating-point number with a binary precision of 126.

Alternatively, specify FLOAT(126) or ORA_FLOAT(126).

FLOAT[(b)]

NUMBER

Floating-point number with binary precision b. Acceptable values for b are between 1 and 126 (binary digits).

FLOAT is an exact numeric type. Use FLOAT to define a column with a floated scale and a specified precision. A floated scale is supported with the NUMBER type, but you cannot specify the precision. A lower precision requires less space, so because you can specify a precision with FLOAT, it may be more desirable than NUMBER. If you do not specify b, then the default precision is 126 binary (38 decimal).

BINARY_FLOAT and BINARY_DOUBLE are inexact numeric types and are therefore different floating types than FLOAT. In addition, the semantics are different between FLOAT and BINARY_FLOAT/BINARY_DOUBLE because BINARY_FLOAT and BINARY_DOUBLE conform to the IEEE standard.

Internally, FLOAT is implemented as type NUMBER.

Alternatively, specify ORA_FLOAT. For example:

FLOAT(24) = ORA_FLOAT(24)

FLOAT(53) = ORA_FLOAT(53)

FLOAT(n) = ORA_FLOAT(n)

INT[EGER]

NUMBER(38,0)

TT_INTEGER is a native 32-bit integer type. Use TT_INTEGER, as this data type is more compact and offers faster performance than the NUMBER type.

NATIONAL CHARACTER(n) or

NATIONAL CHAR(n)

NCHAR(n)

NATIONAL CHARACTER VARYING(n) or

NATIONAL CHAR VARYING(n) or

NCHAR VARYING(n)

NVARCHAR2(n)

NUMERIC[(p[,s])] or

DEC[IMAL][(p[,s])]

NUMBER(p,s)

Specifies a fixed-point number with precision p and scale s. This can only be used for fixed-point numbers. If no scale is specified, s defaults to 0.

REAL

NUMBER

Floating-point number with a binary precision of 63.

Alternatively, specify ORA_FLOAT(63) or FLOAT(63).

SMALLINT

NUMBER(38,0)

TT_SMALLINT is a native signed integer data type. Using TT_SMALLINT is more compact and offers faster performance than the NUMBER type.


Types supported for backward compatibility in Oracle type mode

TimesTen supports the data types shown in Table 1-3 for backward compatibility in Oracle type mode.

Table 1-3 Data types supported for backward compatibility in Oracle type mode

Data typeDescription

TT_CHAR[(n[BYTE|CHAR])]

Fixed-length character string of length n bytes or characters. Default is one byte.

BYTE indicates that the column has byte-length semantics. Legal values for n range from a minimum of one byte to a maximum 8300 bytes.

CHAR indicates that the column has character-length semantics. The minimum CHAR length is one character. The maximum CHAR length depends on how many characters fit in 8300 bytes. This is determined by the database character set in use. For character set AL32UTF8, up to four bytes per character may be needed, so the CHAR length limit ranges from 2075 to 8300 depending on the character set.

If you insert a zero-length (empty) string into a column, the SQL NULL value is inserted. This is true in Oracle type mode only.

TT_CHAR data is padded to the maximum column size with trailing blanks. Blank-padded comparison semantics are used.

TT_DECIMAL[(p[,s])]

An exact numeric value with a fixed maximum precision (total number of digits) and scale (number of digits to the right of the decimal point). The precision p must be between 1 and 40. The scale s must be between 0 and p. The default precision is 40 and the default scale is 0.

Use the NUMBER data type, which offers better performance, rather than TT_DECIMAL.

TT_NCHAR[(n)]

Fixed-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NCHAR character limits are half the byte limits so the maximum size is 4150.

If you insert a zero-length (empty) string into a column, the SQL NULL value is inserted. This is true in Oracle type mode only.

TT_NCHAR data is padded to the maximum column size with U+0020 SPACE. Blank-padded comparison semantics are used.

TT_NVARCHAR(n)

Variable-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. TT_NVARCHAR character limits are half the byte limits so the maximum size is 2,097,152 (221). You must specify n.

If you insert a zero-length (empty) string into a column, the SQL NULL value is inserted. This is true in Oracle type mode only.

Blank-padded comparison semantics are used.

TT_VARCHAR(n[BYTE|CHAR])

Variable-length character string having maximum length n bytes or characters. You must specify n.

BYTE indicates that the column has byte-length semantics. Legal values for n range from a minimum of 1 byte to a maximum 4194304 (222) bytes.

CHAR indicates that the column has character-length semantics.

If you insert a zero-length (empty) string into a column, the SQL NULL value is inserted. This is true in Oracle type mode only.

Blank-padded comparison semantics are used.


TimesTen type mapping

The names of the data types listed in the left column of Table 1-4 are the data types that existed in previous releases of TimesTen. If TypeMode is set to 0 (the default), indicating Oracle type mode, the name of the data type may be changed to a new name in Oracle type mode. The name of the data type in Oracle type mode is listed in the right column. The table illustrates the mapping of the data type in the left column to the corresponding data type in the right column.

Table 1-4 Data type mapping: TimesTen data type to TimesTen data type in Oracle type mode

TimesTen data typeTimesTen data type in Oracle type mode

BIGINT

TT_BIGINT

In Oracle type mode, specify TT_BIGINT. For more information on TT_BIGINT, see "Type specifications".

BINARY(n)

BINARY(n)

In Oracle type mode, the data type has the same name. For more information on BINARY(n), see "Type specifications".

CHAR[ACTER][(n)]

TT_CHAR[(n[BYTE|CHAR])]

In Oracle type mode, specify TT_CHAR. Character semantics is supported. For more information on type TT_CHAR, see "Types supported for backward compatibility in Oracle type mode".

DATE

TT_DATE

In Oracle type mode, specify TT_DATE. For more information on TT_DATE, see "Type specifications".

DEC[IMAL][(p[,s])] or

NUMERIC[(p[,s])]

TT_DECIMAL[(p[,s])]

In Oracle type mode, specify TT_DECIMAL.

For more information on TT_DECIMAL, see "Types supported for backward compatibility in Oracle type mode".

DOUBLE [PRECISION] or

FLOAT[(53)]

BINARY_DOUBLE

In Oracle type mode, specify BINARY_DOUBLE. For more information on BINARY_DOUBLE, see "Type specifications".

INT[EGER]

TT_INT[EGER]

In Oracle type mode, specify TT_INTEGER. For more information on TT_INTEGER, see "Type specifications".

INTERVAL IntervalQualifier

INTERVAL IntervalQualifier

In Oracle type mode, the data type has the same name. For more information on interval types, see "Type specifications".

NCHAR[(n)]

TT_NCHAR[(n)]

In Oracle type mode, specify TT_CHAR. For more information on TT_NCHAR, see "Types supported for backward compatibility in Oracle type mode".

NVARCHAR(n)

TT_NVARCHAR(n)

In Oracle type mode, specify TT_NVARCHAR. For more information on TT_NVARCHAR, see "Types supported for backward compatibility in Oracle type mode".

REAL or

FLOAT(24)

BINARY_FLOAT

In Oracle type mode, specify BINARY_FLOAT. For more information on BINARY_FLOAT, see "Type specifications".

SMALLINT

TT_SMALLINT

In Oracle type mode, specify TT_SMALLINT. For more information on TT_SMALLINT, see "Type specifications".

TIME

TIME

In Oracle type mode, the data type has the same name. For more information on TIME, see "Type specifications".

TIMESTAMP

TT_TIMESTAMP

In Oracle type mode, specify TT_TIMESTAMP. For more information on TT_TIMESTAMP, see "Type specifications".

TINYINT

TT_TINYINT

In Oracle type mode, specify TT_TINYINT. For more information on TT_TINYINT, see "Type specifications".

VARBINARY(n)

VARBINARY(n)

In Oracle type mode, the data type has the same name. For more information on VARBINARY(n), see "Type specifications".

VARCHAR(n)

TT_VARCHAR(n[BYTE|CHAR])

In Oracle type mode, specify TT_VARCHAR. Character semantics is supported. For more information on TT_VARCHAR, see "Types supported for backward compatibility in Oracle type mode".


Character data types

Character data types store character (alphanumeric) data either in the database character set or the UTF-16 format. Character data is stored in strings with byte values. The byte values correspond to one of the database character sets defined when the database is created. TimesTen supports both single and multibyte character sets.

The character types are as follows:

CHAR

The CHAR type specifies a fixed length character string. If you insert a value into a CHAR column and the value is shorter than the defined column length, then TimesTen blank-pads the value to the column length. If you insert a value into a CHAR column and the value is longer than the defined length, TimesTen returns an error.

By default, the column length is defined in bytes. Use the CHAR qualifier to define the column length in characters. The size of a character ranges from one byte to four bytes depending on the database character set. The BYTE and CHAR qualifiers override the NLS_LENGTH_SEMANTICS parameter setting. For more information about NLS_LENGTH_SEMANTICS, see "ALTER SESSION" and "Setting globalization support attributes" in Oracle TimesTen In-Memory Database Operations Guide.


Note:

With the CHAR type, a zero-length string is interpreted as NULL. With the TT_CHAR type, a zero-length string is a valid non-NULL value. Both CHAR and TT_CHAR use blank padded comparison semantics. The TT_CHAR type is supported for backward compatibility.

The following example creates a table. Columns are defined with type CHAR and TT_CHAR. Blank padded comparison semantics are used for these types.

Command> CREATE TABLE typedemo (name CHAR (20), nnme2 TT_CHAR (20));
Command> INSERT INTO typedemo VALUES ('SMITH     ','SMITH     ');
1 row inserted.
Command> DESCRIBE typedemo;
Table USER.TYPEDEMO:
  Columns:
    NAME                            CHAR (20)
    NAME2                           TT_CHAR (20)
1 table found.
(primary key columns are indicated with *)
Command> SELECT * FROM typedemo;
< SMITH     , SMITH      >
1 row found.
Command> # Expect 1 row found; blank-padded comparison semantics
Command> SELECT * FROM typedemo WHERE name = 'SMITH';
< SMITH     , SMITH      >
1 row found.
Command> SELECT * FROM typedemo WHERE name2 = 'SMITH';
< SMITH     , SMITH      >
1 row found.
Command> # Expect 0 rows; blank padded comparison semantics.
Command> SELECT * FROM typedemo WHERE name > 'SMITH';
0 rows found.
Command> SELECT * FROM typedemo WHERE name2 > 'SMITH';
0 rows found.

The following example alters table typedemo adding column name3. The column name3 is defined with character semantics.

Command> ALTER TABLE typedemo ADD COLUMN name3 CHAR (10 CHAR);
Command> DESCRIBE typedemo;
Table USER.TYPEDEMO:
  Columns:
    NAME                            CHAR (20)
    NAME2                           TT_CHAR (20)
    NAME3                           CHAR (10 CHAR)
1 table found.

NCHAR

The NCHAR data type is a fixed length string of two-byte Unicode characters. NCHAR data types are padded to the specified length with the Unicode space character U+0020 SPACE. Blank-padded comparison semantics are used.


Note:

With the NCHAR type, a zero-length string is interpreted as NULL. With the TT_NCHAR type, a zero-length string is a valid non-NULL value. Both NCHAR and TT_NCHAR use blank padded comparison semantics. The TT_NCHAR type is supported for backward compatibility.

The following example alters table typedemo, adding column Name4. Data type is NCHAR.

Command> ALTER TABLE typedemo ADD COLUMN Name4 NCHAR (10);
Command> DESCRIBE typedemo;

Table USER.TYPEDEMO:
  Columns:
    NAME                            CHAR (20)
    NAME2                           TT_CHAR (20)
    NAME3                           CHAR (10 CHAR)
    NAME4                           NCHAR (10)
1 table found.

VARCHAR2

The VARCHAR2 data type specifies a variable length character string. When you define a VARCHAR2 column, you define the maximum number of bytes or characters. Each value is stored exactly as you specify it. The value cannot exceed the maximum length of the column.

You must specify the maximum length. The minimum must be at least one byte. Use the CHAR qualifier to specify the maximum length in characters. For example, VARCHAR2(10 CHAR).

The size of a character ranges from one byte to four bytes depending on the database character set. The BYTE and CHAR qualifiers override the NLS_LENGTH_SEMANTICS parameter setting. For more information on NLS_LENGTH_SEMANTICS, see "ALTER SESSION" and "Setting globalization support attributes" in Oracle TimesTen In-Memory Database Operations Guide.

The NULL value is stored as a single bit for each nullable field within the row. A NOT INLINE VARCHAR2(n) whose value is NULL takes (null bit) + four bytes of storage on 32-bit platforms, whereas an INLINE VARCHAR2(n) whose value is NULL takes (null bit) + four bytes + n bytes of storage, or n more bytes of storage than a NOT INLINE VARCHAR2(n) whose value is NULL. This storage principal holds for all variable length data types: TT_VARCHAR, TT_NVARCHAR, VARCHAR2, NVARCHAR2, VARBINARY.


Notes:

  • Do not use the VARCHAR data type. Use VARCHAR2. Even though both data types are currently synonymous, the VARCHAR data type may be redefined as a different data type with different semantics.

  • With the VARCHAR2 type, a zero-length string is interpreted as NULL. With the TT_VARCHAR type, a zero-length string is a valid non-NULL value. VARCHAR2 uses nonpadded comparison semantics. TT_VARCHAR uses blank-padded comparison semantics. The TT_VARCHAR type is supported for backward compatibility.


The following example alters table typedemo, adding columns name5 and name6. The name5 column is defined with type VARCHAR2. The name6 column is defined with TT_VARCHAR. The example illustrates the use of nonpadded comparison semantics with column name5 and blank-padded comparison semantics with column name6:

Command> ALTER TABLE typedemo ADD COLUMN name5 VARCHAR2 (20);
Command> ALTER TABLE typedemo ADD COLUMN name6 TT_VARCHAR (20);
Command> DESCRIBE typedemo;
Table USER.TYPEDEMO:
  Columns:
    NAME                            CHAR (20)
    NAME2                           TT_CHAR (20)
    NAME3                           CHAR (10 CHAR)
    NAME4                           NCHAR (10)
    NAME5                           VARCHAR2 (20) INLINE
    NAME6                           TT_VARCHAR (20) INLINE
1 table found.
(primary key columns are indicated with *)
Command> #Insert SMITH followed by 5 spaces into all columns
Command> INSERT INTO typedemo VALUES
       > ('SMITH     ', 'SMITH     ', 'SMITH     ', 'SMITH     ','SMITH     ',
       > 'SMITH');
1 row inserted.
Command> # Expect 0; Nonpadded comparison semantics
Command> SELECT COUNT (*) FROM typedemo WHERE name5 = 'SMITH';
< 0 >
1 row found.
Command> # Expect 1; Blank-padded comparison semantics
Command> SELECT COUNT (*) FROM typedemo WHERE name6 = 'SMITH';
< 1 >
1 row found.
Command> # Expect 1; Nonpadded comparison semantics
Command> SELECT COUNT (*) FROM typedemo WHERE name5 > 'SMITH';
< 1 >
1 row found.
Command> # Expect 0; Blank-padded comparison semantics
Command> SELECT COUNT (*) FROM typedemo WHERE name6 > 'SMITH';
< 0 >
1 row found.

NVARCHAR2

The NVARCHAR2 data type is a variable length string of two-byte Unicode characters. When you define an NVARCHAR2 column, you define the maximum number of characters. Each value is stored exactly as you specify it. The value cannot exceed the maximum length of the column.


Note:

With the NVARCHAR2 type, a zero-length string is interpreted as NULL. With the TT_NVARCHAR type, a zero-length string is a valid non-NULL value. NVARCHAR2 uses nonpadded comparison semantics. TT_NVARCHAR uses blank-padded comparison semantics. The TT_NVARCHAR type is supported for backward compatibility.

The following example alters table typedemo adding column name7. Data type is NVARCHAR2.

Command> ALTER TABLE typedemo ADD COLUMN Nnme7 NVARCHAR2 (20);
Command> DESCRIBE typedemo;
Table USER1.TYPEDEMO:
  Columns:
    NAME                            CHAR (20)
    NAME2                           TT_CHAR (20)
    NAME3                           CHAR (10 CHAR)
    NAME4                           NCHAR (10)
    NAME5                           VARCHAR2 (20) INLINE
    NAME6                           TT_VARCHAR (20) INLINE
    NAME7                           NVARCHAR2 (20) INLINE
1 table found.

Numeric data types

Numeric types store positive and negative fixed and floating-point numbers, zero, infinity, and values that are the undefined result of an operation (NaN, meaning not a number).

TimesTen supports both exact and approximate numeric data types. Arithmetic operations can be performed on numeric types only. Similarly, SUM and AVG aggregates require numeric types.

The exact numeric types are:

The approximate types are:

NUMBER

The NUMBER data type stores zero as well as positive and negative fixed numbers with absolute values from 1.0 x 10 -130 up to but not including 1.0 x 10 126. Each NUMBER value requires from five to 22 bytes.

Specify a fixed-point number as NUMBER(p,s), where the following holds:

  • The argument p is the precision or the total number of significant decimal digits, where the most significant digit is the left-most non-zero digit and the least significant digit is the right-most known digit.

  • The argument s is the scale, or the number of digits from the decimal point to the least significant digit. The scale ranges from -84 to 127.

    • Positive scale is the number of significant digits to the right of the decimal point up to and including the least significant digit.

    • Negative scale is the number of significant digits to the left of the decimal point up to but not including the least significant digit. For negative scale, the least significant digit is on the left side of the decimal point, because the number is rounded to the specified number of places to the left of the decimal point.

Scale can be greater than precision. For example, in the case of E-notation. When scale is greater than precision, the precision specifies the maximum number of significant digits to the right of the decimal point. For example, if you define the column as type NUMBER(4,5) and you insert .000127 into the column, the value is stored as .00013. A zero is required for the first digit after the decimal point. TimesTen rounds values after the fifth digit to the right of the decimal point.

If a value exceeds the precision, then TimesTen returns an error. If a value exceeds the scale, then TimesTen rounds the value.

NUMBER(p) represents a fixed-point number with precision p and scale 0 and is equivalent to NUMBER(p,0).

Specify a floating-point number as NUMBER. If you do not specify precision and scale, TimesTen uses the maximum precision and scale.

The following example alters table numerics by adding columns col6, col7, col8, and col9 defined with the NUMBER data type and specified with different precisions and scales.

Command> ALTER TABLE numerics ADD col6 NUMBER;
Command> ALTER TABLE numerics ADD col7 NUMBER (4,2);
Command> ALTER TABLE numerics ADD col8 NUMBER (4,-2);
Command> ALTER TABLE numerics ADD col8 NUMBER (2,4);
Command> ALTER TABLE numerics ADD col9 NUMBER (2,4);
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            TT_INTEGER
    COL4                            TT_INTEGER
    COL5                            TT_BIGINT
    COL6                            NUMBER
    COL7                            NUMBER (4,2)
    COL8                            NUMBER (4,-2)
    COL9                            NUMBER (2,4)
1 table found.
(primary key columns are indicated with *)

The next example creates table numbercombo and defines columns with the NUMBER data type using different precisions and scales. The value 123.89 is inserted into the columns.

Command> CREATE TABLE numbercombo (col1 NUMBER, col2 NUMBER (3), 
       > col3 NUMBER (6,2), col4 NUMBER (6,1), col5 NUMBER (6,-2));
Command> DESCRIBE numbercombo;
Table USER1.NUMBERCOMBO:
  Columns:
    COL1                            NUMBER
    COL2                            NUMBER (3)
    COL3                            NUMBER (6,2)
    COL4                            NUMBER (6,1)
    COL5                            NUMBER (6,-2)
1 table found.
(primary key columns are indicated with *)
Command> INSERT INTO numbercombo VALUES (123.89,123.89,123.89,123.89,123.89);
1 row inserted.
Command> VERTICAL ON;
Command> SELECT * FROM numbercombo;
COL1:   123.89
  COL2:   124
  COL3:   123.89
  COL4:   123.9
  COL5:   100
1 row found.

The next example creates a table and defines a column with data type NUMBER(4,2). An attempt to insert a value of 123.89 results in an overflow error.

Command> CREATE TABLE invnumbervalue (col6 NUMBER (4,2));
Command> INSERT INTO invnumbervalue VALUES (123.89);
 2923: Number type value overflow
The command failed.

The next example creates a table and defines columns with the NUMBER data type using a scale that is greater than the precision. Values are inserted into the columns.

Command> CREATE TABLE numbercombo2 (col1 NUMBER (4,5), col2 NUMBER (4,5), 
       > col3 NUMBER (4,5), col4 NUMBER (2,7), col5 NUMBER (2,7), 
       > col6 NUMBER (2,5), col7 NUMBER (2,5));
Command> INSERT INTO numbercombo2 VALUES 
       > (.01234, .00012, .000127, .0000012, .00000123, 1.2e-4, 1.2e-5);
1 row inserted.
Command> DESCRIBE numbercombo2;
Table USER1.NUMBERCOMBO2:
  Columns:
    COL1                            NUMBER (4,5)
    COL2                            NUMBER (4,5)
    COL3                            NUMBER (4,5)
    COL4                            NUMBER (2,7)
    COL5                            NUMBER (2,7)
    COL6                            NUMBER (2,5)
    COL7                            NUMBER (2,5)
1 table found.

(primary key columns are indicated with *)
Command> SELECT * FROM numbercombo2;
COL1:   .01234
  COL2:   .00012
  COL3:   .00013
  COL4:   .0000012
  COL5:   .0000012
  COL6:   .00012
  COL7:   .00001
1 row found.

TT_BIGINT

The TT_BIGINT data type is a signed integer that ranges from -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (263-1). It requires eight bytes of storage and thus is more compact than the NUMBER data type. It also has better performance than the NUMBER data type. You cannot specify BIGINT.

This example alters table numerics and attempts to add col5 with a data type of BIGINT. TimesTen generates an error. A second ALTER TABLE successfully adds col5 with the data type TT_BIGINT.

Command> ALTER TABLE numerics ADD COLUMN col5 BIGINT;
 3300: BIGINT is not a valid type name; use TT_BIGINT instead
The command failed.
Command> ALTER TABLE numerics ADD COLUMN col5 TT_BIGINT;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            TT_INTEGER
    COL4                            TT_INTEGER
    COL5                            TT_BIGINT
1 table found.
(primary key columns are indicated with *)

TT_INTEGER

The TT_INTEGER data type is a signed integer that ranges from -2,147,483,648 (-231) to 2,147,483,647 (231 -1). It requires four bytes of storage and thus is more compact than the NUMBER data type. It also has better performance than the NUMBER data type. You can specify TT_INT for TT_INTEGER. If you specify either INTEGER or INT, these types are mapped to NUMBER(38).

The following example alters the table numerics and adds col3 with the data type INT. Describing the table shows that the data type is NUMBER(38). The column col3 is dropped. A second ALTER TABLE adds col2 with the data type INTEGER. Describing the table shows that the data type is NUMBER(38). The column col3 is dropped. Columns col3 and col4 are then added with the data types TT_INTEGER and TT_INT. Describing the table shows both data types as TT_INTEGER.

Command> ALTER TABLE numerics ADD col3 INT;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            NUMBER (38)
1 table found.
(primary key columns are indicated with *)
Command> ALTER TABLE numerics  col3;
Command> ALTER TABLE numerics ADD col3 INTEGER;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            NUMBER (38)
1 table found.
(primary key columns are indicated with *)
Command> ALTER TABLE numerics  col3;
Command> ALTER TABLE numerics ADD COLUMN col3 TT_INTEGER;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            TT_INTEGER
1 table found.
(primary key columns are indicated with *)
Command> ALTER TABLE numerics ADD col4 TT_INT;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
    COL3                            TT_INTEGER
    COL4                            TT_INTEGER
1 table found.
(primary key columns are indicated with *)

TT_SMALLINT

The TT_SMALLINT data type is a signed integer that ranges from -32,768 (-215) to 32,767 (215-1). It requires two bytes of storage and thus is more compact than the NUMBER data type. It also has better performance than the NUMBER data type. You can specify the data type SMALLINT, but it maps to NUMBER(38).

The following example alters the table numerics and adds col2 with the data type SMALLINT. Describing the table shows that the data type is NUMBER(38). The column col2 is dropped. A second ALTER TABLE adds col2 with the data type TT_SMALLINT.

Command> ALTER TABLE numerics ADD COLUMN col2 SMALLINT;
Command> DESCRIBE Numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
    COL2                            NUMBER (38)
1 table found.
(primary key columns are indicated with *)
Command> ALTER TABLE numerics  COLUMN col2;
Command> ALTER TABLE numerics ADD COLUMN col2 TT_SMALLINT;
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
    COL2                            TT_SMALLINT
1 table found.
(primary key columns are indicated with *)

TT_TINYINT

The TT_TINYINT data type is an unsigned integer that ranges from 0 to 255 (28 -1). It requires one byte of storage and thus is more compact than the NUMBER data type. It also has better performance than the NUMBER data type. The data type of a negative TT_TINYINT is TT_SMALLINT. You cannot specify TINYINT.

The following example first attempts to create a table named numerics that defines a column named col1 with data type TINYINT. TimesTen returns an error. The example then redefines the column with data type TT_TINYINT.

Command> CREATE TABLE numerics (col1 TINYINT);
 3300: TINYINT is not a valid type name; use TT_TINYINT instead
The command failed.
Command> CREATE TABLE numerics (col1 TT_TINYINT);
Command> DESCRIBE numerics;
Table USER1.NUMERICS:
  Columns:
    COL1                            TT_TINYINT
1 table found.
(primary key columns are indicated with *)

Floating-point numbers

Floating-point numbers can be with or without a decimal point. An exponent may be used to increase the range (for example, 1.2E-20).

Floating-point numbers do not have a scale because the number of digits that can appear after the decimal point is not restricted.

Binary floating-point numbers are stored using binary precision (the digits 0 and 1). For the NUMBER data type, values are stored using decimal precision (the digits 0 through 9).

Literal values that are within the range and precision supported by NUMBER are stored as NUMBER because literals are expressed using decimal precision.

Use one of the following data types for floating-point numbers:

BINARY_DOUBLE

BINARY_DOUBLE is a 64-bit, double-precision, floating-point number.

Both BINARY_FLOAT and BINARY_DOUBLE support the special values Inf, -Inf, and NaN (not a number) and conform to the IEEE standard.

Floating-point number limits:

  • BINARY_FLOAT

    • Minimum positive finite value: 1.17549E-38F

    • Maximum positive finite value: 3.40282E+38F

  • BINARY_DOUBLE

    • Minimum positive finite value: 2.22507485850720E-308

    • Maximum positive finite value: 1.79769313486231E+308

The following example creates a table and defines two columns with the BINARY_FLOAT and BINARY_DOUBLE data types.

Command> CREATE TABLE BfBd (Col1 BINARY_FLOAT, Col2 BINARY_DOUBLE);
Command> DESCRIBE BfBd;
Table UISER1.BFBD:
  Columns:
    COL1                            BINARY_FLOAT
    COL2                            BINARY_DOUBLE
1 table found.
(primary key columns are indicated with *)

BINARY_FLOAT

BINARY_FLOAT is a 32-bit, single-precision, floating-point number.

FLOAT and FLOAT(n)

TimesTen also supports the ANSI type FLOAT. FLOAT is an exact numeric type and is implemented as the NUMBER type. The value of n indicates the number of bits of precision that can be stored, from 1 to 126. To convert from binary precision to decimal precision, multiply n by 0.30103. To convert from decimal precision to binary precision, multiply the decimal precision by 3.32193. The maximum 126 digits of binary precision is equivalent to approximately 38 digits of decimal precision.

BINARY and VARBINARY data types

The BINARY data type is a fixed-length binary value with a length of n bytes, where the value of n ranges from 1 to 8300 bytes. The BINARY data type requires n bytes of storage. Data is padded to the maximum column size with trailing zeros. Zero padded comparison semantics are used.

The VARBINARY data type is a variable-length binary value having a maximum length of n bytes, where the value of n ranges from 1 to 4,194,304 (222) bytes.

The following example creates a table and defines two columns: col1 is defined with data type BINARY and col2 with data type VARBINARY. Then, binary data is inserted into each column. Note that the BINARY value is padded to the right with zeros.


Note:

For details on assigning hexadecimal literals as binary data in TimesTen, see the description for the HexadecimalLiteral in "Constants".

Command> CREATE TABLE bvar (col1 BINARY (10), col2 VARBINARY (10));
Command> DESCRIBE bvar;
Table USER1.BVAR:
  Columns:
    COL1                            BINARY (10)
    COL2                            VARBINARY (10) INLINE
1 table found.
(primary key columns are indicated with *)

Command> INSERT INTO bvar (col1, col2)
 > VALUES (0x4D7953514C, 0x39274D);
1 row inserted.

Command> select * from bvar;
 < 4D7953514C0000000000, 39274D >
1 row found.

Numeric precedence

The result type of an expression is determined by the operand with the highest type precedence. The numeric precedence order is as follows (highest to lowest):

For example, the sum of TT_INTEGER and BINARY_FLOAT values is type BINARY_FLOAT because BINARY_FLOAT has higher numeric precedence. Similarly, the product of NUMBER and BINARY_DOUBLE values is type BINARY_DOUBLE.

LOB data types

The large object (LOB) data types can store large and unstructured data such as text, image, video, and spatial data. LOBs include the BLOB, CLOB and NCLOB data types.

You can insert or update data in a column that is of a LOB data type. For update operations, you can set the LOB value to NULL, an empty value through EMPTY_CLOB or EMPTY_BLOB, or replace the entire LOB with new data. You can update a LOB value with another LOB value. If you delete a row containing a LOB column, you also delete the LOB value.

LOB data type semantics are similar to the following SQL semantics:

The following SQL statements, operators, and functions accept one or more of the LOB data types as arguments.


Note:

Support for LOB data types are detailed in the appropriate SQL operator, statement and function documentation.

Description

The following sections describe each LOB data type in more detail:

In addition, the following sections provide more details on LOBs in general:

BLOB

The Binary LOB (BLOB) data type stores unstructured binary large objects. The maximum size for BLOB data is 16 MB.


Note:

For details on assigning hexadecimal literals as binary data in TimesTen, see the description for the HexadecimalLiteral in "Constants".

When you define a BLOB in a column, you do not define the maximum number of characters as you would with VARBINARY and other variable length data types. Instead, the definition for the column would be as follows:

Command> CREATE TABLE blob_content ( 
 > id NUMBER PRIMARY KEY, 
 > blob_column BLOB ); 

To manipulate a BLOB, the following functions are provided:

  • There are two methods to initialize a BLOB, including the EMPTY_BLOB function to initialize an empty BLOB. For details on initializing a BLOB, see "Initializing LOBs". For details on how an empty LOB is different from a NULL LOB, see "Difference between NULL and empty LOBs".

  • To convert a binary value to a BLOB, use the TO_LOB or TO_BLOB functions. See "TO_BLOB" and "TO_LOB" for more details.

CLOB

The Character LOB (CLOB) data type stores single-byte and multibyte character data. The maximum size for CLOB data is 4 MB. The maximum number of characters that can be stored in the CLOB depends on whether you are using a single or multibyte character set.

When you define a CLOB in a column, you do not define the maximum number of characters as you would with VARCHAR and other variable length data types. Instead, the definition for the column would be as follows:

Command> CREATE TABLE clob_content ( 
 > id NUMBER PRIMARY KEY, 
 > clob_column CLOB ); 

To manipulate a CLOB, the following functions are provided:

  • There are two methods to initialize a CLOB, including the EMPTY_CLOB function to initialize an empty CLOB. For details on initializing a CLOB, see "Initializing LOBs". For details on how an empty LOB is different from a NULL LOB, see "Difference between NULL and empty LOBs".

  • To convert a character string to a CLOB, use the TO_LOB or TO_CLOB functions. See "TO_CLOB" and "TO_LOB" for more details.

NCLOB

The National Character LOB (NCLOB) data type stores Unicode data. The maximum size for an NCLOB data is 4 MB.

When you define a NCLOB in a column, you do not define the maximum number of characters as you would with VARCHAR and other variable length data types. Instead, the definition for the column would be as follows:

Command> CREATE TABLE nclob_content ( 
 > id NUMBER PRIMARY KEY, 
 > nclob_column NCLOB ); 

The following functions support the NCLOB data type:

  • There are two methods to initialize an NCLOB, including the EMPTY_CLOB function to initialize an empty NCLOB. For details on initializing a NCLOB, see "Initializing LOBs". For details on how an empty LOB is different from a NULL LOB, see "Difference between NULL and empty LOBs".

  • To convert a character string to an NCLOB, use the TO_LOB or TO_CLOB functions. See "TO_CLOB" and "TO_LOB" for more details.

Difference between NULL and empty LOBs

A NULL LOB is not the same as an empty LOB.

  • A NULL LOB has the value of NULL, so NULL is returned if you request a NULL LOB.

  • An empty LOB is initialized with either the EMPTY_CLOB or EMPTY_BLOB functions. These functions initialize the LOB to be a zero-length, non-NULL value. You can also use the EMPTY_CLOB or EMPTY_BLOB functions to initialize a LOB in a non-nullable column.

Initializing LOBs

You can initialize a LOB in one of two ways:

  • You can insert an empty LOB into a BLOB, CLOB or NCLOB column by using the EMPTY_BLOB or EMPTY_CLOB functions. This is useful when you do not have any data, but want to create the LOB in preparation for data. It is also useful for initializing non-nullable LOB columns.

  • Initialize the LOB by inserting data directly. There is no need to initialize a LOB using the EMPTY_BLOB or EMPTY_CLOB functions, you can simply insert the data directly.

The following demonstrates examples of each type of initialization:

You can initialize a LOB with the EMPTY_CLOB function, as shown with the following example:

Command> INSERT INTO clob_content (id, clob_column)
       > VALUES (1, EMPTY_CLOB( ) );
1 row inserted.

You can initialize a LOB by inserting data directly, as shown with the following example:

Command> INSERT INTO clob_content(id, clob_column)
 > VALUES (4, 'Demonstration of the LOB initialization.');
1 row inserted.

You can initialize or update an existing LOB value with the UPDATE statement, as shown with the following examples:

Command> UPDATE blob_content
 > SET blob_column = 0x000AF4511
 > WHERE id = 1;
1 row updated.

Command> select * from blob_content;
 < 1, 0000AF4511 >
1 rows found.

Command> UPDATE clob_content
 > SET clob_column = 'Demonstration of the CLOB data type '
 > WHERE id = 1;
1 row updated.

Command> SELECT * FROM clob_content;
 < 1, Demonstration of the CLOB data type >

ROWID data type

The address of a row in a table or materialized view is called a rowid. The rowid data type is ROWID. You can examine a rowid by querying the ROWID pseudocolumn. See "ROWID" for details on the ROWID pseudocolumn.

Specify literal ROWID values in SQL statements as constants enclosed in single quotes, as follows:

Command> SELECT ROWID, last_name 
> FROM employees 
> WHERE department_id = 20;

< BMUFVUAAACOAAAALhM, Hartstein >
< BMUFVUAAACOAAAAMhM, Fay >
2 rows found.

Command> SELECT ROWID, last_name FROM employees
       > WHERE ROWID='BMUFVUAAACOAAAALhM';
< BMUFVUAAACOAAAALhM, Hartstein >
1 row found.

The ROWID data type can be used as follows:

Implicit type conversions are supported for assigning values and comparison operations between ROWID and CHAR or between ROWID and VARCHAR2 data.

When CHAR, VARCHAR2, and ROWID operands are combined in COALESCE, DECODE, NVL, or CASE expressions, the result data type is ROWID. Expressions with CHAR and VARCHAR2 values are converted to ROWID values to evaluate the expression.

To use ROWID values with string functions such as CONCAT, the application must convert ROWID values explicitly to CHAR values using the SQL TO_CHAR function.

Datetime data types

The datetime data types are as follows:

DATE

The format of a DATE value is YYYY-MM-DD HH:MI:SS and ranges from -4712-01-01 (January 1, 4712 BC) to 9999-12-31 (December 31, 9999 AD). There are no fractional seconds. The DATE type requires seven bytes of storage.

TimesTen does not support user-specified NLS_DATE_FORMAT settings. The SQL TO_CHAR and TO_DATE functions can be used to specify other formats.

TIME

The format of a TIME value is HH:MI:SS and ranges from 00:00:00 (midnight) to 23:59:59 (11:59:59 pm). The TIME data type requires eight bytes of storage.

TIMESTAMP

The format of a TIMESTAMP value is YYYY-MM-DD HH:MI:SS [.FFFFFFFFF]. The fractional seconds precision range is 0 to 9. The default is 6. The date range is from -4712-01-01 (January 1, 4712 BC) to 9999-12-31 (December 31, 9999 AD). The TIMESTAMP type requires 12 bytes of storage. The TIMESTAMP type has a larger date range and supports more precision than TT_TIMESTAMP.

TimesTen does not support user-specified NLS_TIMESTAMP_FORMAT settings. The SQL TO_CHAR and TO_DATE functions can be used to specify other formats.

TT_DATE

The format of a TT_DATE value is YYYY-MM-DD and ranges from 1753-01-01 (January 1, 1753 AD) to 9999-12-31 (December 31, 9999 AD). The TT_DATE data type requires four bytes of storage.

TT_TIMESTAMP

The format of a TT_TIMESTAMP value is YYYY-MM-DD HH:MI:SS [.FFFFFFFFF]. The fractional seconds precision is 6. The range is from 1753-01-01 00:00:00 (January 1, 1753, midnight) to 9999-12-31 23:59:59 (December 31, 9999, 11:59:59 PM). The TT_TIMESTAMP type requires eight bytes of storage. TT_TIMESTAMP is faster than the TIMESTAMP data type and has a smaller storage size.

TimesTen intervals

This section includes the following topics:

Using interval data types

If you are using TimesTen type mode, refer to the Oracle TimesTen In-Memory Database API and SQL Reference Guide, Release 6.0.3, for information on interval types.

TimesTen supports interval types only in a constant specification or intermediate expression result. Interval types cannot be the final result. Columns cannot be defined with an interval type. See "Type specifications".

You can specify a single-field literal that is an interval in an expression, but you cannot specify a complete expression that returns an interval data type. Instead, the EXTRACT function must be used to extract the desired component of the interval result.

TimesTen supports interval literals of the following form:

INTERVAL [+/-] CharString IntervalQualifier

Using DATE and TIME data types

This section shows some DATE, TIME, and TIMESTAMP data type examples:

To create a table named sample that contains a column dcol of type DATE and a column tcol of type TIME, use the following:

CREATE TABLE sample (tcol TIME, dcol DATE);

To insert DATE and TIME values into the sample table, use this:

INSERT INTO sample VALUES (TIME '12:00:00', DATE '1998-10-28');

To select all rows in the sample table that are between noon and 4:00 p.m. on October 29, 1998, use the following:

SELECT * FROM sample WHERE dcol = DATE '1998-10-29' 
AND tcol BETWEEN TIME '12:00:00' AND TIME '16:00:00';

To create a table named sample2 that contains a column tscol of type TIMESTAMP and then select all rows in the table that are between noon and 4:00 p.m. on October 29, 1998, use these statements:

CREATE TABLE sample2 (tscol TIMESTAMP);
INSERT INTO sample2 VALUES (TIMESTAMP '1998-10-28 12:00:00');
SELECT * FROM sample2 WHERE tscol
BETWEEN TIMESTAMP '1998-10-29 12:00:00' AND '1998-10-29 16:00:00';

Note:

TimesTen enables both literal and string formats of the TIME, DATE, and TIMESTAMP types. For example, timestring ('12:00:00') and timeliteral (TIME '16:00:00') are both valid ways to specify a TIME value. TimesTen reads the first value as CHAR type and later converts it to TIME type as needed. TimesTen reads the second value as TIME. The examples above use the literal format. Any values for the fraction not specified in full microseconds result in a "Data truncated" error.

Handling timezone conversions

TimesTen does not support TIMEZONE. TIME and TIMESTAMP data type values are stored without making any adjustment for time difference. Applications must assume one time zone and convert TIME and TIMESTAMP to that time zone before sending values to the database. For example, an application can assume its time zone to be Pacific Standard Time. If the application is using TIME and TIMESTAMP values from Pacific Daylight Time or Eastern Standard Time, for example, the application must convert TIME and TIMESTAMP to Pacific Standard Time.

Datetime and interval data types in arithmetic operations

If you are using TimesTen type mode, see Oracle TimesTen In-Memory Database API and SQL Reference Guide, Release 6.0.3, for information about datetime and interval types in arithmetic operations

You can perform numeric operations on date, timestamp and interval data. TimesTen calculates the results based on the rules:

  • You can add or subtract a numeric value to or from a ORA_DATE or ORA_TIMESTAMP value. TimesTen internally converts ORA_TIMESTAMP values to ORA_DATE values.

  • You can add or subtract a numeric value to or from a TT_DATE or TT_TIMESTAMP value and the resulting value is TT_DATE or TT_TIMESTAMP respectively.

  • Numeric values are treated as number of days. For example, SYSDATE + 1 is tomorrow. SYSDATE - 7 is one week ago.

  • Subtracting two date columns results in the number of days between the two dates. The return type is numeric.

  • You cannot add date values. You cannot multiple or divide date or timestamp values.

Table 1-5 is a matrix of datetime arithmetic operations. Dashes represent operations that are not supported. The matrix assumes that you are using Oracle type mode:

Table 1-5 DateTime arithmetic operations


DATETT_DATETIMESTAMPTT_TIMESTAMPNUMERICINTERVAL

DATE







+ (plus)





DATE

DATE

- (minus)

NUMBER

NUMBER

INTERVAL

INTERVAL

DATE

DATE

* (multiply)







/ (divide)







TT_DATE







+ (plus)





TT_DATE

TT_DATE

- (minus)

NUMBER

TT_BIGINT

INTERVAL

INTERVAL

TT_DATE

TT_DATE

* (multiply)







/ (divide)







TIMESTAMP







+ (plus)





DATE

TIMESTAMP

- (minus)

INTERVAL

INTERVAL

INTERVAL

INTERVAL

DATE

TIMESTAMP

* (multiply)







/ (divide)







TT_TIMESTAMP







+ (plus)





TT_TIMESTAMP

TT_TIMESTAMP

- (minus)

INTERVAL

INTERVAL

INTERVAL

INTERVAL

TT_TIMESTAMP

TT_TIMESTAMP

* (multiply)







/ (divide)







NUMERIC







+ (plus)

DATE

TT_DATE

DATE

TT_TIMESTAMP

Not applicable


- (minus)





Not applicable


* (multiply)





Not applicable

INTERVAL

/ (divide)





Not applicable


INTERVAL







+ (plus)

DATE

TT_DATE

TIMESTAMP

TT_TIMESTAMP


INTERVAL

- (minus)






INTERVAL

* (multiply)





INTERVAL


/ (divide)





INTERVAL




Note:

An interval data type cannot be the final result of a complete expression. The EXTRACT function must be used to extract the desired component of this interval result.

SELECT tt_date1 - tt_date2 FROM t1;
SELECT EXTRACT(DAY FROM timestamp1-timestamp2) FROM t1;
SELECT * FROM t1 WHERE timestamp1 - timestamp2 = NUMTODSINTERVAL(10, 'DAY');
SELECT SYSDATE + NUMTODSINTERVAL(20,'SECOND') FROM dual;
SELECT EXTRACT (SECOND FROM timestamp1-timestamp2) FROM dual;
/* select the microsecond difference between two timestamp values d1 and d2 */
SELECT 1000000*(EXTRACT(DAY FROM d1-d2)*24*3600+
EXTRACT(HOUR FROM d1-d2)*3600+
EXTRACT(MINUTE FROM d1-d2)*60+EXTRACT(SECOND FROM d1-d2) FROM d1;

This example inserts TIMESTAMP values into two columns and then subtracts the two values using the EXTRACT function:

Command> CREATE TABLE ts (id TIMESTAMP, id2 TIMESTAMP);
Command> INSERT INTO ts VALUES (TIMESTAMP '2007-01-20 12:45:23', 
       > TIMESTAMP '2006-12-25 17:34:22');
1 row inserted.
Command> SELECT EXTRACT (DAY FROM id - id2) FROM ts;
< 25 >
1 row found.

The following queries return errors. You cannot select an interval result:

SELECT timestamp1 - timestamp2 FROM t1;

You cannot compare an INTERVAL YEAR TO MONTH with an INTERVAL DAY TO SECOND:

SELECT * FROM t1 WHERE timestamp1 - timestamp2 = NUMTOYMINTERVAL(10, 'YEAR');

You cannot compare an INTERVAL DAY TO SECOND with an INTERVAL DAY:

SELECT * FROM t1 WHERE timestamp1 - timestamp2 = INTERVAL '10' DAY;

You cannot extract YEAR from an INTERVAL DAY TO SECOND:

SELECT EXTRACT (YEAR FROM timestamp1 - timestamp2) FROM dual;

Restrictions on datetime and interval arithmetic operations

Consider these restrictions when performing datetime and interval arithmetic:

  • The results for addition and subtraction with DATE and TIMESTAMP types for INTERVAL YEAR and INTERVAL MONTH are not closed. For example, adding one year to the DATE or TIMESTAMP of '2004-02-29' results in a date arithmetic error (TimesTen error 2787) because February 29, 2005 does not exist (2005 is not a leap year). Adding INTERVAL '1' month to DATE '2005-01-30' also results in the same error because February never has 30 days.

  • The results are closed for INTERVAL DAY.

  • An interval data type cannot be the final result of a complete expression. The EXTRACT function must be used to extract the desired component of the interval result.

Storage requirements

Variable-length columns whose declared column length is greater than 128 bytes are stored out of line. Variable-length columns whose declared column length is less than or equal to 128 bytes are stored inline. All LOB data types are stored out of line.

For character semantics, the number of bytes stored out of line is dependent on the character set. For example, for a character set with four bytes per character, variable-length columns whose declared column length is greater than 32 (128/4) are stored out of line.

Table 1-6 shows the storage requirements of the various data types.

Table 1-6 Data type storage requirements

TypeStorage required

BINARY(n)

n bytes.

BINARY_DOUBLE

Eight bytes.

BINARY_FLOAT

Four bytes.

CHAR(n[BYTE|CHAR])

n bytes or, if character semantics, n characters. If character semantics, the length of the column (n) is based on length semantics and character set.

DATE

Seven bytes.

Interval

An interval type cannot be stored in TimesTen.

NCHAR(n)

Bytes required is 2*n where n is the number of characters.

NUMBER

Five to 22 bytes.

NVARCHAR2(n)

For NOT INLINE columns:

On 32-bit platforms, 2*(length of value) + 20 bytes (minimum of 28 bytes).

On 64-bit platforms, 2*(length of value) + 24 bytes (minimum of 40 bytes).

For INLINE columns:

On 32-bit platforms, 2*(length of column) + 4 bytes.

On 64-bit platforms, 2*(length of column) + 8 bytes.

ROWID

Twelve bytes.

TIMESTAMP

Twelve bytes.

TT_BIGINT

Eight bytes.

TT_DATE

Four bytes.

TT_DECIMAL(p,s)

Approximately p/2 bytes.

TT_INT[EGER]

Four bytes.

TT_SMALLINT

Two bytes.

TT_TIME

Eight bytes.

TT_TIMESTAMP

Eight bytes.

TT_TINYINT

One byte.

VARBINARY(n)

For NOT INLINE columns:

On 32-bit platforms, length of value + 20 bytes (minimum of 28 bytes).

On 64-bit platforms, length of value + 24 bytes (minimum of 40 bytes).

For INLINE columns:

On 32-bit platforms, length of column + 4 bytes.

On 64-bit platforms, length of column + 8 bytes.

VARCHAR2(n[BYTE|CHAR])

For NOT INLINE columns:

On 32-bit platforms, length of value + 20 bytes (minimum of 28 bytes). NULL value is stored as (null bit) + 4 bytes, or 4.125 bytes.

On 64-bit platforms, length of value + 24 bytes (minimum of 40 bytes). NULL value is stored as (null bit) + 8 bytes, or 8.125 bytes.

This storage principal holds for all variable length NOT INLINE data types: TT_VARCHAR, TT_NVARCHAR, VARCHAR2, NVARCHAR2, and VARBINARY.

For INLINE columns:

On 32-bit platforms, n + 4 bytes. NULL value is stored as (null bit) + n + 4 bytes.

On 64-bit platforms, n + 8 bytes. NULL value is stored as (null bit) + n + 8 bytes.

If character semantics, the length of the column (n) is based on length semantics and character set.

BLOB and CLOB

On 32-bit platforms, length of value + 36 bytes (minimum of 40 bytes).

On 64-bit platforms, length of value + 48 bytes (minimum of 56 bytes).

NCLOB

On 32-bit platforms, 2 * (length of value) + 36 bytes (minimum of 40 bytes).

On 64-bit platforms, 2 * (length of value) + 48 bytes (minimum of 56 bytes).


Data type comparison rules

This section describes how values of each data type are compared in TimesTen.

Numeric values

A larger value is greater than a smaller value: -1 is less than 10, and -10 is less than -1.

The floating-point value NaN is greater than any other numeric value and is equal to itself.

Date values

A later date is considered greater than an earlier one. For example, the date equivalent of '10-AUG-2005' is less than that of '30-AUG-2006', and '30-AUG-2006 1:15 pm' is greater than '30-AUG-2006 10:10 am'.

Character values

Character values are compared in the following ways:

Binary and linguistic sorting

In binary sorting, TimesTen compares character strings according to the concatenated value of the numeric codes of the characters in the database character set. One character is greater than the other if it has a greater numeric values than the other in the character set. Blanks are less than any character.

Linguistic sorting is useful if the binary sequence of numeric codes does not match the linguistic sequence of the characters you are comparing. In linguistic sorting, SQL sorting and comparison are based on the linguistic rule set by NLS_SORT. For more information on linguistic sorts, see "Linguistic sorts" in Oracle TimesTen In-Memory Database Operations Guide.

The default is binary sorting.

Blank-padded and nonpadded comparison semantics

With blank-padded semantics, if two values have different lengths, TimesTen adds blanks to the shorter value until both lengths are equal. Values are then compared character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. Thus, two values are considered equal if they differ only in the number of trailing blanks.

Blank-padded semantics are used when both values in the comparison are expressions of type CHAR or NCHAR or text literals.

With nonpadded semantics, two values are compared, character by character, up to the first character that differs. The value with the greater character in that position is considered greater. If two values that have differing lengths are identical up to the end of the shorter one, then the longer one is considered greater. If two values of equal length have no differing characters, they are considered equal.

Nonpadded semantics are used when both values in the comparison have the type VARCHAR2 or NVARCHAR2.

An example with blank-padded semantics:

'a   ' = 'a'

An example with nonpadded semantics:

'a   ' > 'a'

Data type conversion

Generally an expression cannot contain values of different data types. However, TimesTen supports both implicit and explicit conversion from one data type to another. Because algorithms for implicit conversion are subject to change across software releases and the behavior of explicit conversions is more predictable, TimesTen recommends explicit conversion.

Implicit data type conversion

TimesTen converts a value from one data type to another when such a conversion makes sense.

Table 1-7 and Table 1-8 use a matrix to illustrate TimesTen implicit data type conversions. YES in the cell indicates the conversion is supported. NO in the cell indicates the conversion is not supported. The rules for implicit conversion follow the table.

Table 1-7 Implicit data type conversion


CHARVARCHAR2NCHARNVARCHAR2DATETT_DATETIMESTAMPTT_TIMESTAMP

CHAR


YES

YES

YES

YES

YES

YES

YES

VARCHAR2

YES


YES

YES

YES

YES

YES

YES

NCHAR

YES

YES


YES

YES

YES

YES

YES

NVARCHAR2

YES

YES

YES


YES

YES

YES

YES

DATE

YES

YES

YES

YES


YES

YES

YES

TT_DATE

YES

YES

YES

YES

YES


YES

YES

TIMESTAMP

YES

YES

YES

YES

YES

YES


YES

TT_TIMESTAMP

YES

YES

YES

YES

YES

YES

YES


NUMERIC

YES

YES

YES

YES

NO

NO

NO

NO

BLOB

NO

NO

NO

NO

NO

NO

NO

NO

CLOB

YES

YES

YES

YES

NO

NO

NO

NO

NCLOB

YES

YES

YES

YES

NO

NO

NO

NO

BINARY/VARBINARY

YES

YES

YES

YES

NO

NO

NO

NO

ROWID

YES

YES

YES

YES

NO

NO

NO

NO


Table 1-8 Implict data type conversion (continued)


NUMERICBLOBCLOBNCLOBBINARY/VARBINARYROWID

CHAR

YES

YES

YES

YES

YES

YES

VARCHAR2

YES

YES

YES

YES

YES

YES

NCHAR

YES

YES

YES

YES

YES

YES

NVARCHAR2

YES

YES

YES

YES

YES

YES

DATE

NO

NO

NO

NO

NO

NO

TT_DATE

NO

NO

NO

NO

NO

NO

TIMESTAMP

NO

NO

NO

NO

NO

NO

TT_TIMESTAMP

NO

NO

NO

NO

NO

NO

NUMERIC


NO

NO

NO

NO

NO

BLOB

NO


NO

NO

YES

NO

CLOB

NO

NO


YES

NO

NO

NCLOB

NO

NO

YES


NO

NO

BINARY/VARBINARY

NO

YES

YES

YES


NO

ROWID

NO

NO

NO

NO

NO



The following rules apply:

  • During arithmetic operations on and comparisons between character and non-character data types, TimesTen converts from any character data type to a numeric or datetime data type as appropriate. In arithmetic operations between CHAR/VARCHAR2 and NCHAR/NVARCHAR2, TimesTen converts to a NUMBER.

  • During arithmetic operations, floating point values INF and NAN are not supported when converting character values to numeric values.

  • During concatenation operations, TimesTen converts non-character data types to CHAR, NCHAR, VARCHAR2, or NVARCHAR2 depending on the other operand.

  • When comparing a character value with a numeric value, TimesTen converts the character data to a numeric value.

  • When comparing a character value with a datetime value, TimesTen converts the character data to a datetime value.

  • During conversion from a timestamp value to a DATE value, the fractional seconds portion of the timestamp value is truncated.

  • Conversions from BINARY_FLOAT to BINARY_DOUBLE are exact.

  • Conversions from BINARY_DOUBLE to BINARY_FLOAT are inexact if the BINARY_DOUBLE value uses more bits of precision that supported by the BINARY_FLOAT.

  • Conversions between either character values or exact numeric values (TT_TINYINT, TT_SMALLINT, TT_INTEGER, TT_BIGINT, NUMBER) and floating-point values (BINARY_FLOAT, BINARY_DOUBLE) can be inexact because the character values and the exact numeric values use decimal precision whereas the floating-point numbers use binary precision.

  • When manipulating numeric values, TimesTen usually adjusts precision and scale to allow for maximum capacity. In such cases, the numeric data type resulting from such operations can differ from the numeric data type found in the underlying tables.

  • When making assignments, TimesTen converts the value on the right side of the equal sign (=) to the data type of the target of the assignment on the left side.

  • When you use a SQL function or operator with an argument of a data type other than the one it accepts, TimesTen converts the argument to the accepted data type so long as TimesTen supports the implicit conversion. For more information on supported data type conversions, see Implicit data type conversion.

  • During INSERT, INSERT... SELECT, and UPDATE operations, TimesTen converts the value to the data type of the affected column.

  • Implicit and explicit CHAR/VARCHAR2 <-> NCHAR/NVARCHAR2 conversions are supported except when the character set is TIMESTEN8. An example of implicit conversion:

    Command> CREATE TABLE convdemo (c1 CHAR (10), x1 TT_INTEGER);
    Command> CREATE TABLE convdemo2 (c1 NCHAR (10), x2 TT_INTEGER);
    Command> INSERT INTO convdemo VALUES ('ABC', 10);
    1 row inserted.
    Command> INSERT INTO convdemo VALUES ('def', 100);
    1 row inserted.
    Command> INSERT INTO convdemo2 SELECT * FROM convdemo;
    2 rows inserted.
    Command> SELECT x1,x2,convdemo.c1, convdemo2.c1 
           > FROM convdemo, convdemo2 where Convdemo.c1 = convdemo2.c1;
    X1, X2, C1, C1
    < 10, 10, ABC       , ABC        >
    < 100, 100, def       , def        >
    2 rows found.
    

Null values

The value NULL indicates the absence of a value. It is a placeholder for a value that is missing. Use a NULL when the actual value is not known or when a value would not be meaningful. Do not use NULL to represent a numeric value of zero, because they are not equivalent. Any parameter in an expression can contain NULL regardless of its data type. In addition, any column in a table can contain NULL, regardless of its data type, unless you specify NOT NULL or PRIMARY KEY integrity constraints for the column when you create the table.

The following properties of NULL affect operations on rows, parameters, or local variables:

Because of these properties, TimesTen ignores columns, rows, or parameters containing NULL when:

In several SQL predicates, described in Chapter 5, "Search Conditions," you can explicitly test for NULL. APIs supported by TimesTen offer ways to handle null values. For example, in an ODBC application, use the functions SQLBindCol, SQLBindParameter, SQLGetData, and SQLParamData to handle input and output of NULL values.

INF and NAN

TimesTen supports the IEEE floating-point values Inf (positive infinity), -Inf (negative infinity), and NaN (not a number).

Constant values

You can use constant values in places where a floating-point constant is allowed. The following constants are supported:

  • BINARY_FLOAT_INFINITY

  • -BINARY_FLOAT_INFINITY

  • BINARY_DOUBLE_INFINITY

  • -BINARY_DOUBLE_INFINITY

  • BINARY_FLOAT_NAN

  • BINARY_DOUBLE_NAN

In the following example, a table is created with a column of type BINARY_FLOAT and a column of type TT_INTEGER. BINARY_FLOAT_INFINITY and BINARY_FLOAT_NAN are inserted into the column of type BINARY_FLOAT.

Command> CREATE TABLE bfdemo (id BINARY_FLOAT, Ii2 TT_INTEGER);
Command> INSERT INTO bfdemo VALUES (BINARY_FLOAT_INFINITY, 50);
1 row inserted.
Command> INSERT INTO bfdemo VALUES (BINARY_FLOAT_NAN, 100);
1 row inserted.
Command> SELECT * FROM bfdemo;
< INF, 50 >
< NAN, 100 >
2 rows found.

Primary key values

Inf, -Inf, and NaN are acceptable values in columns defined with a primary key. This is different from NULL, which is not allowed in columns defined with a primary key.

You can only insert Inf, -Inf, and NaN values into BINARY_FLOAT and BINARY_DOUBLE columns.

Selecting Inf and NaN (floating-point conditions)

Floating-point conditions determine whether an expression is infinite or is the undefined result of an operation (NaN, meaning not a number).

Consider the following syntax:

Expression IS [NOT] {NAN|INFINITE}

Expression must either resolve to a numeric data type or to a data type that can be implicitly converted to a numeric data type.

The following table describes the floating-point conditions.

ConditionOperationExample
IS [NOT] NANReturns TRUE if Expression is the value NaN when NOT is not specified. Returns TRUE if Expression is not the value NaN when NOT is specified.
SELECT * FROM bfdemo WHERE id IS
NOT NAN;
ID, ID2
< INF, 50 >
1 row found.
IS [NOT] INFINITEReturns TRUE if Expression is the value +Inf or -Inf when NOT is not specified. Returns TRUE if Expression is neither +Inf nor -Inf when NOT is specified.
SELECT * FROM bfdemo WHERE id IS
NOT INFINITE;
ID, ID2
< NAN, 100 >
1 row found.


Note:

The constant keywords represent specific BINARY_FLOAT and BINARY_DOUBLE values. The comparison keywords correspond to properties of a value and are not specific to any type, although they can only evaluate to TRUE for BINARY_FLOAT or BINARY_DOUBLE types or types that can be converted to BINARY_FLOAT or BINARY_DOUBLE.

The following rules apply to comparisons with Inf and NaN:

  • Comparison between Inf (or -Inf) and a finite value are as expected. For example, 5 > -Inf.

  • (Inf = Inf) and (Inf > -Inf) both evaluate to TRUE.

  • (NaN = NaN) evaluates to TRUE.

In reference to collating sequences:

  • -Inf sorts lower than any other value.

  • Inf sorts lower than NaN and NULL and higher than any other value.

  • NaN sorts higher than Inf.

  • NULL sorts higher than NaN. NULL is always the largest value in any collating sequence.

Expressions involving Inf and NaN

  • Expressions containing floating-point values may generate Inf, -Inf, or NaN. This can occur either because the expression generated overflow or exceptional conditions or because one or more of the values in the expression was Inf, -Inf, or NaN. Inf and NaN are generated in overflow or division-by-zero conditions.

  • Inf, -Inf, and NaN values are not ignored in aggregate functions. NULL values are. If you want to exclude Inf and NaN from aggregates, or from any SELECT result, use both the IS NOT NAN and IS NOT INFINITE predicates.

Overflow and truncation

Some operations can result in data overflow or truncation. Overflow results in an error and can generate Inf. Truncation results in loss of least significant data.

Exact values are truncated only when they are stored in the database by an INSERT or UPDATE statement, and if the target column has smaller scale than the value. TimesTen returns a warning when such truncation occurs. If the value does not fit because of overflow, TimesTen returns the special value Inf and does not insert the specified value.

TimesTen may truncate approximate values during computations, when values are inserted into the database, or when database values are updated. TimesTen returns an error only upon INSERT or UPDATE. When overflow with approximate values occurs, TimesTen returns the special value Inf.

There are several circumstances that can cause overflow:

Truncation can cause an error or warning for alphanumeric or numeric data types:

Underflow

When an approximate numeric value is too close to zero to be represented by the hardware, TimesTen underflows to zero and returns a truncation warning.

Replication limits

TimesTen places the following limits on the size of data types in a database that is being replicated:

TimesTen type mode (backward compatibility)

TimesTen supports a data type backward compatibility mode called TimesTen type mode. This is specified using the data store creation attribute TypeMode, where TypeMode=1 indicates TimesTen mode. Type mode determines the default data type. For example, DATE in TimesTen type mode defaults to TT_DATE; DATE in Oracle type mode defaults to ORA_DATE.

For more information on type modes, see "TypeMode" in Oracle TimesTen In-Memory Database Reference. For information on data type usage in TimesTen type mode, refer to Oracle TimesTen In-Memory Database API and SQL Reference Guide,cB Release 6.0.3.

Data types supported in TimesTen type mode

Table 1-9 Data types supported in TimesTen type mode

Data typeDescription

BIGINT

A signed eight-byte integer in the range -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (263-1).

Alternatively, specify TT_BIGINT.

BINARY(n)

Fixed-length binary value of n bytes. Legal values for n range from 1 to 8300.

BINARY data is padded to the maximum column size with trailing zeroes.

BINARY_DOUBLE

A 64-bit floating-point number. BINARY_DOUBLE is a double-precision native floating point number. Supports +Inf, -Inf, and NaN values. BINARY_DOUBLE is an approximate numeric value consisting of an exponent and mantissa. You can use exponential or E-notation. BINARY_DOUBLE has binary precision 53.

Minimum positive finite value: 2.22507485850720E-308

Maximum positive finite value: 1.79769313486231E+308

Alternatively, specify DOUBLE [PRECISION] or FLOAT[(53)].

BINARY_FLOAT

A 32-bit floating-point number. BINARY_FLOAT is a single-precision native floating-point type. Supports +Inf, -Inf, and NaN values. BINARY_FLOAT is an approximate numeric value consisting of an exponent and mantissa. You can use exponential or E-notation. BINARY_FLOAT has binary precision 24.

Minimum positive finite value: 1.17549E-38F

Maximum positive finite value: 3.40282E+38F

Alternatively, specify REAL or FLOAT(24).

CHAR[ACTER][(n [BYTE|CHAR])]

Fixed-length character string of length n bytes or characters. Default is one byte.

BYTE indicates that the column has byte-length semantics. Legal values for n bytes range from 1 to 8300.

CHAR indicates that the column has character-length semantics. The minimum CHAR length is one character. The maximum CHAR length depends on how many characters fit in 8300 bytes. This is determined by the database character set in use. For character set AL32UTF8, up to four bytes per character may be needed, so the CHAR length limit ranges from 2075 to 8300 depending on the character set.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

CHAR data is padded to the maximum column size with trailing blanks. Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

Alternatively, specify TT_CHAR[(n [BYTE|CHAR])].

DATE

Stores date information: century, year, month, and day. The format is YYYY-MM-DD, where MM is expressed as an integer. For example: 2006-10-28.

Storage size is four bytes.

Valid dates are between 1753-01-01 (January 1,1753) and 9999-12-31 (December 31, 9999).

Alternatively, specify TT_DATE.

DEC[IMAL][(p[,s])] or

NUMERIC[(p[,s])]

An exact numeric value with a fixed maximum precision (total number of digits) and scale (number of digits to the right of the decimal point). The value of precision p must be between 1 and 40. The value of scale s must be between 0 and p. The default precision is 40 and the default scale is 0.

INTERVAL [+/-] IntervalQualifier

TimesTen partially supports interval types, expressed with INTERVAL and an IntervalQualifier. An IntervalQualifier can specify only a single field type with no precision. The default leading precision is eight digits for all interval types. The single field type can be one of: YEAR, MONTH, DAY, HOUR, MINUTE, or SECOND. Currently, interval types can be specified only with a constant.

NCHAR[(n)]

Fixed-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NCHAR character limits are half the byte limits, so the maximum size is 4150. Default and minimum bytes of storage is 2n (2).

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

NCHAR data is padded to the maximum column size with U+0020 SPACE. Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

Alternatively, specify TT_NCHAR[(n)].

NATIONAL CHARACTER and NATIONAL CHAR are synonyms for NCHAR.

SMALLINT

A native signed 16-bit integer in the range -32,768 (-215) to 32,767 (215-1).

Alternatively, specify TT_SMALLINT.

TIME

A time of day between 00:00:00 (midnight) and 23:59:59 (11:59:59 pm), inclusive. The format is: HH:MI:SS. Storage size is eight bytes.

TIMESTAMP

A date and time between 1753-01-01 00:00:00 (midnight on January 1, 1753) and 9999-12-31 23:59:59 pm (11:59:59 pm on December 31, 9999), inclusive. Any values for the fraction not specified in full microseconds result in a "Data Truncated" error. The format is YYYY-MM-DD HH:MI:SS [.FFFFFFFFF].

Storage size is eight bytes.

Alternatively, specify TT_TIMESTAMP or [TT_]TIMESTAMP(6).

TINYINT

Unsigned integer ranging from 0 to 255 (28-1).

Since TINYINT is unsigned, the negation of a TINYINT is SMALLINT.

Alternatively, specify TT_TINYINT.

INT[EGER]

A signed integer in the range -2,147,483,648 (-231) to 2,147,483,647 (231-1).

Alternatively, specify TT_INTEGER.

NVARCHAR(n)

Variable-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NVARCHAR character limits are half the byte limits so the maximum size is 2,097,152 (221). You must specify n.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

Alternatively, specify TT_NVARCHAR(n).

NATIONAL CHARACTER VARYING, NATIONAL CHAR VARYING, and NCHAR VARYING are synonyms for NVARCHAR.

VARCHAR(n[BYTE|CHAR])

Variable-length character string having maximum length n bytes or characters. You must specify n.

BYTE indicates that the column has byte-length semantics. Legal values for n bytes range from 1 to 4194304 (222).

CHAR indicates that the column has character-length semantics.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

Alternatively, specify TT_VARCHAR(n[BYTE|CHAR]).

VARBINARY(n)

Variable-length binary value having maximum length n bytes. Legal values for n range from 1 to 4194304 (222).


Oracle data types supported in TimesTen type mode

Table 1-10 Oracle data types supported in TimesTen type mode

Data typeDescription

NUMBER[(p [,s])]

Number having precision and scale. The precision value ranges from 1 to 38 decimal. The scale value ranges from -84 to 127. Both precision and scale are optional.

If you do not specify a precision or a scale, then maximum precision of 38 and flexible scale are assumed.

NUMBER supports scale > precision and negative scale.

NUMBER stores zero as well as positive and negative fixed numbers with absolute values from 1.0 x 10-130 up to but not including 1.0 x 10126. If you specify an arithmetic expression whose value has an absolute value greater than or equal to 1.0 x 10126, then TimesTen returns an error.

In TimesTen type mode, the NUMBER data type stores 10E-89 as its smallest (closest to zero) value.

ORA_CHAR[(n [BYTE|CHAR])]

Fixed-length character string of length n bytes or characters. Default is one byte.

BYTE indicates that the column has byte-length semantics. Legal values for n bytes range from 1 to 8300.

CHAR indicates that the column has character-length semantics. The minimum CHAR length is one character. The maximum CHAR length depends on how many characters fit in 8300 bytes. This is determined by the database character set in use. For character set AL32UTF8, up to four bytes per character may be needed, so the CHAR length limit ranges from 2075 to 8300 depending on the character set.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

ORA_CHAR data is padded to the maximum column size with trailing blanks. Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

ORA_DATE

Stores date and time information: century, year, month, date, hour, minute, and second. Format is YYYY-MM-DD HHMMSS.

Valid date range is from January 1, 4712 BC to December 31, 9999 AD.

The storage size is seven bytes. There are no fractional seconds.

ORA_NCHAR[(n)]

Fixed-length string of length n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. NCHAR character limits are half the byte limits so the maximum size is 4150. Default and minimum bytes of storage is 2n (2).

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

ORA_NCHAR data is padded to the maximum column size with U+0020 SPACE. Blank-padded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

ORA_NVARCHAR2(n)

Variable-length string of n two-byte Unicode characters.

The number of bytes required is 2*n where n is the specified number of characters. ORA_NVARCHAR2 character limits are half the byte limits so the maximum size is 2,097,152 (221). You must specify n.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

Nonpadded comparison semantics are used.

For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

ORA_VARCHAR2(n[BYTE|CHAR])

Variable-length character string having maximum length n bytes or characters.

BYTE indicates that the column has byte-length semantics. Legal values for n bytes range from 1 to 4194304 (222). You must specify n.

CHAR indicates that the column has character-length semantics.

A zero-length string is a valid non-NULL value. The string value "" is an empty, zero-length string, but not a NULL value. However, in PL/SQL, a zero-length string is always considered to be NULL. Therefore, when you use PL/SQL, any empty string parameter in SQL is converted to NULL by PL/SQL before the value is passed to the TimesTen database.

Nonpadded comparison semantics are used. For information on blank-padded and nonpadded semantics, see "Blank-padded and nonpadded comparison semantics".

ORA_TIMESTAMP

[(fractional_seconds_precision)]

Stores year, month, and day values of the date data type plus hour, minute, and second values of time. Fractional_seconds_precision is the number of digits in the fractional part of the seconds field. Valid date range is from January 1, 4712 BC to December 31, 9999 AD.

The fractional seconds precision range is 0 to 9. The default is 6. Format is:

YYYY-MM-DD HH:MI:SS [.FFFFFFFFF]

Storage size is 12 bytes.


PKccPK*AOEBPS/title.htmn Oracle TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2)

Oracle® TimesTen In-Memory Database

SQL Reference

11g Release 2 (11.2.2)

E21642-04

September 2012


Oracle TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2)

E21642-04

Copyright © 1996, 2012, Oracle and/or its affiliates. All rights reserved.

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are "commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, shall be subject to license terms and license restrictions applicable to the programs. No other rights are granted to the U.S. Government.

This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.

This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.

PK\qsnPK*AOEBPS/preface.htm)} Preface

Preface

Oracle TimesTen In-Memory Database is a memory-optimized relational database. Deployed in the application tier, TimesTen operates on databases that fit entirely in physical memory using standard SQL interfaces.

Audience

This document provides a reference for TimesTen SQL data types, statements, expressions, functions, including TimesTen SQL extensions.

To work with this guide, you should understand how database systems work. You should also have knowledge of SQL (Structured Query Language).

Related documents

TimesTen documentation is available on the product distribution media and on the Oracle Technology Network:

http://www.oracle.com/technetwork/products/timesten/documentation/

Conventions

TimesTen supports multiple platforms. Unless otherwise indicated, the information in this guide applies to all supported platforms. The term Windows refers to all supported Windows platforms and the term UNIX applies to all supported UNIX platforms and also to Linux. Refer to the "Platforms" section in Oracle TimesTen In-Memory Database Release Notes for specific platform versions supported by TimesTen.


Note:

In TimesTen documentation, the terms "data store" and "database" are equivalent. Both terms refer to the TimesTen database unless otherwise noted.

This document uses the following text conventions:

ConventionMeaning
boldfaceBoldface type indicates graphical user interface elements associated with an action, or terms defined in text or the glossary.
italicItalic type indicates book titles, emphasis, or placeholder variables for which you supply particular values.
monospaceMonospace type indicates commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter.
italic monospaceItalic monospace type indicates a variable in a code example that you must replace. For example:

Driver=install_dir/lib/libtten.sl

Replace install_dir with the path of your TimesTen installation directory.

[ ]Square brackets indicate that an item in a command line is optional.
{ }Curly braces indicated that you must choose one of the items separated by a vertical bar ( | ) in a command line.
|
A vertical bar (or pipe) separates alternative arguments.
. . .An ellipsis (. . .) after an argument indicates that you may use more than one argument on a single command line.
%
The percent sign indicates the UNIX shell prompt.
#
The number (or pound) sign indicates the UNIX root prompt.

TimesTen documentation uses these variables to identify path, file and user names:

ConventionMeaning
install_dirThe path that represents the directory where the current release of TimesTen is installed.
TTinstanceThe instance name for your specific installation of TimesTen. Each installation of TimesTen must be identified at install time with a unique alphanumeric instance name. This name appears in the install path.
bits or bbTwo digits, either 32 or 64, that represent either the 32-bit or 64-bit operating system.
release or rrThe first three parts in a release number, with or without dots. The first three parts of a release number represent a major TimesTen release. For example, 1122 or 11.2.2 represents TimesTen 11g Release 2 (11.2.2).
DSNThe data source name.

Documentation Accessibility

For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.

Access to Oracle Support

Oracle customers have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs if you are hearing impaired.

PK[))PK*AOEBPS/function.htm Functions

4 Functions

Functions manipulate data and return a result. In addition to an alphabetical listing of all functions, this chapter contains the following function overview sections:

Numeric functions

Numeric functions accept numeric input and return numeric values. The numeric functions are as follows:

ABS

CEIL

FLOOR

MOD

POWER

SIGN

SQRT

Character functions returning character values

The character functions that return character values are as follows:

CHR

CONCAT

LOWER and UPPER

LPAD

LTRIM

NCHR

NLSSORT

REPLACE

RPAD

RTRIM

SOUNDEX

SUBSTR, SUBSTRB, SUBSTR4

TRIM

Character functions returning number values

Character functions that return number values are as follows:

ASCIISTR

INSTR, INSTRB, INSTR4

LENGTH, LENGTHB, LENGTH4

String functions

TimesTen supports these string functions in SELECT statements:

A selected value that specifies a string function causes the SELECT result to be materialized. This causes overhead in both time and space.

LOB functions

The following EMPTY_* functions initialize LOBs to a non-NULL value:

The following TO_* functions convert specific data types into the desired LOB data type:

NLS character set functions

The NLS character set functions return information about the specified character set.

General comparison functions

The general comparison functions determine the greatest and or least value from a set of values. The general comparison functions are:

GREATEST

LEAST

Conversion functions

Conversion functions convert a value from one data type to another. Some of the conversion function names follow the convention of TO_datatype.

The SQL conversion functions are as follows:

ASCIISTR

CAST

NUMTODSINTERVAL

NUMTOYMINTERVAL

TO_CHAR

TO_DATE

TO_NUMBER

UNISTR

Datetime functions

For a full description of the datetime data types, see "Datetime data types".

The datetime functions are as follows:

ADD_MONTHS

EXTRACT

MONTHS_BETWEEN

NUMTODSINTERVAL

NUMTOYMINTERVAL

ROUND (Date)

SYSDATE and GETDATE

TIMESTAMPADD

TIMESTAMPDIFF

TO_DATE

TRUNC (date)

Aggregate functions

Aggregate functions perform a specific operation over all rows in a group. Aggregate functions return a single result row based on groups of rows, rather than on single rows. They are commonly used with the GROUP BY clause in a SELECT statement, where the returned rows are divided into groups. If you omit the GROUP BY clause, the aggregate functions in the select list are applied to all the rows in the queried table or view.

Aggregate functions can be specified in the select list or the HAVING clause. See "SELECT" for more information. The value of the expression is computed using each row that satisfies the WHERE clause.

Many aggregate functions that take a single argument can use the ALL or DISTINCT keywords. The default is ALL. See each aggregate function syntax to see if ALL or DISTINCT can be used.

For example, the DISTINCT average of 1, 1, 1, and 3 is 2. The ALL average for these results is 1.5.

The ROLLUP and CUBE clauses within a GROUP BY clause produce superaggregate rows where the column values are represented by null values. Because the superaggregate rows are denoted by NULL, it can be a challenge to differentiate between query results that include a null value and the superaggregate result. In addition, within the returned subtotals, how do you find the exact level of aggregation for a given subtotal? Use the GROUP_ID, GROUPING and GROUPING_ID functions to resolve these issues.

See Chapter 1, "Data Types" for information about:

The following is a list of aggregate functions:

AVG

COUNT

GROUP_ID

GROUPING

GROUPING_ID

MAX

MIN

SUM

Analytic functions

Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause.

Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins, WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. The final ORDER BY clause is used to order the result of analytic functions. Analytic functions can appear in the select list of a query or subquery and in the ORDER BY clause.

Analytic functions allow you to divide query result sets into groups of rows called partitions. You can define partitions on columns or expressions. You can partition a query result set into just one partition holding all rows, a few large partitions or many small partitions holding just a few rows each.

You can define a sliding window for each row in the partition. This window determines the range of rows used to perform the calculations for the current row. Window sizes are based on a physical number of rows. The window has a starting row and an ending row and the window may move at one or both ends. For example, a window defined for a cumulative sum function would have its starting row fixed at the first row of the partition and the ending rows would slide from the start point to the last row of the partition. In contrast, a window defined for a moving average would have both the start point and end point slide.

You can set the window as large as all the rows in the partition or as small as one row within a partition.

You can specify multiple ordering expressions within each function. This is useful when using functions that rank values because the second expression can resolve ties between identical values for the first expression.

Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.

Restrictions:

The list of analytic functions follows. Functions followed by an asterisk (*) support the WindowingClause.

SQL syntax

Analytic function syntax:

AnalyticFunctionName ([arguments]) OVER ([AnalyticClause])

AnalyticClause::= QueryPartitionClause [ORDER BY OrderByClause [,...]
                                          [WindowingClause]] |
                  ORDER BY OrderByClause [,...] [WindowingClause]

QueryPartitionClause::= PARTITION BY { Expression[,Expression]... |
                                      (Expression [,Expression]...) 
                                     }

OrderByClause::= Expression [ASC|DESC] [NULLS {FIRST|LAST}]

WindowingClause::= ROWS { BETWEEN StartPoint AND EndPoint |
                          StartPoint
                        }

StartPoint::= UNBOUNDED PRECEDING | CURRENT ROW | ConstantExpression 
                                                    { PRECEDING | FOLLOWING }

EndPoint::= UNBOUNDED FOLLOWING | CURRENT ROW | ConstantExpression
                                                   { PRECEDING | FOLLOWING }

Parameters

ParameterDescription
AnalyticFunctionNameName of analytic function.
argumentsArguments for the analytic function. Number of arguments depends on the analytic function. Refer to the particular function for specific information on the arguments to the function.
OVER ( [ AnalyticClause ] )Indicates that the function is an analytic function. This clause is computed after the FROM, WHERE, GROUP BY, and HAVING clauses.

If you do not specify the AnalyticClause, then the analytic function is evaluated over the entire result set without partitioning, ordering, or using a window.

QueryPartitionClauseOptional clause used in AnalyticClause. Denoted by the PARTITION BY clause. If specified, the query result set is partitioned into groups based on the Expression list. If you omit this clause, then the function treats all rows of the query result set as a single group.

You can specify multiple analytic functions in the same query using either the same or different PARTITION keys.

Valid values for Expression are constants, columns, non-analytic functions or function expressions.

ORDER BY OrderByClauseOptional clause used in AnalyticClause. Use this clause to specify how data is ordered within the partition. Expression cannot be a column alias or position.

You can order the values in a partition on multiple keys each defined by Expression and each qualified by an ordering sequence.

Analytic functions operate in the order specified in this clause. However this clause does not guarantee the order of the result. Use the ORDER BY clause of the query to guarantee the final result ordering.

If you specify the ORDER BY OrderByClause and you do not specify either a QueryPartitionClause or a WindowingClause, then the default window is ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

If you do not specify the ORDER BY OrderByClause, then the order is indeterminate.

ASC | DESCSpecifies the ordering sequence (ascending or descending). ASC is the default.

Clause is optional.

NULLS FIRST | NULLS LASTSpecifies whether rows that contain NULLs are specified first or last in the ordering sequence. NULLS LAST is the default for ascending order. NULLS FIRST is the default for descending order.

Clause is optional.

WindowingClauseClause is denoted by the ROWS keyword. Specifies for each row a window expressed in physical units (rows). The window is used for calculating the function result. The function is applied to all the rows in the window. The window moves through the query result set or partition from top to bottom.

You cannot specify the WindowingClause if you have not specified the ORDER BY OrderByClause.

The value returned by the analytic function may produce nondeterministic results unless the ordering sequence results in unique ordering. In this case, specify multiple columns in the OrderByClause to achieve unique ordering.

For the list of functions that allow the WindowingClause, see "Analytic functions".

BETWEEN...ANDUse the BETWEEN...AND clause to specify a start point (StartPoint) and end point (EndPoint) for the window.

If you omit the BETWEEN...AND clause and attempt to specify one end point, then TimesTen considers this end point the start point and the end point defaults to the current row.

StartPointValid values are UNBOUNDED PRECEDING, CURRENT ROW, ConstantExpression PRECEDING or ConstantExpression FOLLOWING.
EndPointValid values are UNBOUNDED FOLLOWING, CURRENT ROW, ConstantExpression PRECEDING or ConstantExpression FOLLOWING.
UNBOUNDED PRECEDINGUse UNBOUNDED PRECEDING to indicate that the window starts at the first row of the partition.

Cannot be used as the end point.

UNBOUNDED FOLLOWINGUse UNBOUNDED FOLLOWING to indicate that the window ends at the last row of the partition.

Cannot be used as the start point.

CURRENT ROWAs a start point, CURRENT ROW specifies that the window begins at the current row. In this case, the end point cannot be ConstantExpression PRECEDING.

As an end point, CURRENT ROW specifies that the window ends at the current row. In this case, the start point cannot be ConstantExpression FOLLOWING.

ConstantExpression {PRECEDING | FOLLOWING }If ConstantExpression FOLLOWING is the start point, then the end point must be ConstantExpression FOLLOWING or UNBOUNDED FOLLOWING. If ConstantExpression PRECEDING is the end point, then the start point must be ConstantExpression PRECEDING or UNBOUNDED PRECEDING.

The end point ConstantExpression must be greater or equal to the start point ConstantExpression.

ConstantExpression must be either a constant or an expression that evaluates to a constant positive numeric value.


USER functions

TimesTen supports these USER functions:

Each of these functions returns the name of the user that is currently connected to the TimesTen database.

Cache grid functions

You may wish to execute a global query without changing the location of the data. You can use cache grid functions to determine the location of data in a cache grid and then execute a query for the information from that member.

Use these SQL functions in a global query to obtain information about the location of data in the cache grid, which the user can use to map each returned row to a member of the grid.

These functions can be used in a SELECT statement and in these clauses of a SELECT statement:

See "Obtaining information about the location of data in the cache grid" in Oracle In-Memory Database Cache User's Guide for more information.


ABS

The ABS function returns the absolute value of Expression.

SQL syntax

ABS(Expression)

Parameters

ABS has the parameter:

ParameterDescription
ExpressionOperand or column can be any numeric data type. Absolute value of Expression is returned.

Description

Examples

Create table abstest and define columns with type BINARY_FLOAT and TT_INTEGER. Insert values -BINARY_FLOAT_INFINITY and -10. Call ABS to return the absolute value. You see INF and 10 are the returned values:

Command> CREATE TABLE abstest (col1 BINARY_FLOAT, col2 TT_INTEGER);
Command> INSERT INTO abstest VALUES 
       > (-BINARY_FLOAT_INFINITY, -10);
1 row inserted.
Command> SELECT ABS (col1) FROM abstest;
< INF >
1 row found.
Command> SELECT ABS (col2) FROM abstest;
< 10 >
1 row found.

ADD_MONTHS

The ADD_MONTHS function returns the date resulting from date plus integer months.

SQL syntax

ADD_MONTHS(Date,Integer)

Parameters

ADD_MONTHS has the parameters:

ParameterDescription
DateA datetime value or any value that can be converted to a datetime value.
IntegerAn integer or any value that can be converted to an integer.

Description

Examples

Call the ADD_MONTHS function to add 1 month to date January 31, 2007. The last day of February is returned.

Command> SELECT ADD_MONTHS (DATE '2007-01-31', 1) FROM dual;
< 2007-02-28 00:00:00 >
1 row found.

ADD_MONTHS returns data type DATE if date is of type TIMESTAMP:

Command> DESCRIBE SELECT ADD_MONTHS (TIMESTAMP '2007-01-31
       > 10:00:00', 1) FROM dual;
Prepared Statement:
  Columns:
    EXP                             DATE NOT NULL

Use the HR schema to select the first 5 rows of the employees table, showing employee_id, last_name and hire_date. Create new table temp_hire_date using the CREATE TABLE ... AS SELECT statement. Call ADD_MONTHS to add 23 months to the original hire_date.

Command> SELECT FIRST 5 employee_id, last_name, hire_date FROM employees;
< 100, King, 1987-06-17 00:00:00 >
< 101, Kochhar, 1989-09-21 00:00:00 >
< 102, De Haan, 1993-01-13 00:00:00 >
< 103, Hunold, 1990-01-03 00:00:00 >
< 104, Ernst, 1991-05-21 00:00:00 >
5 rows found.
Command> CREATE TABLE temp_hire_date (employee_id, last_name,
        > hire_date) AS SELECT FIRST 5 employee_id, last_name,
        > ADD_MONTHS (hire_date, 23) FROM employees;
5 rows inserted.
Command> SELECT * FROM temp_hire_date;
< 100, King, 1989-05-17 00:00:00 >
< 101, Kochhar, 1991-08-21 00:00:00 >
< 102, De Haan, 1994-12-13 00:00:00 >
< 103, Hunold, 1991-12-03 00:00:00 >
< 104, Ernst, 1993-04-21 00:00:00 >
5 rows found.

ASCIISTR

The ASCIISTR function takes as its argument, either a string or any expression that resolves to a string, in any character set, and returns the ASCII version of the string in the database character set. Non-ASCII characters are converted to Unicode escapes.

SQL syntax

ASCIISTR ([N]'String')

Parameters

ASCIISTR has the parameter:

ParameterDescription
[N]'String'The string or expression that evaluates to a string that is passed to the ASCIISTR function. The string can be in any character set. Value can be of any supported character data types including CHAR, VARCHAR, VARCHAR2, NCHAR, NVARCHAR, NVARCHAR2, CLOB, or NCLOB data types. Both TimesTen and Oracle data types are supported. The ASCII version of the string in the database character set is returned. Specify N if you want to pass the string in UTF-16 format.

Description

The ASCIISTR function enables you to see the representation of a string value that is not in the database character set.

Examples

The following example invokes the ASCIISTR function passing as an argument the string 'Aäa' in UTF-16 format. The ASCII version is returned in the WE8ISO8859P1 character set. The non-ASCII character ä is converted to Unicode encoding value:

Command> connect "dsn=test; ConnectionCharacterSet= WE8ISO8859P1";
Connection successful: DSN=test;UID=user1;DataStore=/datastore/user1/test;
DatabaseCharacterSet=WE8ISO8859P1;
ConnectionCharacterSet=WE8ISO8859P1;PermSize=32;TypeMode=0;
(Default setting AutoCommit=1)
Command> SELECT ASCIISTR (n'Aäa') FROM dual;
< A\00E4a >
1 row found.

AVG

Computes the arithmetic mean of the values in the argument. Null values are ignored.

SQL syntax

AVG ([ALL | DISTINCT] Expression) [OVER ([AnalyticClause])]

Parameters

AVG has the following parameters:

ParameterDescription
ExpressionCan be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type.
ALLIncludes duplicate rows in the argument of an aggregate function. If neither ALL nor DISTINCT is specified, ALL is assumed.
DISTINCTEliminates duplicate column values from the argument of an aggregate function.
OVER ([AnalyticClause])If specified, indicates aggregate analytic function. For more information on analytic functions, see "Analytic functions".

Description

Examples

Calculate the average salary for employees in the HR schema. Use CAST to cast the average as the data type of the column:

Command> SELECT CAST(AVG (salary) AS NUMBER (8,2)) FROM employees;
< 6461.68 >

CAST

Enables you to convert data of one type to another type. CAST can be used wherever a constant can be used. CAST is useful in specifying the exact data type for an argument. This is especially true for unary operators like '-' or functions with one operand like TO_CHAR or TO_DATE.

A value can only be CAST to a compatible data type, with the exception of NULL. NULL can be cast to any data type. CAST is not needed to convert a NULL literal to the desired target type.

The following conversions are supported:

SQL syntax

CAST
  ( {Expression | NULL} AS DataType )

Parameters

CAST has the parameters:

ParameterDescription
ExpressionSpecifies the value to be converted.
AS DataTypeSpecifies the resulting data type.

Description

Examples

INSERT INTO t1 VALUES(TO_CHAR(CAST(? AS REAL)));
SELECT CONCAT(x1, CAST (? AS CHAR(10))) FROM t1;        
SELECT * FROM t1 WHERE CAST (? AS INT)=CAST(? AS INT);

CHR

The CHR function returns the character having the specified binary value in the database character set.

SQL syntax

CHR(n)

Parameters

CHR has the parameter:

ParameterDescription
nThe binary value in the database character set. The character having this binary value is returned. The result is of type VARCHAR2.

Description

Examples

The following example is run on an ASCII-based machine with the WE8ISO8859P1 character set.

Command> SELECT CHR(67)||CHR(65)||CHR(84) FROM dual;
< CAT >
1 row found.

CEIL

The CEIL function returns the smallest integer greater than or equal to Expression.

SQL syntax

CEIL(Expression)

Parameters

CEIL has the parameter:

ParameterDescription
ExpressionOperand or column can be any numeric data type.

Description

Examples

Sum the commission_pct for employees in the employees table, and then call CEIL to return the smallest integer greater than or equal to the value returned by SUM. You see the value returned by the SUM function is 7.8 and the value returned by the CEIL function is 8.

Command> SELECT SUM (commission_pct) FROM employees;
< 7.8 >
1 row found.
Command> SELECT CEIL (SUM (commission_pct)) FROM employees;
< 8 >
1 row found.

COALESCE

The COALESCE function returns the first non-NULL expression in the expression list. If all occurrences of expression evaluate to NULL, then the function returns NULL.

SQL syntax

COALESCE(Expression1, Expression2 [,...])

Parameters

COALESCE has the parameters:

ParameterDescription
Expression1, Expression2 [,...]The expressions in the expression list. The first non-NULL expression in the expression list is returned.

Each expression is evaluated in order and there must be at least 2 expressions.


Description

Examples

The example illustrates the use of the COALESCE expression. The COALESCE expression is used to return the commission_pct for the first 10 employees with manager_id = 100. If the commission_pct is NOT NULL, then the original value for commission_pct is returned. If commission_pct is NULL, then 0 is returned.

Command> SELECT FIRST 10 employee_id, COALESCE (commission_pct, 0) FROM
 employees WHERE manager_id = 100;
< 101, 0 >
< 102, 0 >
< 114, 0 >
< 120, 0 >
< 121, 0 >
< 122, 0 >
< 123, 0 >
< 124, 0 >
< 145, .4 >
< 146, .3 >
10 rows found.

CONCAT

The CONCAT function concatenates one character string with another to form a new character string.

SQL syntax

CONCAT(Expression1, Expression2)

Parameters

CONCAT has the parameters:

ParameterDescription
Expression1A CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB expression.
Expression2A CHAR, VARCHAR2, NCHAR , NVARCHAR2, CLOB, or NCLOB expression.

Description

Examples

The following example concatenates first names and last names.

Command> SELECT CONCAT(CONCAT(first_name, ' '), last_name), salary 
 FROM employees;
< Steven King, 24000 >
< Neena Kochhar, 17000 >
< Lex De Haan, 17000 >
< Alexander Hunold, 9000 >
...
107 rows found.

The following example concatenates column id with column id2. In this example, the result type is NCHAR(40).

Command> CREATE TABLE cat (id CHAR (20), id2 NCHAR (20));
Command> INSERT INTO cat VALUES ('abc', 'def');
1 row inserted.
Command> SELECT CONCAT (id,id2) FROM cat;
< abc                 def                  >
1 row found.

The description of the || operator is in "Expression specification".


COUNT

Counts all rows that satisfy the WHERE clause, including rows containing null values. The data type of the result is TT_INTEGER.

COUNT is an aggregate function and can also be an aggregate analytic function. For more details on aggregate functions, see "Aggregate functions". For information on analytic functions, see "Analytic functions". For more information on the number of rows in a table, see the description for the NUMTUPS field in "SYS.TABLES" in Oracle TimesTen In-Memory Database System Tables and Views Reference.

SQL syntax

COUNT ({* | [ALL | DISTINCT]{Expression|ROWID}}) 
[OVER ([AnalyticClause])]

Parameters

COUNT has the parameters:

ParameterDescription
ExpressionCan be any numeric data type or any nonnumeric type that can be implicitly converted to a numeric type.

Counts all rows. Rows containing null values are not counted. The data type of the result is TT_INTEGER. For more information on the number of rows in a table, see the description for the NUMTUPS field in "SYS.TABLES" in Oracle TimesTen In-Memory Database System Tables and Views Reference.

*
Counts all rows that satisfy the WHERE clause, including duplicates and null values. COUNT never returns NULL.The data type of the result is TT_INTEGER. For more information on the number of rows in a table, see the description for the NUMTUPS field in "SYS.TABLES" in Oracle TimesTen In-Memory Database System Tables and Views Reference.
ALLIncludes duplicate rows in the argument of an aggregate function. If neither ALL nor DISTINCT is specified, ALL is assumed.
DISTINCTEliminates duplicate column values from the argument of an aggregate function.
ROWIDTimesTen assigns a unique ID called a rowid to each row stored in a table. The rowid value can be retrieved through the ROWID pseudocolumn. See "ROWID" for more details.
OVER ([AnalyticClause])If specified, indicates aggregate analytic function. For more information on analytic functions, see "Analytic functions".

Description

Examples

Count the number of employees.

Command> SELECT COUNT(*) "TOTAL EMP" FROM employees;
 
TOTAL EMP
< 107 >
1 row found.

Count the number of managers by selecting out each individual manager id without duplication.

Command> SELECT COUNT(DISTINCT manager_id) "Managers" FROM employees;
 
MANAGERS
< 18 >
1 row found.

CURRENT_USER

Returns the name of the TimesTen user currently connected to the database.

SQL syntax

CURRENT_USER

Parameters

CURRENT_USER has no parameters.

Examples

To return the name of the user who is currently connected to the database:

SELECT CURRENT_USER FROM dual;

DECODE

The DECODE function compares an expression to each search value one by one. If the expression is equal to the search value, the result value is returned. If no match is found, then the default value (if specified) is returned. Otherwise NULL is returned.

SQL syntax

DECODE(Expression, {SearchValue, Result [,...])} [,Default])

Parameters

DECODE has the parameters:

ParameterDescription
ExpressionThe expression that is compared to the search value. Expression can be CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data types. Both TimesTen and Oracle data types are supported.
SearchValueAn expression is compared to one or more search values.
ResultIf the expression is equal to a SearchValue, the specified Result value is returned.
DefaultIf no match is found, the default value is returned. Default is optional. If Default is not specified and no match is found, then NULL is returned.

Description

If an expression is NULL, then the null expression equals a null search value.

Examples

The following example invokes the DECODE function. In the locations table, if the column country_id is equal to 'IT', the function returns 'Italy'. If the country_id is equal to 'JP', the function returns 'Japan'. If the country_id is equal to 'US', 'United States' is returned. If the country_id is not equal to 'IT' or 'JP' or 'US', the function returns 'Other'.

Command> SELECT location_id, 
> DECODE (country_id, 'IT', 'Italy', 
> 'JP', 'Japan', 'US', 'United States', 'Other') 
> FROM locations WHERE location_id < 2000;

LOCATION_ID, EXP
< 1000, Italy >
< 1100, Italy >
< 1200, Japan >
< 1300, Japan >
< 1400, United States >
< 1500, United States >
< 1600, United States >
< 1700, United States >
< 1800, Other >
< 1900, Other >
10 rows found.

DENSE_RANK

The DENSE_RANK function is an analytic function that computes the rank of rows in an ordered group of rows and returns the ranks as type NUMBER.

SQL syntax

DENSE_RANK () OVER ( [QueryPartitionClause] OrderByClause )

Parameters

DENSE_RANK has the parameters:

ParameterDescription
QueryPartitionClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".
OrderByClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".

Description

Example

Select the department name, employee name, and salary of all employees who work in the human resources or purchasing department. Compute a rank for each unique salary in each of the two departments. The salaries that are equal receive the same rank.

Command> SELECT d.department_name, e.last_name, e.salary, DENSE_RANK()
       >  OVER (PARTITION BY e.department_id ORDER BY e.salary) AS dense
       > FROM employees e, departments d
       > WHERE e.department_id = d.department_id
       >    AND d.department_id IN ('30', '40')
       > ORDER BY e.last_name, e.salary, d.department_name, dense;
< Purchasing, Baida, 2900, 4 >
< Purchasing, Colmenares, 2500, 1 >
< Purchasing, Himuro, 2600, 2 >
< Purchasing, Khoo, 3100, 5 >
< Human Resources, Mavris, 6500, 1 >
< Purchasing, Raphaely, 11000, 6 >
< Purchasing, Tobias, 2800, 3 >
7 rows found.

EMPTY_BLOB

A BLOB column can be initialized to a zero-length, empty BLOB using the EMPTY_BLOB function. This function initializes the LOB to a non-NULL value, so can be used for initializing any BLOB that has been declared as NOT NULL.

SQL syntax

EMPTY_BLOB ()

Parameters

EMPTY_BLOB has no parameters.

Description

You can only use EMPTY_BLOB in the VALUES clause of an INSERT statement or the SET clause of an UPDATE statement.

Examples

The following example uses the EMPTY_BLOB function to initialize a non-NULL BLOB column to a zero-length value.

Command> CREATE TABLE blob_content (
 > id NUMBER PRIMARY KEY, 
 > blob_column BLOB NOT NULL); -- Does not allow a NULL value

Command> INSERT INTO blob_content (id, blob_column) 
 > VALUES (1, EMPTY_BLOB( ) );
1 row inserted.

EMPTY_CLOB

A CLOB or NCLOB column can be initialized to a zero-length, empty CLOB or NCLOB using the EMPTY_CLOB function. Both CLOB and NCLOB data types are initialized with the EMPTY_CLOB function. This function initializes the LOB to a non-NULL value, so can be used for initializing any CLOB or NCLOB that has been declared as NOT NULL.

SQL syntax

EMPTY_CLOB () 

Parameters

EMPTY_CLOB has no parameters.

Description

You can only use EMPTY_CLOB in the VALUES clause of an INSERT statement or the SET clause of an UPDATE statement.

Examples

The following example uses the EMPTY_CLOB function to initialize a non-NULL CLOB column to a zero-length value.

Command> CREATE TABLE clob_content ( 
 > id NUMBER PRIMARY KEY, 
 > clob_column CLOB NOT NULL ); -- This definition does not allow a NULL value

Command> INSERT INTO clob_content (id, clob_column)
       > VALUES (1, EMPTY_CLOB( ) );
1 row inserted.

EXTRACT

The EXTRACT function extracts and returns the value of a specified datetime field from a datetime or interval value expression as a NUMBER data type. This function can be useful for manipulating datetime field values in very large tables.

If you are using TimesTen type mode, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation for information about the EXTRACT function.

SQL syntax

EXTRACT (DateTimeField FROM IntervalExpression | DateTimeExpression)

Parameters

EXTRACT has the following parameters:

ParameterDescription
DateTimeFieldThe field to be extracted from IntervalExpression or DateTimeExpression. Accepted fields are YEAR, MONTH, DAY, HOUR, MINUTE or SECOND.
IntervalExpressionAn interval result.
DateTimeExpressionA datetime expression. For example, TIME, DATE, TIMESTAMP.

Description

Examples

The following example extracts the second field out of the interval result sysdate-t1.createtime.

SELECT EXTRACT(SECOND FROM sysdate-t1.createtime) FROM t1;

The following example extracts the second field out of sysdate from the dual system table.

Command> SELECT EXTRACT (SECOND FROM sysdate) FROM dual;
< 20 >
1 row found.

FIRST_VALUE

The FIRST_VALUE function is an analytic function that returns the first value in an ordered set of values.

SQL syntax

FIRST_VALUE (Expression [IGNORE NULLS]) OVER (AnalyticClause)

Parameters

FIRST_VALUE has the parameters:

ParameterDescription
ExpressionFor information on supported Expressions, see "Analytic functions".
IGNORE NULLSSpecify IGNORE NULLS if you wish FIRST_VALUE to return the first non-NULL value in the set or NULL if all values in the set are NULL. Clause is optional.
OVER (AnalyticClause)For information on syntax, semantics, and restrictions, see "Analytic functions".

Description

Example

Use the FIRST_VALUE function to select for each employee in department 90, the last name of the employee with the lowest salary.

Command> SELECT department_id, last_name, salary, FIRST_VALUE (last_name) OVER
       >   (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS lowest_sal
       > FROM
       >  (SELECT * FROM employees WHERE department_id = 90 ORDER BY employee_id)
       > ORDER BY department_id, last_name, salary, lowest_sal;
< 90, De Haan, 17000, Kochhar >
< 90, King, 24000, Kochhar >
< 90, Kochhar, 17000, Kochhar >
3 rows found.

FLOOR

The FLOOR function returns the largest integer equal to or less than Expression.

SQL syntax

FLOOR (Expression)

Parameters

FLOOR has the parameter:

ParameterDescription
ExpressionOperand or column can be any numeric data type.

Description

Examples

Sum the commission_pct for employees in the employees table. Then call FLOOR to return the largest integer equal to or less than the value returned by SUM. You see the value returned by the SUM function is 7.8 and the value returned by the FLOOR function is 7:

Command> SELECT SUM (commission_pct) FROM employees;
< 7.8 >
1 row found.
Command> SELECT FLOOR (SUM (commission_pct)) FROM employees;
< 7 >
1 row found.

GREATEST

The GREATEST function returns the greatest of the list of one or more expressions.

SQL syntax

GREATEST (Expression [,...])

Parameters

GREATEST has the parameter:

ParameterDescription
Expression [,...]List of one or more expressions that is evaluated to determine the greatest expression value. Operand or column can be numeric, character or date. Each expression in the list must be from the same data type family.

Description

Use the GREATEST function to return the string with the greatest value:

Command> SELECT GREATEST ('GREAT', 'GREATER', 'GREATEST') FROM dual;
< GREATEST >
1 row found.

Use the GREATEST function to return the numeric expression with the greatest value. In this example, BINARY_DOUBLE is the data type with the highest numeric precedence, so arguments are implicitly converted to BINARY_DOUBLE before the comparison and the data type BINARY_DOUBLE is returned:

Command> SELECT GREATEST (10, 10.55, 10.1D) FROM dual;
< 10.5500000000000 >
1 row found.

Use the DESCRIBE command to confirm the data type returned is BINARY_DOUBLE:

Command> DESCRIBE SELECT GREATEST (10, 10.55, 10.1D) FROM dual;

Prepared Statement:
  Columns:
    EXP                             BINARY_DOUBLE NOT NULL

Use the GREATEST function to return the DATE expression with the greatest value. DATE and TIMESTAMP are in the same date family.

Command> SELECT GREATEST (DATE '2007-09-30',
       > TIMESTAMP '2007-09-30:10:00:00') FROM dual;
< 2007-09-30 10:00:00 >
1 row found.

Attempt to use the GREATEST function to return the greatest value in the list of TT_DATE and TT_TIMESTAMP expressions. You see an error because TT_DATE and TT_TIMESTAMP are in different date subfamilies and cannot be used in the same list of expressions.

Command> SELECT GREATEST (TT_DATE '2007-09-30', TT_TIMESTAMP
       > '2007-09-30:10:00:00') FROM dual;
2817: Invalid data type TT_TIMESTAMP for argument 2 for function GREATEST
The command failed.

Use the GREATEST function to return the TT_DATE expression with the greatest value.

Command> SELECT GREATEST (TT_DATE '2007-09-30',
       > TT_DATE '2007-09-29', TT_DATE '2007-09-28') FROM dual;
< 2007-09-30 >
1 row found.

GROUP_ID

The GROUP_ID function identifies duplicate groups in a SELECT query resulting from a GROUP BY clause. The GROUP_ID function returns the number 0 for a unique group; any subsequent duplicate grouping row receives a higher number, starting with 1.

The GROUP_ID function filters out duplicate groupings from the query result. If you have complicated queries that may generate duplicate values, you can eliminate those rows by including the HAVING GROUP_ID() = 0 condition.


Note:

For full details on the GROUP BY clause, see "GROUP BY clause". For details on the HAVING clause, see "SELECT".

Syntax

The GROUP_ID function is applicable only in a SELECT statement that contains a GROUP BY clause; it can be used in the select list and HAVING clause of the SELECT query.

GROUP_ID()

Parameters

GROUP_ID has no parameters.

Example

The following example shows how GROUP_ID returns 0 for a unique group and a number > 0 to identify duplicate groups. The following example prints out the department number, manager id and the sum of the salary within the manager. The resulting output is grouped using the ROLLUP clause on the manager and department providing superaggregate results.

Command> SELECT department_id as DEPT, manager_id AS MGR, 
 GROUP_ID(), SUM(salary) as SALARY
 FROM employees 
 WHERE manager_id > 146 
 GROUP BY manager_id, ROLLUP(manager_id, department_id) 
 ORDER BY manager_id, department_id;
 
DEPT, MGR, EXP, SALARY
< 80, 147, 0, 46600 >
< <NULL>, 147, 1, 46600 >
< <NULL>, 147, 0, 46600 >
< 80, 148, 0, 51900 >
< <NULL>, 148, 0, 51900 >
< <NULL>, 148, 1, 51900 >
< 80, 149, 0, 43000 >
< <NULL>, 149, 0, 7000 >
< <NULL>, 149, 0, 50000 >
< <NULL>, 149, 1, 50000 >
< 20, 201, 0, 6000 >
< <NULL>, 201, 0, 6000 >
< <NULL>, 201, 1, 6000 >
< 110, 205, 0, 8300 >
< <NULL>, 205, 0, 8300 >
< <NULL>, 205, 1, 8300 >
16 rows found.

GROUPING

The GROUPING function enables you to determine whether a NULL is a stored NULL or an indication of a subtotal or grand total. Using a single column as its argument, GROUPING returns a 1 when it encounters a null value created by a ROLLUP or CUBE operation, indicating a subtotal or grand total. Any other type of value, including a stored NULL, returns a 0.


Note:

For full details on ROLLUP and CUBE clauses, see "GROUP BY clause".

Syntax

The GROUPING function is applicable only in a SELECT statement that contains a GROUP BY clause. It can be used in the select list and HAVING clause of the SELECT query that includes the GROUP BY clause. The expression indicated in the GROUPING function syntax must match one of the expressions contained in the GROUP BY clause.

The following syntax uses GROUPING to identify the results from the expression listed as an aggregate or not:

SELECT …  [GROUPING(Expression)…]  … 
  GROUP BY … { RollupCubeClause | GroupingSetsClause } ...

The following syntax uses GROUPING within a HAVING clause to identify the results from the expression listed as an aggregate or not:

SELECT …
  GROUP BY … { RollupCubeClause | GroupingSetsClause } ...
 HAVING GROUPING(Expression) = 1

Parameters

ParameterDescription
ExpressionValid expression syntax. See Chapter 3, "Expressions".
RollupCubeClauseThe GROUP BY clause may include one or more ROLLUP or CUBE clauses. See "GROUP BY clause" for full details.
GroupingSetsClauseThe GROUP BY clause may include one or more GROUPING SETS clauses. The GROUPING SETS clause enables you to explicitly specify which groupings of data that the database returns. For more information, see "GROUPING SETS".

Examples

The following example shows how the grouping function returns a '1' when it encounters the grand total for the department.

Command> SELECT department_id AS DEPT, 
GROUPING(department_id) AS DEPT_GRP, SUM(salary) AS SALARY 
FROM emp_details_view 
GROUP BY ROLLUP(department_id) 
ORDER BY department_id; 
DEPT, DEPT_GRP, SALARY
< 10, 0, 4400 >
< 20, 0, 19000 >
< 30, 0, 24900 >
< 40, 0, 6500 >
< 50, 0, 156400 >
< 60, 0, 28800 >
< 70, 0, 10000 >
< 80, 0, 304500 >
< 90, 0, 58000 >
< 100, 0, 51600 >
< 110, 0, 20300 >
< <NULL>, 1, 684400 >
12 rows found.

The following example shows that you can use the GROUPING function for each column to determine which null values are for the totals.

Command> SELECT department_id AS DEPT, job_id AS JOB, 
GROUPING(department_id) AS DEPT_GRP, GROUPING(job_id) AS JOB_GRP, 
GROUPING_ID(department_id, job_id) AS GRP_ID, SUM(salary) AS SALARY 
FROM emp_details_view 
GROUP BY CUBE(department_id, job_id) 
ORDER BY department_id, job_id, grp_id ASC;
 
DEPT, JOB, DEPT_GRP, JOB_GRP, GRP_ID, SALARY
< 10, AD_ASST, 0, 0, 0, 4400 >
< 10, <NULL>, 0, 1, 1, 4400 >
< 20, MK_MAN, 0, 0, 0, 13000 >
< 20, MK_REP, 0, 0, 0, 6000 >
< 20, <NULL>, 0, 1, 1, 19000 >
< 30, PU_CLERK, 0, 0, 0, 13900 >
< 30, PU_MAN, 0, 0, 0, 11000 >
< 30, <NULL>, 0, 1, 1, 24900 >
...
< 110, AC_ACCOUNT, 0, 0, 0, 8300 >
< 110, AC_MGR, 0, 0, 0, 12000 >
< 110, <NULL>, 0, 1, 1, 20300 >
< <NULL>, AC_ACCOUNT, 1, 0, 2, 8300 >
< <NULL>, AC_MGR, 1, 0, 2, 12000 >
< <NULL>, AD_ASST, 1, 0, 2, 4400 >
< <NULL>, AD_PRES, 1, 0, 2, 24000 >
< <NULL>, AD_VP, 1, 0, 2, 34000 >
< <NULL>, FI_ACCOUNT, 1, 0, 2, 39600 >
< <NULL>, FI_MGR, 1, 0, 2, 12000 >
< <NULL>, HR_REP, 1, 0, 2, 6500 >
< <NULL>, IT_PROG, 1, 0, 2, 28800 >
< <NULL>, MK_MAN, 1, 0, 2, 13000 >
< <NULL>, MK_REP, 1, 0, 2, 6000 >
< <NULL>, PR_REP, 1, 0, 2, 10000 >
< <NULL>, PU_CLERK, 1, 0, 2, 13900 >
< <NULL>, PU_MAN, 1, 0, 2, 11000 >
< <NULL>, SA_MAN, 1, 0, 2, 61000 >
< <NULL>, SA_REP, 1, 0, 2, 243500 >
< <NULL>, SH_CLERK, 1, 0, 2, 64300 >
< <NULL>, ST_CLERK, 1, 0, 2, 55700 >
< <NULL>, ST_MAN, 1, 0, 2, 36400 >
< <NULL>, <NULL>, 1, 1, 3, 684400 >
50 rows found.

GROUPING_ID

The GROUPING_ID function returns a number that shows the exact GROUP BY level of aggregation resulting from a ROLLUP or CUBE clause.


Note:

For details on ROLLUP and CUBE clauses, see "GROUP BY clause".

The GROUPING_ID function takes the ordered list of grouping columns from the ROLLUP or CUBE as input and computes the grouping id as follows:

  1. Applies the GROUPING function to each of the individual columns in the list. The result is a set of ones and zeros, where 1 represents a superaggregate generated by the ROLLUP or CUBE.

  2. Puts these ones and zeros in the same order as the order of the columns in its argument list to produce a bit vector.

  3. Converts this bit vector from a binary number into a decimal (base 10) number, which is returned as the grouping id.

For instance, if you group with CUBE(department_id, job_id), the returned values are as shown in Table 4-1.

Table 4-1 GROUPING_ID Example for CUBE(department_id, job_id)

Aggregation LevelBit VectorGROUPING_ID

normal grouping rows for department and job

0 0

0

subtotal for department_id, aggregated at job_id

0 1

1

subtotal for job_id, aggregated at department_id

1 0

2

grand total

1 1

3


The GROUPING_ID function can be used in a query to filter rows so that only the summary rows are displayed. You can use the GROUPING_ID function in the HAVING clause to restrict output to only those rows that contain totals and subtotals. This can be accomplished when adding a comparison of the GROUPING_ID function results as greater than zero in the HAVING clause.

Syntax

The GROUPING_ID function is applicable only in a SELECT statement that contains the GROUP BY clause, a GROUPING function, and one of the following clauses: ROLLUP, CUBE or GROUPING SETS clauses. It can be used in the select list and HAVING clause of the SELECT query.

GROUPING_ID(Expression [, Expression ]...)

Parameters

ParameterDescription
ExpressionValid expression syntax. See Chapter 3, "Expressions".

Examples

The following example has the HAVING clause filter on the GROUPING_ID function, where the returned value is greater than zero. This excludes rows that do not contain either a subtotal or grand total. The following example shows the subtotals for the departments are identified with a group id of 1, subtotals for the job id with a group id of 2 and the grand total with a group id of 3:

Command> SELECT department_id AS DEPT, job_id AS JOB, 
GROUPING_ID(department_id, job_id) AS GRP_ID, 
SUM(salary) AS SALARY 
FROM emp_details_view 
GROUP BY CUBE(department_id, job_id) 
HAVING GROUPING_ID(department_id, job_id) > 0 
ORDER BY department_id, job_id, grp_id ASC;
 
DEPT, JOB, GRP_ID, SALARY
< 10, <NULL>, 1, 4400 >
< 20, <NULL>, 1, 19000 >
< 30, <NULL>, 1, 24900 >
< 40, <NULL>, 1, 6500 >
< 50, <NULL>, 1, 156400 >
< 60, <NULL>, 1, 28800 >
< 70, <NULL>, 1, 10000 >
< 80, <NULL>, 1, 304500 >
< 90, <NULL>, 1, 58000 >
< 100, <NULL>, 1, 51600 >
< 110, <NULL>, 1, 20300 >
< <NULL>, AC_ACCOUNT, 2, 8300 >
< <NULL>, AC_MGR, 2, 12000 >
< <NULL>, AD_ASST, 2, 4400 >
< <NULL>, AD_PRES, 2, 24000 >
< <NULL>, AD_VP, 2, 34000 >
< <NULL>, FI_ACCOUNT, 2, 39600 >
< <NULL>, FI_MGR, 2, 12000 >
< <NULL>, HR_REP, 2, 6500 >
< <NULL>, IT_PROG, 2, 28800 >
< <NULL>, MK_MAN, 2, 13000 >
< <NULL>, MK_REP, 2, 6000 >
< <NULL>, PR_REP, 2, 10000 >
< <NULL>, PU_CLERK, 2, 13900 >
< <NULL>, PU_MAN, 2, 11000 >
< <NULL>, SA_MAN, 2, 61000 >
< <NULL>, SA_REP, 2, 243500 >
< <NULL>, SH_CLERK, 2, 64300 >
< <NULL>, ST_CLERK, 2, 55700 >
< <NULL>, ST_MAN, 2, 36400 >
< <NULL>, <NULL>, 3, 684400 >
31 rows found.

INSTR, INSTRB, INSTR4

Determines the first position, if any, at which one string occurs within another. If the substring does not occur in the string, 0 is returned. The position returned is always relative to the beginning of SourceExpr. INSTR returns type NUMBER.

If you are using TimesTen type mode, for information on the INSTR function, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation.

SQL syntax

{INSTR | INSTRB | INSTR4} ( SourceExpr, SearchExpr [,m[,n]])

Parameters

INSTR has the parameters:

ParameterDescription
SourceExprThe string to be searched to find the position of SearchExpr. Value can be any supported character data types including CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB data types. Both TimesTen and Oracle data types are supported.
SearchExprThe substring to be found in string SourceExpr. If SearchExpr does not occur in SourceExpr, zero is returned. If either string is of length zero, NULL is returned.
mThe optional position at which to begin the search. If m is specified as zero, the result is zero. If m is positive, the search begins at the CharExpr2+m. If m is negative, the search begins m characters from the end of CharExpr2.
nIf n is specified it must be a positive value and the search returns the position of the nth occurrence of CharExpr1

Description

INSTR calculates strings using characters as defined by character set. INSTRB uses bytes instead of characters. INSTR4 uses UCS4 code points.

Examples

The following example uses INSTR to determine the position at which the substring 'ing' occurs in the string 'Washington':

Command> SELECT INSTR ('Washington', 'ing') FROM dual;
< 5 >
1 row found.

The following example uses INSTR to provide the number of employees with a '650' area code as input to the COUNT function:

Command> SELECT COUNT(INSTR(phone_number, '650')) FROM employees;
< 107 >
1 row found.

LAST_VALUE

The LAST_VALUE function is an analytic function that returns the last value in an ordered set of values.

SQL syntax

LAST_VALUE (Expression [IGNORE NULLS]) OVER (AnalyticClause)

Parameters

LAST_VALUE has the parameters:

ParameterDescription
ExpressionFor information on supported Expressions, see "Analytic functions".
IGNORE NULLSSpecify IGNORE NULLS if you wish LAST_VALUE to return the last non-NULL value in the set or NULL if all values in the set are NULL. Clause is optional.
OVER (AnalyticClause)For information on syntax, semantics, and restrictions, see "Analytic functions".

Description

Example

Use the LAST_VALUE function to return for each row the hire date of the employee with the highest salary.

Command> SELECT last_name, salary, hire_date,
       >  LAST_VALUE (hire_date) OVER (ORDER BY salary
       >    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lv
       > FROM
       > (SELECT * FROM employees WHERE department_id = 90 ORDER BY hire_date)
       > ORDER BY last_name, salary, hire_date, lv;
< De Haan, 17000, 1993-01-13 00:00:00, 1987-06-17 00:00:00 >
< King, 24000, 1987-06-17 00:00:00, 1987-06-17 00:00:00 >
< Kochhar, 17000, 1989-09-21 00:00:00, 1987-06-17 00:00:00 >
3 rows found.

LEAST

The LEAST function returns the smallest of the list of one or more expressions.

SQL syntax

LEAST (Expression [,...])

Parameters

LEAST has the parameter:

ParameterDescription
Expression [,...]List of one or more expressions that is evaluated to determine the smallest expression value. Operand or column can be numeric, character, or date. Each expression in the list must be from the same data type family.

Description

Use the LEAST function to return the string with the smallest value:

Command> SELECT LEAST ('SMALL','SMALLER','SMALLEST') FROM dual;
< SMALL >
1 row found.

Use the LEAST function to return the numeric expression with the smallest value. In this example, NUMBER is the data type with the highest numeric precedence, so arguments are implicitly converted to NUMBER before the comparison and the data type NUMBER is returned. First describe the table leastex to see the data types defined for columns col1 and col2. Then SELECT * from leastex to see the data. Then invoke the LEAST function.

Command> DESCRIBE leastex;

Table SAMPLEUSER.LEASTEX:
  Columns:
    COL1                            NUMBER (2,1)
    COL2                            TT_BIGINT

1 table found.
(primary key columns are indicated with *)
Command> SELECT * FROM leastex;
< 1.1, 1 >
1 row found.
Command> SELECT LEAST (Col2,Col1) from leastex;
< 1 >
1 row found.

Use the DESCRIBE command to confirm that the data type returned is NUMBER:

Command> DESCRIBE SELECT LEAST (Col2,Col1) FROM leastex;

Prepared Statement:
  Columns:
    EXP                             NUMBER

Use the LEAST function to return the DATE expression with the smallest value. DATE and TIMESTAMP are in the same date family.

Command> SELECT LEAST (DATE '2007-09-17', 
       > TIMESTAMP '2007-09-17:10:00:00') FROM dual;
< 2007-09-17 00:00:00 >
1 row found.

Attempt to use the LEAST function to return the smallest value in the list of TT_DATE and TT_TIMESTAMP expressions. You see an error because TT_DATE and TT_TIMESTAMP are in different date subfamilies and cannot be used in the same list of expressions.

Command> SELECT LEAST (TT_DATE '2007-09-17',
       > TT_TIMESTAMP '2007-09-17:01:00:00') FROM dual;
2817: Invalid data type TT_TIMESTAMP for argument 2 for function LEAST
The command failed.

Use the LEAST function to return the TIME expression with the smallest value.

Command> SELECT LEAST (TIME '13:59:59', TIME '13:59:58',
       > TIME '14:00:00') FROM dual;
< 13:59:58 >
1 row found.

LENGTH, LENGTHB, LENGTH4

Returns the length of a given character string in an expression. LENGTH returns type NUMBER.

If you are using TimesTen type mode, for information on the LENGTH function, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation.

SQL syntax

{LENGTH|LENGTHB|LENGTH4} (CharExpr) 

Parameters

LENGTH has the parameter:

ParameterDescription
CharExprThe string for which to return the length. Supported data types for CharExpr for are CHAR, VARCHAR2, NCHAR, or NVARCHAR2. LENGTH and LENGTHB also support CLOB, NCLOB, and BLOB data types.

Description

The LENGTH functions return the length of CharExpr. LENGTH calculates the length using characters as defined by the character set. LENGTHB uses bytes rather than characters. LENGTH4 uses UCS4 code points.

Examples

Determine the length of the string 'William':

Command> SELECT LENGTH('William') FROM dual;
< 7 >
1 row found.

The following determines the length of the NCLOB data:

Command> SELECT nclob_column FROM nclob_content;
< Demonstration of the NCLOB data type >
1 row found.

Command> SELECT LENGTH(nclob_column) FROM nclob_content;
< 36 >
1 row found.

LOWER and UPPER

The LOWER function converts expressions of type CHAR, NCHAR, VARCHAR2, NVARCHAR2, CLOB, or NCLOB to lowercase. The UPPER function converts expressions of type CHAR, NCHAR, VARCHAR2, NVARCHAR2, CLOB, or NCLOB to uppercase. Character semantics are supported for CHAR and VARCHAR2 types. The data type of the result is the same as the data type of the expression.

SQL syntax

{UPPER | LOWER} (Expression1)

Parameters

LOWER and UPPER have the following parameter:

ParameterDescription
Expression1An expression which is converted to lowercase (using LOWER) or uppercase (using UPPER).

Description

LOWER(?) and UPPER(?) are not supported, but you can combine it with the CAST operator. For example:

LOWER(CAST(? AS CHAR(30))) 

Command> SELECT LOWER (last_name) FROM employees WHERE employee_id = 100;
< king >
1 row found.

LPAD

The LPAD function returns Expression1, left-padded to length n characters with the sequence of characters in Expression2. This function is useful for formatting the output of a query.

SQL syntax

LPAD (Expression1, n [,Expression2])

Parameters

LPAD has the parameters:

ParameterDescription
Expression1CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be left-padded. If Expression1 is longer than n, then LPAD returns the portion of Expression1 that fits in n.
nLength of characters returned by the LPAD function. Must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer.
Expression2Sequence of characters to be left-padded in Expression1. If you do not specify Expression2, the default is a single blank. Operand or column can be of type CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB.

Description

Examples

The following prints out the last names of the first 5 employees, left-padded with periods out to 20 characters.

Command> SELECT FIRST 5 LPAD (last_name, 20, '.') 
 > FROM employees
 > ORDER BY last_name;
< ................Abel >
< ................Ande >
< ............Atkinson >
< ..............Austin >
< ................Baer >
5 rows found.

Use LPAD function to left-pad the string 'LPAD Function' with string 'DEMO-ONLY' plus 2 spaces. The DEMO-ONLY string is replicated as much as it can as defined by the total characters output by the function, which is replicated 3 times.

Command> SELECT LPAD ('LPAD Function', 46, 'DEMO-ONLY  ') FROM dual;
< DEMO-ONLY  DEMO-ONLY  DEMO-ONLY  LPAD Function >
1 row found.

Call LPAD function with length of -1. NULL is returned.

Command> SELECT LPAD ('abc', -1, 'a')  FROM dual;
< <NULL> >
1 row found.

LTRIM

The LTRIM function removes from the left end of Expression1 all of the characters contained in Expression2. TimesTen begins scanning Expression1 from its first character and removes all characters that appear in Expression2 until reaching a character not in Expression2 and returns the result.

SQL syntax

LTRIM (Expression1 [,Expression2])

Parameters

LTRIM has the parameters:

ParameterDescription
Expression1The CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be trimmed. If Expression1 is a character literal, then enclose it in single quotes.
Expression2Optional expression used for trimming Expression1. If Expression2 is a character literal, enclose it in single quotes. If you do not specify Expression2, it defaults to a single blank. Operand or column can be of type CHAR,VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB.

Description

Examples

Call the LTRIM function to remove left-most 'x' and 'y' from string. LTRIM removes individual occurrences of 'x' and 'y', not pattern 'xy'.

Command> SELECT LTRIM ('xxxyyyxyxyLTRIM Example', 'xy') FROM dual;
< LTRIM Example >
1 row found.

Call the LTRIM function to remove YYYY-MM-DD from SYSDATE. Call TO_CHAR to convert SYSDATE to VARCHAR2.

Command> SELECT LTRIM (TO_CHAR(SYSDATE), '2007-08-21') FROM dual;
<  22:54:39 >
1 row found.

Call LTRIM to remove all characters from Expression1. In the first example, the data type is CHAR, so NULL is returned. In the second example, the data type is TT_CHAR, so the empty string is returned.

Command> CREATE TABLE ltrimtest (col1 CHAR (4), col2 TT_CHAR (4));
Command> INSERT INTO ltrimtest VALUES ('ABBB','ABBB');
1 row inserted.
Command> SELECT LTRIM (col1, 'AB') FROM ltrimtest;
< <NULL> >
1 row found.
Command> SELECT LTRIM (col2, 'AB') FROM ltrimtest;
<  >
1 row found.

MAX

Finds the largest of the values in the argument (ASCII comparison for alphabetic types). Null values are ignored. MAX can be applied to numeric, character, and BINARY data types. MAX is an aggregate function and can also be an aggregate analytic function. For more details on aggregate functions, see "Aggregate functions". For more information on analytic functions, see "Analytic functions".

SQL syntax

MAX ([ALL | DISTINCT]{Expression | ROWID}) [OVER ([AnalyticClause])]

Parameters

MAX has the parameters:

ParameterDescription
ExpressionCan be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type.
ALLIncludes any duplicate rows in the argument of an aggregate function. If neither ALL nor DISTINCT is specified, ALL is assumed.
DISTINCTEliminates duplicate column values from the argument of an aggregate function.
ROWIDTimesTen assigns a unique ID called a rowid to each row stored in a table. The rowid value can be retrieved through the ROWID pseudocolumn. See "ROWID" for more details.
OVER ([AnalyticClause])If specified, indicates aggregate analytic function. For more information on analytic functions, see "Analytic functions".

Description

Examples

Find the largest salary:

Command> SELECT MAX(salary) "Max Salary" FROM employees;
 
MAX SALARY
< 24000 >
1 row found.

MIN

Finds the smallest of the values in the argument (ASCII comparison for alphabetic types). Null values are ignored. MIN can be applied to numeric, character, and BINARY data types. For more details on aggregate functions, see "Aggregate functions". MIN can also be an aggregate analytic function. For information on analytic functions, see "Analytic functions".

SQL syntax

 MIN ([ALL | DISTINCT]{Expression|ROWID}) [OVER (AnalyticClause)]

Parameters

MIN has the parameters:

ParameterDescription
ExpressionCan be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type.
ALLIncludes any duplicate rows in the argument of an aggregate function. If neither ALL nor DISTINCT is specified, ALL is assumed.
DISTINCTEliminates duplicate column values from the argument of an aggregate function.
ROWIDTimesTen assigns a unique ID called a rowid to each row stored in a table. The rowid value can be retrieved through the ROWID pseudocolumn. See "ROWID" for more details.
OVER (AnalyticClause)If specified, indicates aggregate analytic function. For more information on analytic functions, see "Analytic functions".

Description

Examples

Show the smallest salary:

Command> SELECT MIN(salary) "Min Salary" FROM employees;
 
MIN SALARY
< 2100 >

Show the earliest hire date:

1 row found.
Command> SELECT MIN(hire_date) "Earliest Hire Date" FROM employees;
 
EARLIEST HIRE DATE
< 1987-06-17 00:00:00 >
1 row found.

MOD

Returns the remainder of an INTEGER expression divided by a second INTEGER expression.

SQL syntax

MOD(Expression1, Expression2)

Parameters

MOD has the following parameters:

ParameterDescription
Expression1An INTEGER expression.
Expression2An INTEGER expression.

Description

The following example tests whether the value of the expression m is divisible by the value of expression n.

SELECT m, n FROM test WHERE MOD(m, n) = 0;

MONTHS_BETWEEN

The MONTHS_BETWEEN function returns number of months between dates date1 and date2.

SQL syntax

MONTHS_BETWEEN(date1, date2)

Parameters

MONTHS_BETWEEN has the parameters:

ParameterDescription
date1A datetime value or any value that can be converted to a datetime value.
date2A datetime value or any value that can be converted to a datetime value.

Description

Input parameters can be any combination of all supported datetime data types, excluding the TIME or TT_TIME data types. The supported datetime data types include DATE, TIMESTAMP, TT_DATE, TT_TIMESTAMP, ORA_DATE, and ORA_TIMESTAMP. For details on all datetime data types, see Chapter 1, "Data Types".

The return data type is a NUMBER.

MONTHS_BETWEEN returns number of months between dates date1 and date2.

Examples

The following examples calculate months between two given dates.

Command> SELECT MONTHS_BETWEEN(DATE '1995-02-02', DATE '1995-01-01') 
AS Months FROM dual;
 
MONTHS
< 1.03225806451613 >
1 row found. 

Command> SELECT MONTHS_BETWEEN(DATE '2010-02-02', DATE '2010-10-01') "Months"
 FROM dual;
 
MONTHS
< -7.96774193548387 >
1 row found.
 

The following command uses CAST to explicitly convert CHAR strings into timestamps. The first result is rounded to an integer.

Command> SELECT ROUND ( MONTHS_BETWEEN (CAST ('2010-04-15 14:13:52' 
AS TIMESTAMP), CAST ('2000-12-31 00:00:00' AS TIMESTAMP))), 
MONTHS_BETWEEN (CAST ('2010-04-15 14:13:52' AS TIMESTAMP), 
CAST ('2000-12-31 00:00:00' AS TIMESTAMP)) 
FROM dual;

< 112, 111.502998805257 >
1 row found.

NCHR

The NCHR function returns the character having the specified Unicode value.

SQL syntax

NCHR(n)

Parameters

NCHR has the parameter:

ParameterDescription
nThe specified Unicode value. The character having this Unicode value is returned. The result is of type NVARCHAR2.

Example

The following example returns the NCHAR character 187:

Command> SELECT NCHR(187) FROM dual;
< > >
1 row found.

NLS_CHARSET_ID

NLS_CHARSET_ID returns the character set ID number corresponding to the character set name.


Note:

For a complete list of supported character sets, see "Supported character sets" in the Oracle TimesTen In-Memory Database Reference.

SQL syntax

NLS_CHARSET_ID(String)

Parameters

NLS_CHARSET_ID has the parameter:

ParameterDescription
StringThe input string argument is a run-time VARCHAR2 value that represents the character set. This string is case-insensitive.

If the input string corresponds to a legal TimesTen character set, the associated character set ID number is returned; otherwise, NULL is returned.

Providing CHAR_CS returns the database character set ID number. Providing NCHAR_CS returns the national character set ID number. Other input string values are interpreted as Oracle NLS character set names, such as AL32UTF8.


Examples

The following example returns the character set ID number of character set JA16EUC:

SELECT NLS_CHARSET_ID('JA16EUC') FROM dual; 
< 830 >
1 row found.

NLS_CHARSET_NAME

NLS_CHARSET_NAME returns the name of the character set corresponding to the character set ID number.


Note:

For a complete list of supported character sets, see "Supported character sets" in the Oracle TimesTen In-Memory Database Reference.

SQL syntax

NLS_CHARSET_NAME(Number)

Parameters

NLS_CHARSET_NAME has the parameter:

ParameterDescription
NumberThe number represents a character set ID. If the number does not correspond to a legal TimesTen character set ID, NULL is returned.

Description

The character set name is returned as a VARCHAR2 value in the database character set.

Examples

The following example returns the character set name corresponding to character set ID number 2:

SELECT NLS_CHARSET_NAME(2) FROM dual;
< WE8DEC >
1 row found.

The following example determines the name of the database character set by providing CHAR_CS as the character set name within the NLS_CHARSET_ID function, whose results are provided to the NLS_CHARSET_NAME function:

SELECT NLS_CHARSET_NAME(NLS_CHARSET_ID('CHAR_CS')) FROM dual;
< US7ASCII >
1 row found.

NLSSORT

Returns the sort key value for the given string.

SQL syntax

NLSSORT (String [,'NLS_SORT = SortName'])

Parameters

NLSSORT has the following parameters:

ParameterDescription
StringGiven the String, NLSSORT returns the sort key value used to sort the String. Supported data types for String are CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, and NCLOB.
['NLS_SORT = SortName']SortName is either the linguistic sort sequence or BINARY. If you omit this parameter, then the default sort sequence for the session is used. Append to the SortName the suffix -ai for accent-insensitive sorting or -ci for case-insensitive sorting. For more information on acceptable linguistic SortName values, see "Supported linguistic sorts" in Oracle TimesTen In-Memory Database Reference.

Description

Examples

The following example illustrates sorting and comparison operations based on a linguistic sort sequence rather than on the binary value of the string. In addition, the example shows the same results can be obtained by using the ALTER SESSION... SET NLS_SORT statement.

Command> CREATE TABLE nsortdemo (name VARCHAR2 (15));
Command> INSERT INTO nsortdemo VALUES ('Gaardiner');
1 row inserted.
Command> INSERT INTO nsortdemo VALUES ('Gaberd');
1 row inserted.
Command> INSERT INTO nsortdemo VALUES ('Gaasten');
1 row inserted.
Command> # Perform Sort
Command> SELECT * FROM nsortdemo ORDER BY name;
< Gaardiner >
< Gaasten >
< Gaberd >
3 rows found.
Command> #Use function to perform sort
Command> SELECT * FROM nsortdemo ORDER BY NLSSORT (name, 'NLS_SORT = XDanish');
< Gaberd >
< Gaardiner >
< Gaasten >
3 rows found.
Command># comparison operation
Command> SELECT * FROM nsortdemo where Name > 'Gaberd';
< Gardiner >
1 row found.
Command> #Use function in comparison operation
Command> SELECT * FROM nsortdemo WHERE NLSSORT (name, 'NLS_SORT = XDanish') >
> NLSSORT ('Gaberd', 'NLS_SORT = XDanish');
< Gaardiner >
< Gaasten >
2 rows found.
Command> #Use ALTER SESSION to obtain the same results
Command> ALTER SESSION SET NLS_SORT = 'XDanish';
Session altered.
Command> SELECT * FROM nsortdemo ORDER BY name;
< Gaberd >
< Gaardiner >
< Gaasten >
3 rows found.
Command> SELECT * FROM nsortdemo WHERE name > 'Gaberd';
< Gaardiner >
< Gaasten >
2 rows found.

The following example creates a linguistic index:

Command> CREATE INDEX danishindex 
       > ON nsortdemo (NLSSORT (name, 'NLS_SORT =XDanish'));
Command> INDEXES N%;
Indexes on table USER1.NSORTDEMO:
  DANISHINDEX: non-unique range index on columns:
    NLSSORT(NAME,'NLS_SORT = XDanish')
  1 index found.
1 index found on 1 table.

NULLIF

NULLIF compares two expressions. If the values are equal, NULLIF returns a NULL; otherwise, the function returns the first expression.

SQL syntax

NULLIF(Expression1, Expression2)

Parameters

NULLIF has the following parameters:

ParameterDescription
Expression1The expression which is tested to see if equal to Expression2. You cannot specify the literal NULL for Expression1.
Expression2The expression which is tested to see if equal to Expression1.

Description


Note:

See "CASE expressions" for more details.

Examples

The following example selects employees who have changed jobs since they were hired, which is indicated by a different job_id in the job_history table from the current job_id in the employees table. Thus, when you apply NULLIF to the old and new job_id entries, those that are the same returns a NULL; those that are different indicate those employees who have changed jobs.

Command> SELECT e.last_name, NULLIF(e.job_id, j.job_id) "Old Job ID" 
 FROM employees e, job_history j 
 WHERE e.employee_id = j.employee_id 
 ORDER BY last_name, "Old Job ID";

< De Haan, AD_VP >
< Hartstein, MK_MAN >
< Kaufling, ST_MAN >
< Kochhar, AD_VP >
< Kochhar, AD_VP >
< Raphaely, PU_MAN >
< Taylor, SA_REP >
< Taylor, <NULL> >
< Whalen, AD_ASST >
< Whalen, <NULL> >
10 rows found.

NUMTODSINTERVAL

Converts a number or expression to an INTERVAL DAY TO SECOND type.

SQL syntax

NUMTODSINTERVAL (Expression1, IntervalUnit)

Parameters

NUMTODSINTERVAL has the parameters:

ParameterDescription
Expression1The argument can be any NUMBER value or an expression that can be implicitly converted to a NUMBER value.
IntervalUnitOne of the string constants: 'DAY', 'HOUR', 'MINUTE', or 'SECOND'.

Examples

Example using NUMTODSINTERVAL with SYSDATE:

Command> SELECT SYSDATE + NUMTODSINTERVAL(20,'SECOND') FROM dual;
< 2007-01-28 09:11:06 >

NUMTOYMINTERVAL

Converts a number or expression to an INTERVAL YEAR TO MONTH type.

SQL syntax

NUMTOYMINTERVAL (Expression1, 'IntervalUnit')

Parameters

NUMTOYMINTERVAL has the parameters:

ParameterDescription
Expression1The argument can be any NUMBER value or an expression that can be implicitly converted to a NUMBER value.
IntervalUnitOne of the string constants 'YEAR' or 'MONTH'.

Examples

An example using NUMTOYMINTERVAL:

Command> SELECT SYSDATE + NUMTOYMINTERVAL(1,'MONTH') FROM dual;
< 2007-02-28 09:23:28 >
1 row found.

NVL

The NVL function replaces a null value with a second value.

SQL syntax

NVL(Expression1, Expression2)

Parameters

NVL has the parameters:

ParameterDescription
Expression1The expression whose values are to be tested for NULL, which can be a CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, NCLOB, or BLOB expression.
Expression2The alternate value to use if the value of Expression1 is NULL, which can be a CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, NCLOB, or BLOB expression.

Description

Examples

This example checks for null values of commission_pct and replaces them with 'Not Applicable' for employees whose last name start with B.

Command> SELECT last_name, NVL(TO_CHAR(commission_pct), 'Not Applicable')
       > FROM employees 
       > WHERE last_name LIKE 'B%'
       > ORDER BY last_name;
< Baer, Not Applicable >
< Baida, Not Applicable >
< Banda, .1 >
< Bates, .15 >
< Bell, Not Applicable >
< Bernstein, .25 >
< Bissot, Not Applicable >
< Bloom, .2 >
< Bull, Not Applicable >
9 rows found.

POWER

The POWER function returns Base raised to the Exponent power. The base and exponent can be any numbers, but if the Base is negative, the exponent must be an integer.

SQL syntax

POWER (Base, Exponent)

Parameters

POWER has the parameters:

ParameterDescription
BaseOperand or column can be any numeric type. POWER returns this value raised to Exponent power.
ExponentOperand or column can be any numeric type. If Base is negative, Exponent must be an integer.

Description

If either Base or Exponent is of type BINARY_FLOAT or BINARY_DOUBLE, the data type returned is BINARY_DOUBLE. If the Base is of type NUMBER or TT_DECIMAL, and the Exponent is not of type BINARY_FLOAT or BINARY_DOUBLE, the date type returned is NUMBER with maximum precision and scale. If Base is one of the TT* numeric types (TT_BIGINT, TT_INTEGER, TT_SMALLINT, or TT_TINYINT), the data type returned is BINARY_DOUBLE.

Example

Use the POWER function to return the commission_pct squared for the employee with employee_id equal to 145.

Command> SELECT employee_id, commission_pct FROM employees 
 WHERE employee_id = 145;

< 145, .4 >
1 row found.

Command> SELECT POWER (commission_pct,2) FROM employees WHERE employee_id = 145;
< .16 >
1 row found.

RANK

The RANK function is an analytic function that calculates the rank of a value in a group of values.

SQL syntax

RANK () OVER ( [QueryPartitionClause] OrderByClause )

Parameters

RANK has the parameters:

ParameterDescription
QueryPartitionClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".
OrderByClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".

Description

Example

Use the RANK function to rank the first 10 employees in department 80 based on their salary and commission. Identical salary values receive the same rank and cause nonconsecutive ranks.

Command> SELECT first 10 department_id, last_name, salary, commission_pct,
       >  RANK() OVER (PARTITION BY department_id
       >    ORDER BY salary DESC, commission_pct) "Rank"
       > FROM employees WHERE department_id = 80
       > ORDER BY department_id, last_name, salary, commission_pct, "Rank";
< 80, Abel, 11000, .3, 5 >
< 80, Ande, 6400, .1, 31 >
< 80, Banda, 6200, .1, 32 >
< 80, Bates, 7300, .15, 26 >
< 80, Bernstein, 9500, .25, 14 >
< 80, Bloom, 10000, .2, 9 >
< 80, Cambrault, 7500, .2, 23 >
< 80, Cambrault, 11000, .3, 5
< 80, Doran, 7500, .3, 24 >
< 80, Errazuriz, 12000, .3, 3 >
10 rows found.

REPLACE

REPLACE substitutes a sequence of characters in a given string with another set of characters or removes the string entirely.

SQL syntax

REPLACE (String, SearchString [,ReplacementString] )

Parameters

REPLACE has the parameters:

ParameterDescription
StringSource string containing the substring to replace.
SearchStringString of characters to be replaced in the original string. If SearchString is NULL, the original String is returned without any modification.
ReplacementStringString of characters that are used to replace all occurrences of the search string in the original string. If ReplacementString is omitted or NULL, all occurrences of SearchString are removed from the source String.

Description

Examples

The following prints out all locations in Canada, replacing the country code of CA with Canada for easier readability.

Command> SELECT location_id, street_address,
> city, state_province, postal_code,
> REPLACE(country_id, 'CA', 'Canada') 
> FROM LOCATIONS 
> WHERE country_id LIKE 'CA';

< 1800, 147 Spadina Ave, Toronto, Ontario, M5V 2L7, Canada >
< 1900, 6092 Boxwood St, Whitehorse, Yukon, YSW 9T2, Canada >
2 rows found.

ROUND (Date)

Returns date rounded to the unit specified by the format model fmt. The value returned is of type DATE. If you do not specify fmt, then date is rounded to the nearest day.

SQL syntax

ROUND (Date [,Fmt]) 

Parameters

ROUND (Date) has the parameters:

ParameterDescription
DateThe date that is rounded. Must resolve to a date value.

If you do not specify fmt, then date is rounded to the nearest day.

[,Fmt]The format model rounding unit. Specify either a constant or a parameter for fmt.

Description

Examples

Round Date to the first day of the following year by specifying 'YEAR' as the format model:

Command> SELECT ROUND (DATE '2007-08-25','YEAR') FROM dual;
< 2008-01-01 00:00:00 >
1 row found.

Omit Fmt. Specify Date as type TIMESTAMP with a time of 13:00:00. Date is rounded to nearest day:

Command> SELECT ROUND (TIMESTAMP '2007-08-16 13:00:00') FROM dual;
< 2007-08-17 00:00:00 >
1 row found.

ROUND (expression)

The ROUND function returns Expression1 rounded to Expression2 places to the right of the decimal point.

SQL syntax

ROUND (Expression1 [,Expression2])

Parameters

ROUND has the parameters:

ParameterDescription
Expression1Operand or column can be any numeric type.
Expression2Operand or column that indicates how many places to round. Can be negative to round off digits left of the decimal point. If you omit Expression2, then Expression1 is rounded to 0 places. Must be an integer.

Description

Examples

Round a number 2 places to the right of the decimal point.

Command> SELECT ROUND (15.5555,2) FROM dual;
< 15.56 >
1 row found.

Round a number to the left of the decimal point by specifying a negative number for Expression2.

Command> SELECT ROUND (15.5555,-1) FROM dual;
< 20 >
1 row found.

Round a floating point number. Floating point numbers are rounded to nearest even value. Contrast this to rounding an expression of type NUMBER where the value is rounded up (for positive values).

Command> SELECT ROUND (1.5f), ROUND (2.5f) FROM dual;
< 2.00000000000000, 2.00000000000000 >
1 row found.
Command> SELECT ROUND (1.5), ROUND (2.5) FROM dual;
< 2, 3 >
1 row found.

ROW_NUMBER

The ROW_NUMBER function is an analytic function that assigns a unique number to each row to which it is applied (either each row in a partition or each row returned by the query), in the ordered sequence of rows specified in the OrderByClause, beginning with 1.

SQL syntax

ROW_NUMBER () OVER ( [QueryPartitionClause] OrderByClause )

Parameters

ROW_NUMBER has the parameters:

ParameterDescription
QueryPartitionClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".
OrderByClauseFor information on syntax, semantics, and restrictions, see "Analytic functions".

Description

Example

Use ROW_NUMBER to return the three highest paid employees in each department. Fewer then three rows are returned for departments with fewer than three employees.

Command> SELECT FIRST 10 department_id, first_name, last_name, salary
       > FROM
       >    (SELECT department_id, first_name, last_name, salary, ROW_NUMBER()
       >       OVER (PARTITION BY department_id ORDER BY salary desc) rn
       >     FROM employees )
       > WHERE rn <= 3
       > ORDER BY department_id, salary DESC, last_name;
< 10, Jennifer, Whalen, 4400 >
< 20, Michael, Hartstein, 13000 >
< 20, Pat, Fay, 6000 >
< 30, Den, Raphaely, 11000 >
< 30, Alexander, Khoo, 3100 >
< 30, Shelli, Baida, 2900 >
< 40, Susan, Mavris, 6500 >
< 50, Adam, Fripp, 8200 >
< 50, Matthew, Weiss, 8000 >
< 50, Payam, Kaufling, 7900 >
10 rows found.

RPAD

The RPAD function returns Expression1, right-padded to length n characters with Expression2, replicated as many times as necessary. This function is useful for formatting the output of a query.

SQL syntax

RPAD (Expression1, n [,Expression2])

Parameters

RPAD has the parameters:

ParameterDescription
Expression1CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be right-padded. If Expression1 is longer than n, then RPAD returns the portion of Expression1 that fits in n.
nLength of characters returned by RPAD function. Must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer.
Expression2CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be right-padded to Expression1. If you do not specify Expression2, the default is a single blank.

Description

Examples

Concatenate first_name and last_name from the employees table. Call the RPAD function to return first_name right-padded to length 12 with spaces and call RPAD a second time to return last_name right-padded to length 12 with spaces. Select first 5 rows.

Command> SELECT FIRST 5 CONCAT (RPAD (first_name,12),
       > RPAD (last_name,12)) FROM employees
       > ORDER BY first_name, last_name;
< Adam        Fripp        >
< Alana       Walsh        >
< Alberto     Errazuriz    >
< Alexander   Hunold       >
< Alexander   Khoo         >
5 rows found.

Call the RPAD function to return last_name right-padded to length 20 characters with the dot ('.') character. Use the employees table and select first 5 rows.

Command> SELECT FIRST 5 RPAD (last_name,20,'.') FROM employees
       > ORDER BY last_name;
< Abel................ >
< Ande................ >
< Atkinson............ >
< Austin.............. >
< Baer................ >
5 rows found.

RTRIM

The RTRIM function removes from the right end of Expression1 all of the characters contained in Expression2. TimesTen scans Expression1 backwards from its last character and removes all characters that appear in Expression2 until reaching a character not in Expression2 and then returns the result.

SQL syntax

RTRIM (Expression1 [,Expression2])

Parameters

RTRIM has the parameters:

ParameterDescription
Expression1The CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be trimmed. If Expression1 is a character literal, then enclose it in quotes.
Expression2Optional expression used for trimming Expression1. If Expression2 is a character literal, enclose it in single quotes. If you do not specify Expression2, it defaults to a single blank. Operand or column can be of type CHAR,VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB.

Description

Examples

The following example trims the trailing spaces from col1 in table rtrimtest.

Command> CREATE TABLE rtrimtest (col1 VARCHAR2 (25));
Command> INSERT INTO rtrimtest VALUES ('abc     ');
1 row inserted.
Command> SELECT * FROM rtrimtest;
< abc      >
1 row found.
Command> SELECT RTRIM (col1) FROM rtrimtest;
< abc >
1 row found.

Call the RTRIM function to remove right-most 'x' and 'y' from string. RTRIM removes individual occurrences of 'x' and 'y', not pattern 'xy'.

Command> SELECT RTRIM ('RTRIM Examplexxxyyyxyxy', 'xy') FROM dual;
< RTRIM Example >
1 row found.

Call RTRIM to remove all characters from Expression1. In the first example, the data type is CHAR, so NULL is returned. In the second example, the data type is TT_CHAR, so the empty string is returned.

Command> CREATE TABLE rtrimtest (col1 CHAR (4), col2 TT_CHAR (4));
Command> INSERT INTO rtrimtest VALUES ('BBBA', 'BBBA');
1 row inserted.
Command> SELECT RTRIM (col1, 'AB') FROM rtrimtest;
< <NULL> >
1 row found.
Command> SELECT RTRIM (col2, 'AB') FROM rtrimtest;
<  >
1 row found.

SESSION_USER

Returns the name of the TimesTen user currently connected to the database.

SQL syntax

SESSION_USER

Parameters

SESSION_USER has no parameters.

Examples

To return the name of the session user:

SELECT SESSION_USER FROM dual;

SIGN

The SIGN function returns the sign of Expression.

SQL syntax

SIGN (Expression)

Parameters

SIGN has the parameter:

ParameterDescription
ExpressionOperand or column can be any numeric data type.

Description

Examples

These examples illustrate use of the SIGN function with different data types. Table signex has been created and the columns have been defined with different data types. First, describe the table signex to see the data types of the columns. Then select each column to retrieve values for that column. Use the SIGN function to return the sign for the column.

Command> DESCRIBE signex;

Table SAMPLEUSER.SIGNEX:
  Columns:
    COL1                            TT_INTEGER
    COL2                            TT_BIGINT
    COL3                            BINARY_FLOAT
    COL4                            NUMBER (3,2)

1 table found.
(primary key columns are indicated with *)
Command> SELECT col1 FROM signex;
< 10 >
< -10 >
< 0 >
3 rows found.
Command> SELECT SIGN (col1) FROM signex;
< 1 >
< -1 >
< 0 >
3 rows found.
Command> SELECT col2 FROM signex;
< 0 >
< -3 >
< 0 >
3 rows found.
Command> SELECT SIGN (col2) FROM signex;
< 0 >
< -1 >
< 0 >
3 rows found.
Command> SELECT col3 FROM signex;
< 3.500000 >
< -3.560000 >
< NAN >
3 rows found.
Command> SELECT SIGN (col3) FROM signex;
< 1 >
< -1 >
< 1 >
3 rows found.
Command> SELECT col4 FROM signex;
< 2.2 >
< -2.2 >
< 0 >
3 rows found.
Command> SELECT SIGN (col4) FROM signex;
< 1 >
< -1 >
< 0 >
3 rows found.

SOUNDEX

The SOUNDEX function determines a phonetic signature for a string and allows comparisons of strings based on phonetic similarity. SOUNDEX lets you compare words that are spelled differently, but sound alike in English.

SQL syntax

SOUNDEX (InputString)

Parameters

SOUNDEX has the parameters:

ParameterDescription
InputStringValid types are CHAR, VARCHAR2, NCHAR and NVARCHAR2 with both ORA and TT variants and CLOB and NCLOB. If the data type is CLOB or NCLOB, TimesTen performs implicit conversion before returning the result.

Description

Examples

Use SOUNDEX function to return the phonetic signature for employees with last name equal to 'Taylor'.

Command> SELECT last_name, first_name, SOUNDEX (last_name)
       > FROM employees where last_name = 'Taylor';
< Taylor, Jonathon, T460 >
< Taylor, Winston, T460 >
2 rows found.

Invoke the function again to return the phonetic signature for the string 'Tailor'. Invoke the function a third time to return the last name and first name of each employee whose last name is phonetically similar to the string 'Tailor'.

Command> SELECT SOUNDEX ('Tailor') FROM dual;
< T460 >
1 row found.

Command> SELECT last_name, first_name FROM employees WHERE SOUNDEX (last_name) = 
       > SOUNDEX ('Tailor');
< Taylor, Jonathon >
< Taylor, Winston >
2 rows found.

SQRT

The SQRT function returns the square root of Expression.

SQL syntax

SQRT(Expression)

Parameters

SQRT has the parameter:

ParameterDescription
ExpressionOperand or column can be any numeric data type.

Description

Examples

Use SQRT function to return the square root of the absolute value of -10. Then cast the value as BINARY_FLOAT.

Command> SELECT CAST (SQRT (ABS (-10)) AS BINARY_FLOAT ) FROM dual;
< 3.162278 >
1 row found.

SUBSTR, SUBSTRB, SUBSTR4

Returns a string that represents a substring of a source string. The returned substring is of a specified number of characters, beginning from a designated starting point, relative to either the beginning or end of the string.

SQL syntax

{SUBSTR | SUBSTRB | SUBSTR4}=(Source, m, n)

Parameters

SUBSTR has the parameters:

ParameterDescription
SourceThe string for which this function returns a substring. Value can be any supported character data types including CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB data types. Both TimesTen and Oracle data types are supported.

If Source is a CHAR string, the result is a CHAR or VARCHAR2 string. If Source is a NCHAR string, the result is a NVARCHAR2 string. If Source is a LOB, the result is the same LOB data type.

mThe position at which to begin the substring. If m is positive, the first character of the returned string is m characters from the beginning of the string specified in char. Otherwise it is m characters from the end of the string. If ABS(m) is bigger than the length of the character string, a null value is returned.
nThe number of characters to be included in the substring. If n is omitted, all characters to the end of the string specified in char are returned. If n is less than 1 or if char, m or n is NULL, NULL is returned.

Description

SUBSTR calculates lengths using characters as defined by character set. SUBSTRB uses bytes instead of characters. SUBSTR4 uses UCS4 code points.

Examples

In the first 5 rows of employees, select the first three characters of last_name:

SELECT FIRST 5 SUBSTR(last_name,1,3) FROM employees;
< Kin >
< Koc >
< De  >
< Hun >
< Ern >
5 rows found.

In the first 5 rows of employees, select the last five characters of last_name:

SELECT FIRST 5 SUBSTR(last_name,-5,5) FROM employees;
< <NULL> >
< chhar >
<  Haan >
< unold >
< Ernst >
5 rows found.

SUM

Finds the total of all values in the argument. Null values are ignored. SUM is an aggregate function. SUM can also be an aggregate analytic function. For more details on aggregate functions, see "Aggregate functions". For more information on analytic functions, see "Analytic functions".

SQL syntax

SUM ([ALL | DISTINCT] Expression) [OVER ([AnalyticClause])]

Parameters

SUM has the parameters:

ParameterDescription
ExpressionCan be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type.
ALLIncludes any duplicate rows in the argument of an aggregate function. If neither ALL nor DISTINCT is specified, ALL is assumed.
DISTINCTEliminates duplicate column values from the argument of an aggregate function.
OVER ([AnalyticClause])If specified, indicates aggregate analytic function. For more information on analytic functions, see "Analytic functions".

Description

Examples

Sum all employee salaries:

Command> SELECT SUM(salary) Total FROM employees;
 
TOTAL
< 691400 >
1 row found.

SYS_CONTEXT

Returns information about the current session.

The data type of the return value is VARCHAR2.

SQL syntax

SYS_CONTEXT('namespace', 'parameter' [, length ])

Parameters

SYS_CONTEXT has the parameters:

ParameterDescription
namespaceValue: USERENV

Other values result in a return of NULL.

parameterSupported values:
  • AUTHENTICATION_METHOD

  • CURRENT_USER

  • CURRENT_USERID

  • IDENTIFICATION_TYPE

  • LANG

  • LANGUAGE

  • NLS_SORT

  • SESSION_USER

  • SESSION_USERID

  • SID

lengthNumber between 1 and 4000 bytes.

These are descriptions of the supported values for parameter:

ParameterDescription
AUTHENTICATION_METHODReturns the method of authentication for these types of users:
  • Local database user authenticated by password

  • External user authenticated by the operating system

CURRENT_USERThe name of the database user whose privileges are currently active. This may change during the duration of a session to reflect the owner of any active definer's rights object. When no definer's rights object is active, CURRENT_USER returns the same value as SESSION_USER. When used directly in the body of a view definition, this returns the user that is executing the cursor that is using the view. It does not respect views used in the cursor as being definer's rights.
CURRENT_USERIDThe identifier of the database user whose privileges are currently active
IDENTIFICATION_TYPEReturns the way the user was created in the database. Specifically, it reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that follows, the syntax used during user creation is followed by the identification type returned:
  • IDENTIFIED BY password: LOCAL

  • IDENTIFIED EXTERNALLY: EXTERNAL

LANGThe ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter.
LANGUAGEThe language and territory currently used by the session, along with the database character set, in this form:

language_territory.characterset

NLS_SORTBinary or linguistic sort.
SESSION_USERThe name of the database user at logon. This value remains the same throughout the duration of the session.
SESSION_USERIDThe identifier of the database user at logon.
SIDThe connection id of the current connection.

Description

The data type of the return value is VARCHAR2.

Examples

SELECT SYS_CONTEXT('USERENV', 'CURRENT_USER') FROM dual;
< TTUSER >
1 row found.

SELECT SYS_CONTEXT('USERENV', 'LANGUAGE') FROM dual;
< AMERICAN_AMERICA.AL32UTF8 >
1 row found.

SELECT SYS_CONTEXT('USERENV', 'IDENTIFICATION_TYPE') FROM dual;
< EXTERNAL >
1 row found.

SYSDATE and GETDATE

Returns the date in the format YYYY-MM-DD HH:MM:SS. The date represents the local current date and time, which is determined by the system on which the statement is executed.

If you are using TimesTen type mode, for information on SYSDATE, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation.

SQL syntax

SYSDATE | GETDATE( )

Parameters

The SYSDATE and GETDATE functions have no parameters.

Description

Examples

In this example, invoking SYSDATE returns the same date and time for all rows in the table:

Command> SELECT SYSDATE FROM dual;
< 2006-09-03 10:33:43 >
1 row found. 

This example invokes SYSDATE to insert the current data and time into column datecol:

Command> CREATE TABLE t (datecol DATE);
Command> INSERT INTO t VALUES (SYSDATE);
1 row inserted.
Command> SELECT * FROM t;
< 2006-09-03 10:35:50 >
1 row found.

In this example, GETDATE inserts the same date value for each new row in the table, even if the query takes several seconds.

INSERT INTO t1 SELECT GETDATE(), col1
   FROM t2 WHERE ...;

TO_CHAR is used with SYSDATE to return the date from table dual:

Command> SELECT TO_CHAR (SYSDATE) FROM dual;
< 2006-09-03 10:56:35 >
1 row found.

This example invokes TT_SYSDATE to return the TT_TIMESTAMP data type and then invokes ORA_SYSDATE to return the DATE data type:

Command> SELECT tt_sysdate FROM dual;
< 2006-10-31 20:02:19.440611 >
1 row found.
Command> SELECT ora_sysdate FROM dual;
< 2006-10-31 20:02:30 >
1 row found.

SYSTEM_USER

Returns the name of the current database user as identified by the operating system.

SQL syntax

SYSTEM_USER

Parameters

SYSTEM_USER has no parameters.

Examples

To return the name of the operating system user:

SELECT SYSTEM_USER FROM dual;

TIMESTAMPADD

The TIMESTAMPADD function adds a specified number of intervals to a timestamp and returns the modified timestamp.

SQL syntax

TIMESTAMPADD (Interval, IntegerExpression, TimestampExpression)

Parameters

TIMESTAMPADD has the parameters:

ParameterDescription
IntervalSpecified interval. Must be expressed as literal. Valid values are listed in the description section.
IntegerExpressionExpression that evaluates to TT_BIGINT.
TimestampExpressionDatetime expressions. Valid data types are ORA_DATE, ORA_TIMESTAMP, TT_DATE, and TT_TIMESTAMP. (The alias DATE and TIMESTAMP data types are also valid). TT_TIME is not supported.

Description

Examples

Use the TIMESTAMPADD function to add 3 months to timestamp '2009-11-30 10:00:00'. TimesTen increments the year and adjusts the day component to accommodate the 28 days in the month of February.

Command> SELECT TIMESTAMPADD (SQL_TSI_MONTH, 3, TIMESTAMP '2010-11-30 10:00:00')
       > FROM dual;
< 2011-02-28 10:00:00 >
1 row found.

Use the TIMESTAMPADD function to add 1 second to timestamp '2010-12-31 23:59:59'. TimesTen propagates the overflow through all components of the timestamp and advances the components appropriately.

Command> SELECT TIMESTAMPADD (SQL_TSI_SECOND, 1, TIMESTAMP '2010-12-31 23:59:59')
       > FROM dual;
< 2011-01-01 00:00:00 >
1 row found.

TIMESTAMPDIFF

The TIMESTAMPDIFF function returns the total number of specified intervals between two timestamps.

SQL syntax

TIMESTAMPDIFF (Interval, TimestampExpression1, TimestampExpression2)

Parameters

TIMESTAMPDIFF has the parameters:

ParameterDescription
IntervalSpecified interval. Must be expressed as literal. Valid values are listed in the description section.
TimestampExpression1Datetime expressions. Valid data types are ORA_DATE, ORA_TIMESTAMP, TT_DATE, and TT_TIMESTAMP. (The alias DATE and TIMESTAMP data types are also valid). TT_TIME is not supported.
TimestampExpression2Datetime expressions. Valid data types are ORA_DATE, ORA_TIMESTAMP, TT_DATE, and TT_TIMESTAMP. (The alias DATE and TIMESTAMP data types are also valid). TT_TIME is not supported.

Description

Examples

Use the TIMESTAMPDIFF function to calculate the difference in days between dates 2008-02-01 and 2008-03-01. Because 2008 is a leap year, the result is 29 days. The calculation is precise with no assumption of a 30 day month.

Command> SELECT TIMESTAMPDIFF (SQL_TSI_DAY, DATE '2008-02-01',
       > DATE '2008-03-01') FROM dual;
< 29 >
1 row found.

Use the TIMESTAMPDIFF function to calculate the difference in months between dates 2009-02-01 and 2009-03-01. Because there is a crossing of the interval month boundary, the function returns 1. In the second example, because days is specified for the interval, the result is 28.

Command> SELECT TIMESTAMPDIFF (SQL_TSI_MONTH, DATE '2009-02-01',
       > DATE '2009-03-01') FROM dual;
< 1 >
1 row found.

Command> SELECT TIMESTAMPDIFF (SQL_TSI_DAY, DATE '2009-02-01',
       > DATE '2009-03-01') FROM dual;
< 28 >
1 row found.

Use the TIMESTAMPDIFF function to calculate the difference in months between dates 2009-02-01 and 2009-02-29. Because there is not a crossing of the interval month boundary, the function returns 0.

Command> SELECT TIMESTAMPDIFF (SQL_TSI_MONTH, DATE '2009-02-01',
       > DATE '2009-02-28') FROM dual;
< 0 >
1 row found.

Use the TIMESTAMPDIFF function to illustrate the time difference in fractional seconds between mixed types. The time difference of one hour is returned in nanoseconds (unit for fractional seconds). The time element of the data type is set to 00:00:00.

Command> SELECT TIMESTAMPDIFF (SQL_TSI_FRAC_SECOND,
       > TT_TIMESTAMP '2009-12-31 01:00:00.00', DATE '2009-12-31') FROM dual;
< -3600000000000 >
1 row found.

TO_BLOB

The TO_BLOB function converts VARBINARY or BINARY to a BLOB:

SQL syntax

TO_BLOB ( ValidDataType )

Parameters

TO_BLOB has the parameters:

ParameterDescription
ValidDataTypeA value that is of VARBINARY or BINARY data type.

Examples

The following example creates a table with a BINARY and a VARBINARY columns. The TO_BLOB function is used on the values of these columns to convert the BINARY and VARBINARY data to a BLOB.

Command> CREATE TABLE bvar 
 > (col1 BINARY (10), col2 VARBINARY (10));

Command> INSERT INTO bvar (col1, col2)
 > VALUES (0x4D7953514C, 0x39274D);
1 row inserted.

Command> SELECT * FROM bvar;
 < 4D7953514C0000000000, 39274D >
1 row found.

Command> SELECT TO_BLOB(col1), TO_BLOB(col2) 
 > FROM bvar;
< 4D7953514C0000000000, 39274D >
1 row found.

TO_CHAR

The TO_CHAR function converts a DATE, TIMESTAMP or numeric input value to a VARCHAR2.

If you are using TimesTen type mode, for information on the TO_CHAR function, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation.

SQL syntax

TO_CHAR ( Expression1[, Expression2 [, Expression3]])

Parameters

TO_CHAR has the parameters:

ParameterDescription
Expression1A DATE, TIMESTAMP, CLOB, NCLOB, or numeric expression.
Expression2The format string. If omitted, TimesTen uses the default date format (YYYY-MM-DD).
Expression3A CHAR or VARCHAR2 expression to specify the NLS parameter, which is currently ignored.

Description

Examples

SELECT FIRST 5 first_name, 
               TO_CHAR (hire_date, 'MONTH DD, YYYY'),
               TO_CHAR (salary, '$999999.99')
  FROM employees;
< Steven, JUNE      17, 1987,   $24000.00 >
< Neena, SEPTEMBER 21, 1989,   $17000.00 >
< Lex, JANUARY   13, 1993,   $17000.00 >
< Alexander, JANUARY   03, 1990,    $9000.00 >
< Bruce, MAY       21, 1991,    $6000.00 >
5 rows found.

SELECT TO_CHAR(-0.12,'$B99.9999') FROM dual;
<   -$.1200 >
1 row found.

SELECT TO_CHAR(-12, 'B99999PR') FROM dual;
<     12  >
1 row found.

SELECT TO_CHAR(-12,'FM99999') FROM dual;
< -12 >
1 row found.

SELECT TO_CHAR(1234.1,'9,999.999') FROM dual;
<  1,234.100 >
1 row found.

TO_CLOB

The TO_CLOB function converts one of the following values to a CLOB:

SQL syntax

TO_CLOB ( ValidDataType )

Parameters

TO_CLOB has the parameters:

ParameterDescription
ValidDataTypeA value of one of the valid data types mentioned above.

Description

The TO_CLOB function will not operate on values contained in INTERVAL or TIMESTAMP with TIMEZONE data types.

Examples

The following example uses the TO_CLOB function to convert a string.

Command> DESCRIBE clob_content;
 
Table USER1.CLOB_CONTENT:
  Columns:
   *ID                              NUMBER (38) NOT NULL
    CLOB_COLUMN                     CLOB NOT NULL
 
1 table found.
(primary key columns are indicated with *)

Command> INSERT INTO clob_content (id, clob_column) 
 > VALUES (3, EMPTY_CLOB());
1 row inserted.

Command> UPDATE clob_content 
 > SET clob_column = TO_CLOB('Demonstration of the TO_CLOB function.') 
 > WHERE id = 3;
1 row updated.

TO_DATE

The TO_DATE function converts a CHAR, VARCHAR2, CLOB, or NCLOB argument to a value of DATE data type

If you are using TimesTen type mode, for information on the TO_DATE function, see the Oracle TimesTen In-Memory Database Release 6.0.3 documentation.

SQL syntax

TO_DATE (Expression1[, Expression2 [, Expression3]])

Parameters

TO_DATE has the parameters:

ParameterDescription
Expression1A CHAR, VARCHAR2, CLOB, or NCLOB expression.
Expression2The format string. This expression is usually required. It is optional only when Expression1 is in the default date format YYYY-MM-DD HHMMSS.
Expression3A CHAR or VARCHAR2 expression to specify the NLS parameter, which is currently ignored.

Description

You can use a datetime format model with the TO_DATE function. For more information on datetime format models, see "Datetime format models".

Examples

Command> SELECT TO_DATE ('1999, JAN 14', 'YYYY, MON DD') FROM dual;
< 1999-01-14 00:00:00 >
1 row found.

Command> SELECT TO_CHAR(TO_DATE('1999-12:23','YYYY-MM:DD')) FROM dual;
< 1999-12-23 00:00:00 >
1 row found.

Command> SELECT TO_CHAR(TO_DATE('12-23-1997 10 AM:56:20', 
'MM-DD-YYYY HH AM:MI:SS'),'MONTH,DD YYYY HH:MI-SS') FROM dual;
< DECEMBER ,23 1997 10:56-20 >
1 row found.

TO_LOB

The TO_LOB function converts supplied TT_VARCHAR and VARCHAR2 data types to a CLOB and VARBINARY data types to a BLOB.

SQL syntax

TO_LOB ( ValidDataType )

Parameters

TO_LOB has the parameters:

ParameterDescription
ValidDataTypeA value that is of TT_VARCHAR, VARCHAR2, or BINARY data types.

Description

You can use this function only on a TT_VARCHAR, VARCHAR2, or VARBINARY column, and only with the CREATE TABLE AS SELECT or INSERT...SELECT statements on tables with a defined LOB column.

Examples

The following example shows how to use the TO_LOB function within the INSERT...SELECT statement on a table with a LOB column.

Command> CREATE TABLE clb(c CLOB);
Command> CREATE TABLE vc (v VARCHAR2(2000));
Command> INSERT INTO vc(v) 
 > VALUES ('Showing the functionality of the TO_LOB function');
1 row inserted.

Command> INSERT INTO clb 
SELECT TO_LOB(v) FROM vc; 
1 row inserted.

Command> SELECT * FROM clb;
< Showing the functionality of the TO_LOB function >
1 row found.

Because of the restriction mentioned above, you cannot use the TO_LOB function in all cases where you can use the TO_CLOB or TO_BLOB functions. The following example demonstrates the error you receive when you try to use the TO_LOB function in this manner:

Command> SELECT TO_LOB(col1) 
 > FROM bvar;
 2610: Operand data type 'BINARY' invalid for operator 
 'TO_LOB' in expr ( TO_LOB( BVAR.COL1 ))
The command failed. 

TO_NCLOB

The TO_NCLOB function converts one of the following values to a NCLOB:

SQL syntax

TO_NCLOB ( ValidDataType )

Parameters

TO_NCLOB has the parameters:

ParameterDescription
ValidDataTypeA value of one of the valid data types mentioned above.

Examples

The following converts the data in the VARCHAR2 job_title column to be of data type NCLOB.

Command> SELECT TO_NCLOB(job_title) FROM jobs;

< Public Accountant >
< Accounting Manager >
< Administration Assistant >
< President >
< Administration Vice President >
< Accountant >
< Finance Manager >
< Human Resources Representative >
< Programmer >
< Marketing Manager >
< Marketing Representative >
< Public Relations Representative >
< Purchasing Clerk >
< Purchasing Manager >
< Sales Manager >
< Sales Representative >
< Shipping Clerk >
< Stock Clerk >
< Stock Manager >
19 rows found.

TO_NUMBER

Converts an expression to a value of NUMBER type.

SQL syntax

TO_NUMBER (Expression[, Format]) 

Parameters

TO_NUMBER has the parameters:

ParameterDescription
ExpressionThe expression to be converted, where the value can be of type CHAR, VARCHAR2, NCHAR, NVARCHAR2, BINARY_FLOAT, BINARY_DOUBLE, CLOB, or NCLOB.
FormatIf specified, the format is used to convert Expression to a value of NUMBER type. The format string identifies the number format model. The format and can be either a constant or a parameter.

Description

You can use a number format model with the TO_NUMBER function. For more information on number format models, see "Number format models".

Examples

Command> SELECT TO_NUMBER ('100.00', '999D99') FROM dual;
< 100 >
1 row found.

Command> SELECT TO_NUMBER ('1210.73', '9999.99') FROM dual;
< 1210.73 >
1 row found.

TRIM

The TRIM function trims leading or trailing characters (or both) from a character string.

SQL syntax

There are four syntax options for TRIM:

Parameters

TRIM has the parameters:

ParameterDescription
LEADING | TRAILING | BOTHLEADING | TRAILING| BOTH are qualifiers to TRIM function. LEADING removes all leading instances of Trim_character from Expression. TRAILING removes all trailing instances of Trim_character from Expression. BOTH removes leading and trailing instances of Trim_character from Expression.
[Trim_character]If specified, Trim_character represents the CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column used for trimming Expression. Must be only one character. If you do not specify Trim_character, it defaults to a single blank. If Trim_character is a character literal, enclose it in single quotes.
Expression )Expression is the CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB or NCLOB operand or column to be trimmed. If Expression is a character literal, enclose it in single quotes.

Description

Examples

Use TRIM function with qualifier to remove Trim_character '0' from Expression '0000TRIM Example0000':

Command> SELECT TRIM (LEADING '0' FROM '0000TRIM Example0000') FROM dual;
< TRIM Example0000 >
1 row found.
Command> SELECT TRIM (TRAILING '0' FROM '0000TRIM Example0000') FROM dual;
< 0000TRIM Example >
1 row found.
Command> SELECT TRIM (BOTH '0' FROM '0000TRIM Example0000') FROM dual;
< TRIM Example >
1 row found.

Use TRIM function with qualifier to remove blank spaces. Do not specify a Trim_character. Default value for Trim_character is blank space:

Command> SELECT TRIM (LEADING FROM '    TRIM Example    ') FROM dual;
< TRIM Example     >
1 row found.
Command> SELECT TRIM (TRAILING FROM '    TRIM Example    ') FROM dual;
<     TRIM Example >
1 row found.
Command> SELECT TRIM (BOTH FROM '    TRIM Example    ') FROM dual;
< TRIM Example >
1 row found.

Use TRIM function with Trim_character '0'. Do not specify a qualifier. Leading and trailing '0's are removed from Expression '0000TRIM Example0000':

Command> SELECT TRIM ('0' FROM '0000TRIM Example0000') FROM dual;
< TRIM Example >
1 row found.

Use TRIM function without a qualifier or Trim_character. Leading and trailing spaces are removed.

< TRIM Example >
1 row found.
Command> SELECT TRIM ('    TRIM Example    ') FROM dual;

TRUNC (date)

Returns date with the time portion of the day truncated to the unit specified by the format model fmt. The value returned is of type DATE. If you do not specify fmt, then date is truncated to the nearest day.

SQL syntax

TRUNC (date [,fmt]) 

Parameters

TRUNC (date) has the parameters:

ParameterDescription
dateThe date that is truncated. Specify the DATE data type for date. The function returns data type DATE with the time portion of the day truncated to the unit specified by the format model. If you do not specify fmt, the date is truncated to the nearest day. An error is returned if you do not specify the DATE data type.
[,fmt]The format model truncating unit. Specify either a constant or a parameter for fmt.

Description

For the permitted format models to use in fmt, see "Format model for ROUND and TRUNC date functions".

Examples

Command> SELECT TRUNC (TO_DATE ('27-OCT-92','DD-MON-YY'),'YEAR') FROM dual;
< 2092-01-01 00:00:00 >
1 row found.

TRUNC (expression)

Returns a number truncated to a certain number of decimal places.

SQL syntax

TRUNC (Expression [,m]) 

Parameters

TRUNC has the parameters:

ParameterDescription
ExpressionThe Expression to truncate. Operands must be of type NUMBER. An error is returned if operands are not of type NUMBER. The value returned is of type NUMBER.
[,m]The number of decimal places to truncate to. If m is omitted, then the number is truncated to 0 places. The value of m can be negative to truncate (make zero) m digits left of the decimal point.

Examples

SELECT TRUNC (15.79,1) FROM dual;
< 15.7 >
1 row found.

SELECT TRUNC (15.79,-1) FROM dual;
< 10 >
1 row found.

9L

TT_HASH

The TT_HASH function returns the hash value of an expression or list of expressions. This value is the value that is used by a hash index.

SQL syntax

TT_HASH(Expression [,...])

Parameters

TT_HASH has the parameter:

ParameterDescription
Expression [,...]One or more expressions to be used to determine the hash value of the expression or list of expressions.

Description

Examples

The following query finds the set of rows whose primary key columns hash to a given hash value:

SELECT * FROM t1 
  WHERE TT_HASH(pkey_col1, pkey_col2, pkey_col3) = 12345678; 

TTGRIDMEMBERID

When executed within a global query, gives the member ID in the cache grid of the owning member for each returned row.

SQL syntax

TTGRIDMEMBERID()

Parameters

TTGRIDMEMBERID() has no parameters.

Description

TTGRIDMEMBERID(), when executed within a global query, returns a TT_INTEGER with the member ID of the member where each returned row is located in the cache grid. If not executed within a global query, the current member ID is returned. NULL is returned if the member's node is not attached to a grid.

Autocommit should be set to OFF.

See "Obtaining information about the location of data in the cache grid" in Oracle In-Memory Database Cache User's Guide for more information on this function.

Examples

The following example shows autocommit set to OFF and sets the GlobalProcessing optimizer hint to 1, which makes the statements following part of a global query. The SELECT statement retrieves the employee number and member ID of the member where the employee data resides. The following output shows that the employee rows exist on members 2 and 4.

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Commmand> SELECT employee_id, TTGRIDMEMBERID() FROM employees;
< 7900, 2 >
< 7902, 4 >
2 rows found.

The following example uses TTGRIDMEMBERID() in an ORDER BY clause.

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Command> SELECT employee_id, TTGRIDMEMBERID() FROM employees 
 ORDER BY TTGRIDMEMBERID();
< 7900, 2 >
< 7902, 4 >
2 rows found.
 

The following example uses TTGRIDMEMBERID() in a WHERE clause:

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Command> SELECT employee_id, TTGRIDMEMBERID() FROM employees 
 WHERE TTGRIDMEMBERID()=2;
< 7900, 2 >
1 row found.

The following example executes TTGRIDMEMBERID() as a local query to retrieve the local member ID, which is 1.

Command> SELECT TTGRIDMEMBERID() FROM dual;
< 1 >
1 row found.

TTGRIDNODENAME

When executed within a global query, returns the name of the node in a cache grid on which the data is located.

SQL syntax

TTGRIDNODENAME()

Parameters

TTGRIDNODENAME() has no parameters.

Description

TTGRIDNODENAME() returns a TT_VARCHAR(64) with the node name of the node on which each returned row is located, which shows the location of data in a cache grid. NULL is returned if the node is not attached to a grid.

Autocommit should be set to OFF.

See "Obtaining information about the location of data in the cache grid" in Oracle In-Memory Database Cache User's Guide for more information.

Examples

The following example shows autocommit set to OFF and sets the GlobalProcessing optimizer hint to 1, which makes the statements following part of a global query. The SELECT statement retrieves the employee number and name of the node where the employee data resides. The following output shows that the employee rows exist on members 2 and 4.

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Commmand> SELECT employee_id, TTGRIDNODENAME() FROM employees;
< 7900, MYGRID_member2 >
< 7902, MYGRID_member4 >
2 rows found.

TTGRIDUSERASSIGNEDNAME

Within a global query, returns the user-assigned name of the node in a cache grid on which the data is located.

SQL syntax

TTGRIDUSERASSIGNEDNAME()

Parameters

TTGRIDUSERASSIGNEDNAME() has no parameters.

Description

TTGRIDUSERASSIGNEDNAME() returns a TT_VARCHAR(30) with the node name assigned by the user to the node of the grid on which the data is located. NULL is returned if the node is not attached to a grid.

Autocommit should be set to OFF.

See "Obtaining information about the location of data in the cache grid" in Oracle In-Memory Database Cache User's Guide for more information.

Examples

The following example includes a cache grid whose members have user-assigned names alone1, alone2, and an active standby pair on nodes cacheact and cachestand. The standby database has the same data as the active database, but the query does not return data from the standby database.

The following example retrieves employee_id and the user-assigned node name with TTGRIDUSERASSIGNEDNAME() from the employees table from the grid members. The returned rows show which grid node owns each row of the cache instance.

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Commmand> SELECT employee_id, TTGRIDUSERASSIGNEDNAME() FROM employees;
Commmand> COMMIT;
< 100, alone1>
< 101, alone2>
< 102, cacheact>
< 103, alone1>
< 104, cacheact>
...

Subsequent queries can access the appropriate node without changing the ownership of the data. For example, execute this query on grid node cacheact, including TTGRIDUSERASSIGNEDNAME() to verify that cacheact is the node where the data is located:

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Commmand> SELECT employee_id, last_name, hire_date, TTGRIDUSERASSIGNEDNAME() 
 FROM employees WHERE employee_id=104;
< 104, Ernst, cacheact, 1991-05-21 00:00:00 >

The following example retrieves the employee number and user-assigned name for the node on which the employee data exists and orders the returned data by the user-assigned name:

Commmand> AUTOCOMMIT OFF;
Commmand> CALL ttOptSetFlag('GlobalProcessing', 1);
Commmand> SELECT employee_id, TTGRIDUSERASSIGNEDNAME() FROM employees ORDER BY
 TTGRIDUSERASSIGNEDNAME() ASC;
< 7900, member2 >
< 7902, member4 >
2 rows found.

UID

This function returns an integer (TT_INTEGER) that uniquely identifies the session user.

Examples

SELECT UID FROM dual;
< 10 >
1 row found.

UNISTR

The UNISTR function takes as its argument a string that resolves to data of type NVARCHAR2 and returns the value in UTF-16 format. Unicode escapes are supported. You can specify the Unicode encoding value of the characters in the string.

SQL syntax

UNISTR ('String')

Parameters

UNISTR has the parameter:

ParameterDescription
'String'The string passed to the UNISTR function. The string resolves to type NVARCHAR2. TimesTen returns the value in UTF-16 format. You can specify Unicode escapes as part of the string.

Examples

The following example invokes the UNISTR function passing as an argument the string 'A\00E4a'. The value returned is the value of the string in UTF-16 format:

Command> SELECT UNISTR ('A\00E4a') FROM dual;
<Aäa> 1 row found.

USER

Returns the name of the TimesTen user who is currently connected to the database.

SQL syntax

USER

Parameters

USER has no parameters.

Examples

To return the name of the user who is currently connected to the database:

SELECT USER FROM dual;
PKd~J99PK*AOEBPS/index.htm Index

Index

A  B  C  D  E  F  G  H  I  J  L  M  N  O  P  Q  R  S  T  U  V  W  X 

Symbols

%
in LIKE predicate, 5
& operator, 3
* , See multiplying
+ , See addition
+ operator
WHERE clause, 6.1
^ operator, 3
_
in LIKE predicate, 5
| operator, 3
|| operator, 3
~ operator, 3

A

ABS function, 4.13
access control
overview, 7
active standby pair
altering, 6.1
ADD column, 6.1
ADD ELEMENT
replication, 6.1
ADD SUBSCRIBER
replication, 6.1
ADD_MONTHS function, 4.13
addition, 3, 3
ADMIN system privilege
definition, 7.1
aggregate functions
ALL, 4.13, 4.13, 4.13, 4.13, 4.13
and overflow, 1.18
AVG, 4.13
DISTINCT, 4.13, 4.13, 4.13, 4.13, 4.13
in expressions, 3
in GROUP BY clause, 6.1
in query, 6.1
MAX, 4.13
over empty, ungrouped table, 4.13, 4.13, 4.13, 4.13, 4.13
SQL syntax, 4.10
AGING reserved word, 8
ALL
defined, 4.13, 4.13, 4.13
in SELECT statements, 6.1
ALL modifier, 4.13, 4.13
ALL/ NOT IN predicate (subquery), 5
ALL reserved word, 8
ALL/NOT IN predicate (value list), 5
ALTER ACTIVE STANDBY PAIR statement, 6.1
ALTER ANY CACHE GROUP system privilege
definition, 7.1
ALTER ANY INDEX system privilege
definition, 7.1
ALTER ANY MATERIALIZED VIEW system privilege
definition, 7.1
ALTER ANY PROCEDURE system privilege
definition, 7.1
ALTER ANY SEQUENCE system privilege
definition, 7.1
ALTER ANY TABLE system privilege
definition, 7.1
ALTER ANY VIEW system privilege
definition, 7.1
ALTER CACHE GROUP statement, 6.1
AUTOREFRESH cache groups, 6.1
AUTOREFRESH state, 6.1
READONLY cache groups, 6.1
ALTER ELEMENT clause
DROP MASTER, 6.1
DROP SUBSCRIBER, 6.1
replication, 6.1
ALTER FUNCTION statement, 6.1
ALTER PACKAGE statement, 6.1
ALTER PROCEDURE statement, 6.1
ALTER REPLICATION statement, 6.1
ALTER SESSION statement, 6.1
ALTER SUBSCRIBER clause, 6.1
ALTER TABLE statement
ADD column, 6.1
defined, 6.1
DROP column, 6.1
PRIMARY KEY, 6.1
table names, 6.1
ALTER USER statement, 6.1
analytic functions, 4.11
ANSI SQL data types, 1.2
ANY/ IN predicate (subquery), 5
ANY/ IN predicate (value list), 5
ANY predicate
defined, 5
example, 5
operators, 5
SQL syntax, 5
ANY reserved word, 8
approximate data types, 1.6
arithmetic operations
and overflow, 1.18
arithmetic operators
in expressions, 3, 3
AS reserved word, 8
ASC clause
CREATE INDEX statement, 6.1
ASCII characters, 3
ASCIISTR function, 4.13
asynchronous materialized view
creating, 6.1
attributes
altering, 6.1
AUTOREFRESH clause
ALTER CACHE GROUP statement, 6.1
FULL, 6.1
in cache groups, 6.1
INCREMENTAL, 6.1
INTERVAL, 6.1
STATE, 6.1
AVG function, 4.13

B

basic names
definition, 2.1
objects having, 2.1
rules, 2.1
BETWEEN predicate
defined, 5
in search conditions, 5
SQL syntax, 5
BETWEEN reserved word, 8
BIGINT data type, 1.21.1
BINARY data type, 1.1, 1.7, 1.13, 1.21.1
BINARY_DOUBLE data type, 1.1, 1.6.6.1, 1.13, 1.21.1
BINARY_DOUBLE_INFINITY reserved word, 8
BINARY_DOUBLE_NAN reserved word, 8
BINARY_FLOAT data type, 1.1, 1.6.6.2, 1.13, 1.21.1
BINARY_FLOAT_INFINITY reserved word, 8
BINARY_FLOAT_NAN, 8
bitwise AND operator, 3
bitwise NOT operator, 3
bitwise OR operator, 3
BLOB
conversion function, 4.13
initialize, 4.13
overview, 1.1
bucket count, 6.1

C

cache
functions, 4.13
grid, 6.1
functions, 4.13
cache groups
aging, 6.1
ALTER CACHE GROUP statement, 6.1
CREATE CACHE GROUP statement, 6.1
definition, 6.1
DROP CACHE GROUP statement, 6.1
dynamic, 6.1
explicitly loaded, 6.1
FLUSH CACHE GROUP statement, 6.1
global, 6.1
instance definition, 6.1
LOAD CACHE GROUP statement, 6.1
local, 6.1
refreshing, 6.1, 6.1, 6.1
restrictions, 6.1
system managed, 6.1, 6.1
UNLOAD CACHE GROUP statement, 6.1
user managed, 6.1
user manager, 6.1
CACHE_MANAGER system privilege
definition, 7.1
privilege hierarchy, 7.3
CALL statement, 6.1
CASE function, 3
CASE reserved word, 8
CAST function, 4.13
CEIL function, 4.13
CHAR data type, 1.1, 1.5.1, 1.13, 1.21.1
CHAR reserved word, 8
CHAR VARYING data type, 1.2
CHARACTER
values in constants, 3
character
ASCII, 3
data truncation, 1.18
data types, 1.5
national character string
constant, 3
string, 3
Unicode
example, 5
pattern matching, 5
UTF-8 Unicode character, 3
CHARACTER VARYING data type, 1.2
CHECK CONFLICTS clause
replication, 6.1
syntax, 6.1
CHR function, 4.13
CLOB
conversion function, 4.13
initialize, 4.13
overview, 1.1
COALESCE function, 4.13
column
alias in SELECT statement, 6.1, 6.1
definition, 6.1, 6.1, 6.1
grouping, 6.1
eliminating duplicates, 6.1
in tables, 6.1
maximum in CREATE TABLE, 6.1, 6.1
name
in expressions, 3
in INSERT SELECT statements, 6.1
in NULL predicates, 5
reference
in GROUP BY clause, 6.1
in SELECT statements, 6.1
syntax, 6.1
results in SELECT statement, 6.1
COLUMN reserved word, 8
COMMIT statement, 6.1
comparison predicate
example, 5
in search conditions, 5
operators, 5
SQL syntax, 5, 5, 5
compound identifiers, 2.3
compression
in-memory columnar compression, 6.1
CONCAT function, 4.13
concatenate operator, 3
conflict resolution
check conflicts, 6.1
replication, 6.1
CONNECTION reserved word, 8
constants
character strings, 3
CHARACTER values, 3
DATE values, 3, 3
defined, 3
fixed point values, 3
FLOAT values, 3, 3
HEXIDECIMAL values, 3
in expressions, 3
in NULL predicates, 5
INTEGER values, 3
SQL syntax, 3
TIME values, 3
TIMESTAMP values, 3
CONSTRAINT reserved word, 8
constraints, defining, 6.1
correlation name
definition, 6.1
in SELECT statement, 6.1, 6.1
COUNT function, 4.13
CREATE ACTIVE STANDBY PAIR statement, 6.1
CREATE ANY CACHE GROUP system privilege
definition, 7.1
CREATE ANY INDEX system privilege
definition, 7.1
CREATE ANY MATERIALIZED VIEW system privilege
definition, 7.1
CREATE ANY PROCEDURE system privilege
definition, 7.1
CREATE ANY SEQUENCE system privilege
definition, 7.1
CREATE ANY SYNONYM system privilege
definition, 7.1
CREATE ANY TABLE system privilege
definition, 7.1
CREATE ANY VIEW system privilege
definition, 7.1
CREATE CACHE GROUP system privilege
definition, 7.1
CREATE FUNCTION, 6.1
defined, 6.1
CREATE GLOBAL TEMPORARY TABLE, 6.1, 6.1
CREATE INDEX statement, 6.1
ASC clause, 6.1
defined, 6.1
DESC clause, 6.1
example, 6.1
index name, 6.1
table names, 6.1
tables without rows, 6.1
UNIQUE clause, 6.1
CREATE MATERIALIZED VIEW
defined, 6.1
CREATE MATERIALIZED VIEW LOG statement, 6.1
CREATE MATERIALIZED VIEW system privilege
definition, 7.1
CREATE PACKAGE
defined, 6.1
CREATE PACKAGE BODY, 6.1, 6.1, 6.1
CREATE PACKAGE BODY statement, 6.1
CREATE PACKAGE statement, 6.1
CREATE PROCEDURE statement, 6.1, 6.1
defined, 6.1
CREATE PROCEDURE system privilege
definition, 7.1
CREATE PUBLIC SYNONYM system privilege
definition, 7.1
CREATE REPLICATION statement, 6.1
CREATE SEQUENCE statement, 6.1
defined, 6.1
CREATE SEQUENCE system privilege
definition, 7.1
CREATE SESSION system privilege
definition, 7.1
CREATE SYNONYM statement, 6.1
CREATE SYNONYM system privilege
definition, 7.1
CREATE TABLE statement
defined, 6.1
examples, 6.1
FOREIGN KEY, 6.1
hash column name, 6.1
maximum columns, 6.1, 6.1, 6.1, 6.1
maximum page number, 6.1
PRIMARY KEY, 6.1
CREATE TABLE system privilege
definition, 7.1
CREATE USER statement, 6.1
CREATE VIEW statement, 6.1
CREATE VIEW system privilege
definition, 7.1
creating
active standby pairs, 6.1
cache groups, 6.1
constraints, 6.1
functions, 6.1
indexes, 6.1, 6.1
materialized views, 6.1
procedures, 6.1, 6.1
sequences, 6.1
tables, 6.1, 6.1
users, 6.1
views, 6.1
CROSS reserved word, 8
CUBE clause
example, 6.1
GROUPING function, 4.10
GROUPING_ID function, 4.13
overview, 6.1, 6.1
syntax, 6.1
CURRENT_SCHEMA, 8
CURRENT_USER function, 4.13
CURRENT_USER reserved word, 8
CURRVAL, 6.1, 6.1
CURSOR reserved word, 8

D

d (ODBC-date-literal syntax), 3
data
truncation, 1.18
Data Definition Language (DDL), 6
Data Manipulation Language (DML), 6
data overflow, 1.18
data types
ANSI SQL, 1.2
approximate types, 1.6
backward compatibility support, 1.3
character types, 1.5
comparing in search conditions, 5
comparison rules, 1.14
conversion, 1.15
effect of, 1
exact and approximate, 1.6
exact types, 1.6
modes, 1.1
specifications, 1.1
storage requirements, 1.13, 1.13
TimesTen/Oracle compatibility, 1.3, 1.4
TIMEZONE unsupported, 1.12.3
DATASTORE clause
in CREATE REPLICATION statement, 6.1
DATASTORE_OWNER reserved word, 8
DATE data type, 1.1, 1.11.1, 1.12.2, 1.12.2, 1.13, 1.21.1
DATE literal
ODBC date-literal syntax, 3
values in constants, 3, 3
date literal
defined, 3
DATE reserved word, 8
date string
defined, 3
datetime and interval types
arithmetic operations, 1.12.4
datetime data types, 1.11
using, 1.12.2
datetime format model
for TO_CHAR of TT_TIMESTAMP and TT_DATE, 3
datetime format models, 3
DECIMAL data type, 1.2
DECIMAL reserved word, 8
DECODE function, 4.13
DEFAULT column value, 6.1, 6.1
DEFAULT reserved word, 8
DELETE ANY TABLE system privilege
definition, 7.1
DELETE object privilege
definition, 7.2
DELETE statement
and DROP TABLE statement, 6.1
defined, 6.1
search conditions, 6.1
deleting
indexes, 6.1
rows, 6.1
tables, 6.1
DENSE_RANK function, 4.13
derived tables, 6.1, 6.1
creating, 6.1
described, 6.1
in SELECT statement, 6.1
in TableSpec, 6.1
restrictions, 6.1
DESC clause, 6.1
DESTROY reserved word, 8
detail tables, 6.1, 6.1, 6.1
and ON DELETE CASCADE, 6.1
in materialized views, 6.1
restrictions, 6.1
VIEWS, 6.1
DISTINCT modifier, 4.13, 4.13
and subqueries, 3
defined, 4.13, 4.13, 4.13
in SELECT statement, 6.1
DISTINCT reserved word, 8
dividing, 3
DOUBLE PRECISION data type, 1.2
DROP ACTIVE STANDBY PAIR statement, 6.1
DROP ANY CACHE GROUP system privilege
definition, 7.1
DROP ANY INDEX system privilege
definition, 7.1
DROP ANY MATERIALIZED VIEW system privilege
definition, 7.1
DROP ANY PROCEDURE system privilege
definition, 7.1
DROP ANY SEQUENCE system privilege
definition, 7.1
DROP ANY SYNONYM system privilege
definition, 7.1
DROP ANY TABLE system privilege
definition, 7.1
DROP ANY VIEW system privilege
definition, 7.1
DROP CACHE GROUP statement, 6.1
DROP column, 6.1
DROP ELEMENT clause
replication, 6.1
DROP FUNCTION statement, 6.1
DROP INDEX statement, 6.1
DROP MATERIALIZED VIEW LOG statement, 6.1
DROP MATERIALIZED VIEW statement, 6.1
DROP PACKAGE statement, 6.1
DROP PROCEDURE statement, 6.1
DROP PUBLIC SYNONYM system privilege
definition, 7.1
DROP REPLICATION statement, 6.1
DROP SEQUENCE statement, 6.1
DROP SYNONYM statement, 6.1
DROP TABLE statement, 6.1
DROP USER statement, 6.1
DROP VIEW statement, 6.1
dropping
active standby pairs, 6.1
cache groups, 6.1
functions, 6.1
indexes, 6.1, 6.1
procedures, 6.1, 6.1
replication schemes, 6.1
sequences, 6.1
tables, 6.1
views, 6.1
duplicate parameters, 2.6
DURABLE clause
in CREATE REPLICATION statement, 6.1
dynamic cache groups, 6.1
dynamic parameters
example, 3
in expressions, 3, 3
in LIKE predicate, 5
in single row inserts, 6.1
names, 2.5
naming rules, 2.5

E

ELEMENT clause
in CREATE REPLICATION statement, 6.1
EMPTY_BLOB function, 4.13
EMPTY_CLOB function, 4.13
escape character
in LIKE predicate, 5
exact data types, 1.6
exclusive OR operator, 3
EXECUTE ANY PROCEDURE system privilege
definition, 7.1
EXECUTE object privilege
definition, 7.2, 7.2
EXISTS predicate, 5, 5
defined, 5
in search conditions, 5
SQL syntax, 5
expressions
arithmetic operators in, 3, 3
bitwise AND operator, 3
bitwise NOT operator, 3
bitwise OR operator, 3
comparing, 4.13
concatenate operators, 3
dividing, 3
exclusive OR operator, 3
in BETWEEN predicates, 5, 5
in comparison predicate, 5, 5, 5
in IS INFINITE predicate, 5
in NAN predicates, 5
in NULL predicates, 5, 5
in UPDATE statements, 6.1
multiplying, 3
ROWID, 3
ROWNUM, 3
specification, 3
SQL syntax, 3
EXTRACT function, 4.13

F

FAILTHRESHOLD clause
in ALTER REPLICATION statement, 6.1
in CREATE ACTIVE STANDBY PAIR statement, 6.1
in CREATE REPLICATION statement, 6.1
FIRST reserved word, 8
FIRST_VALUE function, 4.13
fixed point value
constants, 3
defined, 3
FLOAT (n) data type, 1.6.6.3
FLOAT data type, 1.2, 1.6.6.3
FLOAT reserved word, 8
float value
defined, 3, 3
FLOAT values
in constants, 3, 3
floating-point numbers, 1.6.6
FLOOR function, 4.13
FLUSH ANY CACHE GROUP system privilege
definition, 7.1
FLUSH CACHE GROUP statement, 6.1, 6.1
FLUSH object privilege
definition, 7.2
FOR reserved word, 8
FOREIGN KEY option
in CREATE TABLE statement, 6.1
FOREIGN reserved word, 8
format model, 3
for ROUND and TRUNC date functions, 3
for TO_CHAR of TimesTen types, 3, 3
FROM reserved word, 8
fully qualified name, 2.3
functions
analytic, 4.11
creating, 6.1

G

GETDATE function, 4.13
global cache groups, 6.1
GLOBAL TEMPORARY TABLE, 6.1, 6.1
global temporary table
object privilege, 6.1
GRANT statement, 6.1
GREATEST, 4.13
grid
cache, 6.1
functions, 4.13
GROUP BY clause
eliminate duplicate grouping rows, 4.13
GROUPING_ID function, 4.13
identifying superaggregates, 4.10
in aggregate functions, 4.13, 4.13, 4.13, 4.13, 4.13
in SELECT statements, 6.1
overview, 6.1
syntax, 6.1, 6.1
GROUP reserved word, 8
GROUP_ID function, 4.13
grouping
columns, 6.1, 6.1
eliminating duplicates, 6.1
GROUPING clause
eliminate NULL groupings, 6.1
GROUPING function
overview, 4.10
GROUPING SETS clause
overview, 6.1, 6.1
syntax, 6.1
GROUPING_ID function
overview, 4.13

H

hash index
examples, 6.1
for table, 6.1
materialized view, 6.1
pages, 6.1
HashColumnName option
in CREATE TABLE statement, 6.1
HAVING clause
GROUPING function, 4.13
in SELECT statements, 6.1
HAVING reserved word, 8
HEXIDECIMAL
values in constants, 3
hexidecimal string
defined, 3

I

IN predicate
in search conditions, 5
index
owner
default, 6.1
index names
in CREATE INDEX, 6.1
in DROP INDEX, 6.1
INDEX object privilege
definition, 7.2
indexes
creating, 6.1
dropping, 6.1
owner not specified, 6.1
INF data type, 1.17
INLINE clause, 6.1
in ALTER TABLE statement, 6.1
INNER reserved word, 8
INSERT ANY TABLE system privilege
definition, 7.1
INSERT object privilege
definition, 7.2
INSERT SELECT statement, 6.1
omitted columns, 6.1
rows with defined values, 6.1
INSERT statement, 6.1
INSTR function, 4.13
INSTR4 function, 4.13
INSTRB function, 4.13
INTEGER data type, 1.2, 1.21.1
INTEGER reserved word, 8
integer value
defined, 3
INTEGER values
in constants, 3
INTERSECT reserved word, 8
INTERVAL data type, 1.1, 1.13, 1.21.1
using, 1.12.1
interval literal, 3
INTERVAL reserved word, 8
INTO reserved word, 8
IS INFINITE predicate, 5, 5
IS NAN predicate, 5
IS NULL predicate, 5
defined, 5, 5
SQL syntax, 5, 5, 5
IS reserved word, 8

J

join conditions
+ operator, 6.1
JOIN reserved word, 8
join types
INNER, 6.1
LEFT, 6.1
RIGHT, 6.1
joined tables, 6.1
joins
joining table to itself, 6.1
outer, 6.1

L

LAST_VALUE function, 4.13
LEAST function, 4.13
LEFT reserved word, 8
LENGTH function, 4.13
LENGTH4 function, 4.13
LENGTHB function, 4.13
LIKE predicate, 5
defined, 5
in search conditions, 5
pattern matching, 5
pattern matching of NCHAR and NVARCHAR strings, 5
SQL syntax, 5
LIKE reserved word, 8
LOAD ANY CACHE GROUP system privilege
definition, 7.1
LOAD CACHE GROUP statement, 6.1
LOAD object privilege
definition, 7.2
LOB
conversion function, 4.13
function overview, 4.5
maximum size, 1.9
NULL, 1.9.4
overview, 1.9
local cache groups, 6.1
logical operators
in search conditions, 5
LONG reserved word, 8
lower case letters in names, 2.1
LOWER function, 4.13
LPAD function, 4.13
LTRIM function, 4.13

M

MASTER clause
in ALTER REPLICATION statement, 6.1
in CREATE ACTIVE STANDBY PAIR statement, 6.1
in CREATE REPLICATION statement, 6.1
materialized view log, 6.1
materialized views
invalid, 6.1
revoking privileges on detail table, 6.1
revoking privileges on the detail table, 6.1
MAX function, 4.13
maximum
items for DISTINCT option, 6.1
table cardinality, 6.1
tables per query, 6.1
MERGE statement, 6.1
MIN function, 4.13
MINUS, 8
MOD function, 4.13
MONTHS_BETWEEN function, 4.13
multiplying, 3
MVLOG$_ID
materialized view log, 6.1

N

names
basic names, 2.1, 2.1
compound identifiers, 2.3
dynamic parameters, 2.5, 2.5
fully qualified, 2.3
lower case letters, 2.1
owner names, 2.2
simple names, 2.3
used in TimesTen, 2
user ID, 2.2
namespace, 2.4
naming dynamic parameters, 2.5
naming rules, 2
NAN data type, 1.17
NATIONAL CHAR data type, 1.2
NATIONAL CHAR VARYING data type, 1.2
NATIONAL CHARACTER data type, 1.2, 1.2
NCHAR data type, 1.1, 1.5.2, 1.13, 1.21.1
defined, 5
example, 5
NCHAR VARYING data type, 1.2
NCHR function, 4.13
NCLOB
conversion function, 4.13
initialize, 4.13
overview, 1.1
NEXTVAL, 6.1, 6.1
NLS_CHARSET_ID function, 4.13
NLS_CHARSET_NAME function, 4.13
NLSSORT function, 4.13
NO RETURN clause
in CREATE REPLICATION statement, 6.1, 6.1
node
retrieve ID, 4.13
retrieve name, 4.13
NONDURABLE clause
in CREATE REPLICATION statement, 6.1
NOT INLINE clause, 6.1
in ALTER TABLE statement, 6.1
NOT NULL clause
in INSERT SELECT statement, 6.1
NULL predicate
in search conditions, 5
NULL reserved word, 8
NULL storage, 1.5.3, 1.13
NULL values
defined, 1.16
in comparison predicates, 5
in INSERT statement, 6.1
in search conditions, 5
in UPDATE statements, 6.1
sort order in CREATE INDEX, 6.1
sorting, 1.16
SQLBindCol ODBC function, 1.16
SQLBindParameter ODBC function, 1.16
NULLIF function, 4.13
NUMBER data type, 1.1, 1.6.1
TimesTen Mode, 1.21.2
number format models, 3
NUMERIC data type, 1.2
numeric data type truncation, 1.18
numeric data types, 1.6
numeric precedence, 1.8
NUMTODSINTERVAL function, 4.13
NUMTOYMINTERVAL function, 4.13
NVARCHAR2 data type, 1.1, 1.5.4, 1.13
defined, 5
example, 5
NVL function, 4.13

O

object
name
namespace, 2.4
search order, 2.4
object privilege, 7.2
ON reserved word, 8
operators
comparison, 5
in WHERE clause of SELECT statement, 6.1
ORA_CHAR data type, 1.21.2
ORA_DATE data type, 1.21.2
ORA_NCHAR data type, 1.21.2
ORA_NVARCHAR2 data type, 1.21.2
ORA_SYSDATE reserved word, 8
ORA_TIMESTAMP data type, 1.21.2
ORA_VARCHAR2 data type, 1.21.2
Oracle data types supported in TimesTen type mode, 1.21.2
ORDER BY clause
and subqueries, 3
in SELECT statement, 6.1
specifying result columns, 6.1
ORDER reserved word, 8
OUTER JOIN clause
specifying in SELECT statement, 6.1
outer joins
conditions, 6.1
indicators, 6.1
overflow
during type conversion, 1.18
in aggregate functions, 1.18
in arithmetic operations, 1.18
of data, 1.18
owner names, 2.2
owners of index, 6.1

P

package body
creating, 6.1
packages
CREATE PACKAGE BODY statement, 6.1
CREATE PACKAGE statement, 6.1
creating, 6.1
parameters
duplicate, 2.6
dynamic
naming rules, 2.5
inferring data type, 2.7
Partitions, 6.1
PORT clause
in CREATE ACTIVE STANDBY PAIR statement, 6.1
in CREATE REPLICATION statement, 6.1
POWER function, 4.13
predicates
ANY, 5
BETWEEN, 5
comparison, 5
compatible data types, 5
EXISTS, 5
IS NULL, 5, 5
LIKE, 5
null values, 5
order of evaluation, 5
primary
definition, 3
in expressions, 3
PRIMARY KEY clause
in CREATE TABLE statement, 6.1
PRIMARY reserved word, 8
privilege
object, 7.2
system, 7.1
privilege hierarchy, 7.3
privileges
overview, 7
procedures
creating, 6.1
PROPAGATE reserved word, 8
PROPAGATOR clause
in ALTER REPLICATION statement, 6.1
PUBLIC, 6.1
PUBLIC reserved word, 8
PUBLIC role
privileges, 7.4
PUBLIC user
in GRANT statement, 6.1

Q

quantified predicate
in search conditions, 5
queries
and aggregate functions, 6.1
results, 6.1
syntax, 6.1

R

RANK Function, 4.13
READONLY reserved word, 8
REAL data type, 1.2
REFERENCES object privilege
definition, 7.2
REFRESH ANY CACHE GROUP system privilege
definition, 7.1
REFRESH CACHE GROUP statement, 6.1
REFRESH MATERIALIZED VIEW statement, 6.1
REFRESH object privilege
definition, 7.2
REPLACE function, 4.13
replication, 6.1
ADD ELEMENT, 6.1
ADD SUBSCRIBER, 6.1
ALTER ELEMENT, 6.1
ALTER SUBSCRIBER, 6.1
altering, 6.1
CHECK CONFLICTS, 6.1, 6.1
conflict resolution, 6.1, 6.1
DATASTORE ELEMENT, 6.1
DROP ELEMENT, 6.1
ELEMENT, 6.1
FAILTHRESHOLD, 6.1, 6.1, 6.1
MASTER, 6.1, 6.1, 6.1, 6.1
NO RETURN, 6.1
PORT, 6.1, 6.1
PROPAGATOR, 6.1
restrictions, 6.1
RETURN RECEIPT, 6.1, 6.1, 6.1
SUBSCRIBER, 6.1, 6.1, 6.1, 6.1
TIMEOUT, 6.1, 6.1
TIMESTAMP, 6.1, 6.1
TRANSMIT, 6.1
replication element, 6.1
replication scheme, 6.1
reserved words, 8
restrictions, 6.1, 6.1, 6.1, 6.1
RETURN RECEIPT BY REQUEST clause
in CREATE REPLICATION statement, 6.1
RETURN RECEIPT clause
in ALTER REPLICATION statement, 6.1, 6.1
in CREATE REPLICATION statement, 6.1
RETURN TWOSAFE BY REQUEST clause
in ALTER REPLICATION statement, 6.1
RETURN TWOSAFE clause
in ALTER REPLICATION statement, 6.1
in CREATE REPLICATION statement, 6.1, 6.1
REVOKE, 6.1
REVOKE statement, 6.1
revoking privileges
materialized views, 6.1
RIGHT reserved word, 8
ROLLBACK statement, 6.1
ROLLUP clause
example, 6.1
GROUPING function, 4.10
GROUPING_ID function, 4.13
overview, 6.1, 6.1
syntax, 6.1
ROUND (date) function, 4.13
ROUND (expression) function, 4.13
ROW_NUMBER function, 4.13
rowid, 1.10, 3
ROWID data type, 1.1
description, 1.10
explicit conversion, 1.10
implicit conversion, 1.10
in expressions, 1.10
in INSERT SELECT statement, 1.10
ROWID pseudocolumn
in expressions, 3
ROWNUM pseudocolumn, 3
ROWNUM reserved word, 8
rows
inserting, 6.1
retrieving, 6.1
selecting, 6.1
ROWS reserved word, 8
RPAD function, 4.13
RTRIM function, 4.13

S

search condition
compatible predicates, 5
general syntax, 5
logical operators in, 5
SQL syntax, 5
type conversion, 5
value extensions, 5
SELECT
select list, 6.1
SELECT ANY SEQUENCE system privilege
definition, 7.1
SELECT ANY TABLE system privilege
definition, 7.1
select list
defined, 6.1
SQL syntax, 6.1
SELECT object privilege
definition, 7.2
SELECT reserved word, 8
SELECT statement, 6.1
GROUP BY clause, 6.1
GROUPING function, 4.13
HAVING clause, 6.1
maximum tables per query, 6.1
ORDER BY clause, 6.1
unique rows, 6.1
WHERE clause, 6.1
SELF reserved word, 8
sequence
create, 6.1
CURRVAL, 6.1
NEXTVAL, 6.1
number generator, 6.1
unique integer, 6.1
using, 6.1
values, 6.1
wrapping numbers, 6.1
session parameters
altering, 6.1
SESSION_USER function, 4.13
SESSION_USER reserved word, 8
SET clause
in ALTER ACTIVE STANDBY PAIR statement, 6.1
in ALTER CACHE GROUP statement, 6.1
in ALTER REPLICATION statement, 6.1
SET PAGES, 6.1
SET reserved word, 8
SIGN function, 4.13
simple names, 2.3
SMALLINT data type, 1.2, 1.21.1
SMALLINT reserved word, 8
SOME reserved word, 8
sorting of NULL values, 1.16
SOUNDEX function, 4.13
SQL naming rules, 2
SQL statements
ALTER REPLICATION, 6.1
ALTER SESSION, 6.1
ALTER TABLE, 6.1
CREATE CACHE GROUP, 6.1
CREATE FUNCTION, 6.1
CREATE INDEX, 6.1
CREATE MATERIALIZED VIEW, 6.1
CREATE PACKAGE, 6.1
CREATE PACKAGE BODY, 6.1
CREATE PROCEDURE, 6.1
CREATE SEQUENCE, 6.1
CREATE TABLE, 6.1
CREATE VIEW, 6.1
DELETE, 6.1
DROP CACHE GROUP, 6.1
DROP FUNCTION, 6.1
DROP PROCEDURE, 6.1
DROP REPLICATION, 6.1
DROP SEQUENCE, 6.1
DROP TABLE, 6.1
FLUSH CACHE GROUP, 6.1
INSERT, 6.1
INSERT SELECT, 6.1
LOAD CACHE GROUP, 6.1
SELECT, 6.1
UNLOAD CACHE GROUP, 6.1
UPDATE, 6.1
SQL syntax
CREATE PACKAGE, 6.1
CREATE PACKAGE BODY, 6.1
SQLBindCol ODBC function
and NULL values, 1.16
SQLBindParameter ODBC function
and NULL values, 1.16
SQRT function, 4.13
storage requirements, 1.13
strings
in constants, 3
truncated in UPDATE statement, 6.1
subqueries, 3
subquery
in EXISTS predicates, 5
SUBSCRIBER clause
in ALTER REPLICATION statement, 6.1
in CREATE REPLICATION statement, 6.1
SUBSTR function, 4.13
SUBSTR4 function, 4.13
SUBSTRB function, 4.13
subtraction operator
in expressions, 3
SUM function, 4.13
SYS_CONTEXT function, 4.13
SYSDATE, 8
SYSDATE function, 4.13
system managed cache group, 6.1, 6.1
system privilege, 7.1
system tables, 2.2
SYSTEM_USER function, 4.13
SYSTEM_USER reserved word, 8

T

table names
in ALTER TABLE statement, 6.1
in CREATE INDEX statement, 6.1
in CREATE TABLE statement, 6.1
in DROP INDEX statement, 6.1
in INSERT SELECT statement, 6.1
table owner
not specified, 6.1
tables
altering, 6.1
compression, 6.1
creating, 6.1
derived, 6.1
dropping, 6.1
inserting rows, 6.1
maximum cardinality, 6.1
maximum per query, 6.1
owner not specified, 6.1
specifying in SELECT statement, 6.1
unique constraints, 6.1
temporary table, 6.1, 6.1
object privilege, 6.1
TIME
ODBC-time-literal syntax, 3
values in constants, 3
TIME data type, 1.1, 1.11.2, 1.12.2, 1.12.2, 1.21.1
time literal
defined, 3
in constants, 3
time string
in constants, 3
TIMEOUT clause
in ALTER REPLICATION statement, 6.1
in CREATE REPLICATION, 6.1
TIMESTAMP
in CHECK CONFLICTS clause, 6.1
ODBC literal, 3
replication, 6.1, 6.1
values in constants, 3
timestamp
literal
defined, 3
in constants, 3
ODBC literal, 3
string
in constants, 3
TIMESTAMP data type, 1.1, 1.12.2, 1.13, 1.21.1
TIMESTAMPADD function, 4.13
SQL syntax, 4.13
TIMESTAMPDIFF function, 4.13
SQL syntax, 4.13
TimesTen data type mapping, 1.4
TimesTen interval, 1.12
TimesTen type mode, 1.21
TIMEZONE data type
conversions, 1.12.3
TINYINT data type, 1.21.1
TO reserved word, 8
TO_BLOB function, 4.13
TO_CHAR function, 4.13
SQL syntax, 4.13, 4.13, 4.13, 4.13
TO_CLOB function, 4.13
TO_DATE function, 4.13, 4.13
SQL syntax, 4.13
TO_LOB function, 4.13
TO_NCLOB function, 4.13
TO_NUMBER function, 4.13
TRANSMIT clause
replication, 6.1
TRANSMIT DURABLE/NONDURABLE clause
in CREATE REPLICATION statement, 6.1
TRIM function, 4.13
TRUNC (date), 4.13, 4.13
TRUNC (date) function, 4.13
TRUNC (expression) function, 4.13
TRUNCATE TABLE statement, 6.1
truncation
and numeric data, 1.18
data, 1.18
in character data, 1.18
TT_BIGINT data type, 1.6.2, 1.13
TT_CHAR data type, 1.3
TT_DATE data type, 1.1, 1.11.4, 1.13
TT_DECIMAL data type, 1.3, 1.13
TT_HASH function, 4.13
TT_INTEGER data type, 1.1, 1.6.3, 1.13, 1.21.1
TT_NCHAR data type, 1.3
TT_NVARCHAR data type, 1.3, 1.21.1
TT_SMALLINT data type, 1.6.4, 1.13
TT_SYSDATE reserved word, 8
TT_TIME data type, 1.13
TT_TIMESTAMP data type, 1.1, 1.13
TT_TINYINT data type, 1.6.5, 1.13
TT_VARCHAR data type, 1.3, 1.21.1
TTGRIDMEMBERID function, 4.13
TTGRIDNODENAME function, 4.13
TTGRIDUSERASSIGNEDNAME function, 4.13
ttRepSyncSet built-in procedure, 6.1
type conversion
and overflow, 1.18
type mode, 1.1
TypeMode connection attribute, 1.1

U

UID reserved word, 8
UID SQL function, 4.13
unary minus
in expressions, 3
unary plus
in expressions, 3
underflow
defined, 1.19
Unicode characters
escaped, 3
example, 5
pattern matching, 5
UNION reserved word, 8
unique constraints
on tables, 6.1
UNIQUE INDEX clause
defined, 6.1
UNIQUE reserved word, 8
unique rows, 6.1
UNISTR, 4.13
UNLOAD ANY CACHE GROUP system privilege
definition, 7.1
UNLOAD CACHE GROUP statement
defined, 6.1
UNLOAD object privilege
definition, 7.2
UPDATE ANY TABLE system privilege
definition, 7.1
UPDATE object privilege
definition, 7.2
UPDATE reserved word, 8
UPDATE SET clause
in MERGE statement, 6.1
UPDATE statement, 6.1
FIRST N clause, 6.1
string truncation, 6.1
WHERE clause omitted, 6.1
UPPER function, 4.13
USER function, 4.13
USER functions, 4.12
user ID in names, 2.2
user managed cache group, 6.1, 6.1
USER reserved word, 8
USING reserved word, 8
UTF-8 Unicode characters, 3

V

VARBINARY data type, 1.1, 1.7, 1.13, 1.21.1
VARCHAR data type, 1.1
VARCHAR reserved word, 8
VARCHAR2 data type, 1.1, 1.5.3, 1.13
variables in SQL statements, 2.5
views
CREATE MATERIALIZED VIEW statement, 6.1
CREATE VIEW statement, 6.1
restrictions on detail tables, 6.1
restrictions on queries, 6.1, 6.1
restrictions on views, 6.1

W

WHEN reserved word, 8
WHERE clause
in SELECT statement, 6.1
WHERE reserved word, 8
WITH reserved word, 8

X

XLA system privilege
definition, 7.1
PKhЭޜʜPK*AOEBPS/img/truthtable.gifYGIF87akUƀIII444ΌvvvjjjWWW111PPPTTTғ~~~ccc◗О쐐񽽽س+++䰰¿ ι>>>RRRͲǷrrruuuCCCxxxɤFFFllliiibbb[[[ttt...aaa```喖EEEgggZZZ===ӣ666HHH222___UUUXXX888JJJkkkeeeAAAddd {{{yyynnnqqqVVV333SSS^^^,,,<<<???OOOfffŶ|||###ooo'''zzz---mmmsss"""}}} DDD㈈www$$$999777]]])))hhh555;;;@@@::: !!!***%%%pppLLL///\\\(((MMMNNN KKKQQQ,kUH*\ȰÇ#JHŋ3jȱǏ CIɌdtˊ4.8f50Xx؃lBB),FxAp)] ` . T0Jط&pH۱`2ufBAրy"peZo$[ (?@,6ऒY>0 C[\@ՁM pfF0A(*Tpi%IX.XRlځ4&\Rj2LT.ah L4-Er@L)UN^a3FP!"E'IT"@4>P4')| ~` , dFD" 1 n`BigE A"I9 @"4)C%Z)Q3y@ P&HaEV~uaOqm$tNBHQJ,4D"2@<7"ĸ#I=s Q  dBL T`%IJ( Adhl* DEr!t1q! j씑A.PZHxeAH* ی@4G݊PGR <-I;alԂT,Z_E&F:tqTӈ UG*hB^t/fF~A s09 @D1FCc;t S $_Y*wlt``$@ ٜ/1! @K'|BPc1<F#aMR&@%#&2E6oyQ Jl@0QCrt2AzW͠8pxAH<1s-/Ғ*)ӞZą2!1G!Hlg!bD;1+pUhX2lMƺEPİA. ;W+}Z_.)tH1b kPHRJՌ4OV!2խz"W jVJehmHXp[ep ׾U`э&js@cjFLHe ZqIC%6pl֮XdQ ھ%u4.1f0C-[c/&P[f8c=o1N8@yv;jv "p^–v )p)@ծp6ep7N7p'kZ;k5Sބ/\U sن? UX!׈O|TX${Xk-pPS aKU.qK]J{QXjY "X& a%u>KR`fq(Rf!Wi!F,~pO HV3'=i{3>1*:`l<8>SB$r.PA;@!,w9D0Ax"9 4q;r==~J84 KiL<A(7M$NsS!MXwd- T*U߇5&QB 1 hQ]\(Fml8z㮖'mu+D bb>ZDTSΆ7~|܃!,R)U\pxcdPŗͶe0A'qwz@8nHH˙?Q7/9S JY]iC3CYqy̩L y>BCiBys_ɛjGʩT)'HK >sgcCP @ 1V >ї@ JT` |O)w$}aMGe]QPT1.~W-@ cPq2p X@jQUQA"<@S@Vꔬ98S8j7S;>T$$1wXvVr_z%#az |*~ zbacꕈ)V5:Zx 4Vjʆ ] ,YT7' 1 +Дi 0dPKEP XQZH9A$D I qĊ1 Q0,|0 PHiaFE1 Sdqjj\PD"*r ;`Eu0 @Y )*<@~=k'rB'vbT%B^"o2`{ˇB*G5> qQ:0gm۪ 6p97 Ir-bT`* nYwa/4{Tz{0 dC3`t)QtQiKkKno=(D; YvxvKU'PIGW3&4H`V<@5I*SAVp!xQZp{ I[P9> PZw!y%Uۀ裻!hU01T| DFKTH0{j: UM+A2rj4!KU8LL>o!KAkB 8ۼ{ xQ%@FeSbz. N+S?EzF| 𿏬Lb<ɕQȞ3P@ơ `ħU #;PK?^YPK*AOEBPS/img/tablecompress.gifGGIF89a @@@ࠠ000ߟ``` pppPPP???___///OOOooo!, @pH,Ȥrl:ШtJZجvzxL.zn|N-~yK JKGB !B  "{ !!!v" Ϙ !B"g FBD" !BC!U LЖ/,O>hl(TQ&9~$铛 P`hʄ,mpKq R!ԚDX ;3AB8'":U<󪮍*bBC66}xpm ]^KĚU"MāHi yWfҁlCJa C޵569@Х yK2!}rЅ[i{r>k:,P͗MfA^@48}р9V0mpFAYv8 sрh0ǩ3_Oh#% @@xLVKD8f`i ^G8,]h*Rii0Q5pi\8Ā.Y@S5i!&9L4I!40jQؠv!C5 @A*@&+v9ꮼRj챖稬2OVk-"t)u"&"1+kVݫ٥/+|o'ֿ qq1q ZlBii(,01l3q;[\-DmH' @+P?AQWmkq FU!-֯z^-6يhʶjwsp'"t[Mk7}#wW[?cq88#{wMxL,YJ19qvW҆ċ=|Sz~.G:};}~ Q;}ݛ62-D2w5`q|Og <&X]hӞ}ATHǾSj`"K`*BjD+; boe[+&68DzMx%)[Ր7v0D\8 OpŨ%Rb CPYf'&E Pt'A4$UPE7YaԈ>oWl ļб mcQCp4B. sHѐsɆ7bp$f~!no %p@,gIZƒQC&9{D $&,`MLJᕶ4oI]  Ȧ6nzS װǴ|0ҀHE '::̧>)XswM4JK\&vӠ@n -: aJ2Tde%6Hl'*'̃F]!A\q.*$ud1M<4;İ,\0ն܁.G:`IPj QNڜx0d. ΁#i쐾 = qDS: IđLg$6`;gt|_1&]+I=pL0M}YⳫGH,pr mSma \Ȇ.4-v6' *X[*ͷS-]Q෗|8lnyv5/R튬@{?uuI^=k0 ]X`ˍS ,1R _8E0:!ĝ"+@159w.FȦō;d bOJLR871z1?mI"c,pAO;F1eHI D9@C.'ȼgs`RZ:*uB_|gX?SV C w;zV(4&}G%4|=PH"L:*35!o|Y7{ >u]b'JF.n73HJ`1@c q3j9i 4@l1P5kxHjMs؏xc <}ǁ1'AF el4L,lfYh΄۪Ch_M F*2Y/pZ:~#![HϺL#u pw0mzN/|4{܇!?ѽUŠѶ}kj'} a@d(#K3,lKo{ՙLj PwQȒH7p>)SзFoh0d!hE-WCg S}wvx5yLiBy^6M ,Q`q3#g H \VQ jwHާo9%N'yeVeG"L*MXҁA<" N-}$\&L%_A>7@ 6d&D}H{eeB4B#U(PU=@!FzKwY+èmEebPtP^pّYgZ*!^@ʀ~9 UapP`[rZMhzZnђ5ǜ$2ٜj^^0[``*[5`zL@5Zư!|FhNL]EHDQ O݀;-mpV:磌 ^ @o :bPJg+;-;:XHP4 10'r%0ǡ"7>$$~KЮp`&^1+|w>)'RXӡ~jB?g$&8ʆEG8^r|" ppG#5! Ng08 }Z^05hZ^ EE"0U&Xf8qۺ}i' m 檛!r@ehD*·෨nV]RE`RX>;`D+V)$*|1xjhFyq[Yʔf ^A"۽9ʻW+a l_Wˬ o;$z" kܳ+~kk5gs+T*,, i ; i:<4LL PikM6ppƷje^d3'2`qƕ < i f yf &pZD| '^e`F֊*=  Ïkg;{tŗ|[bj٣8ʕnj!4VfI⊹JNOfnp:[\cGՂn'x]lp' Ecߖu2{\>~R6~Nώ'^ʍ^ӎüN.b>SFNɓ^~^Nδ.SW~^cN On~ ?}PKD&e^]oo#?AU>!o9;_MEOݾK=5A߭4G}?QCOUo'O)2RT] .=O\oz.J!rtv?pO탯䉏Ën_Oa6_ꛯߡ\?xa?OIO/ꪟu8tB聞??逿6OßmnM`o>5o "X4It>Z^Rv( a@ 63gH0]V^w$+ 1799=#?.IL?5OYB[!c`(kR9Wq{d} _G[ua1yYoO{;Ch{%aqOI멚 ܾO *8M\c![BP,~YD.JH5vl"ID&]ٰM6),=ܵD`ԟ dF:jUWJkW];t:lU LIvm) ĕ;n]wջo_]Qۣ &!G,ɓ7ּ˟A}gӧQVukׯaǖ=vm۷qֽwo߿(-@qBaxq  |ɂ ΛAxD'U](;żԡ1q۶̓RN!S3<:Pf @EA^4`X!F0$ @f X(1a P# aŒ&- 0[ސY/La&– d1y)%l PL3gb;xhpf9;- 5OqS{0OHc>Y 8<`#Q> z&[yi] Ty :AH~"\HJM)㤧T6d01txBz 9b,%? >0j4c$]RAR"bSYrSOq|2,)2ÐXM)u[Yu!q:!pgv넋[5,1ǰAp$>a#^b vwdxX Z;MD^XqvZK5ó\KY"p^=‡zl+g%j+4Di خAxgPva +*W:srhTI dvIot][+ AYpONX mg zAHֲBZasv13*|5RX٘=;PKLGPK*AOEBPS/express.htm Expressions

3 Expressions

Expressions are used for the following purposes:

  • The select list of the INSERT...SELECT statement

  • A condition of the WHERE clause and the HAVING clause

  • The GROUP BY and ORDER BY clauses

  • The VALUES clause of the INSERT and MERGE statements

  • The SET clause of the UPDATE and MERGE statements

The following sections describe expressions in TimesTen:


Expression specification

An expression specifies a value to be used in a SQL operation.

An expression can consist of a primary or several primaries connected by arithmetic operators, comparison operators, string or binary operators, bit operators or any of the functions described in this chapter. A primary is a signed or unsigned value derived from one of the items listed in the SQL syntax.

SQL syntax

{ColumnName | ROWID | {? | :DynamicParameter} |
  Function | Constant | (Expression)}

or

[[+ |-] {ColumnName | SYSDATE | TT_SYSDATE|GETDATE() |
{? | :DynamicParameter} | Function |
Constant | {~ | + | -} Expression}]
 [...]

or

Expression1 [& | | | ^ | + | / | * | - ] Expression2

or

Expression1 | | Expression2

or

Expression
ComponentDescription
+, –Unary plus and unary minus. Unary minus changes the sign of the primary. The default is to leave the sign unchanged.
ColumnNameName of a column from which a value is to be taken. Column names are discussed in Chapter 2, "Names, Namespace and Parameters."
ROWIDTimesTen assigns a unique ID called a rowid to each row stored in a table. The rowid value can be retrieved through the ROWID pseudocolumn.
?

:DynamicParameter

A placeholder for a dynamic parameter.

The value of the dynamic parameter is supplied at runtime.

FunctionA computed value. See Chapter 4, "Functions".
ConstantA specific value. See "Constants".
(Expression)Any expression enclosed in parentheses.
Expression1

Expression2

Expression1 and Expression2, when used with the bitwise operators, can be of integer or binary types. The data types of the expressions must be compatible. See Chapter 1, "Data Types."
*Multiplies two primaries.
/Divides two primaries.
+Adds two primaries.
Subtracts two primaries.
&Bitwise AND of the two operands. Sets a bit to 1 if and only if both of the corresponding bits in Expression1 and Expression2 are 1. Sets a bit to 0 if the bits differ or both are 0.
|Bitwise OR of the two operands. Sets a bit to 1 if one or both of the corresponding bits in Expression1 and Expression2 are 1. Sets a bit to 0 if both of the corresponding bits are 0.
~Bitwise NOT of the operand. Takes only one Expression and inverts each bit in the operand, changing all the ones to zeros and zeros to ones.
^Exclusive OR of the two operands. Sets the bit to 1 where the corresponding bits in its Expression1 and Expression2 are different and to 0 if they are the same. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
||Concatenates Expression1 and Expression2, where both expressions are character strings. Forms a new string value that contains the values of both expressions. See also "CONCAT".

Description

  • Arithmetic operators can be used between numeric values. See "Numeric data types".

  • Arithmetic operators can also be used between datetime values and interval types. The result of a datetime expression is either a datetime data type or an interval data type.

  • Arithmetic operators cannot be applied to string values.

  • Elements in an expression are evaluated in the following order:

    • Functions and expressions in parentheses

    • Unary pluses and minuses

    • The * and / operations

    • The + and operations

    • Elements of equal precedence are evaluated in left-to-right order

  • You can enclose expressions in parentheses to control the order of their evaluation. For example:

    10 * 2 – 1 = 19 but 10 * (2 – 1) = 10
    
  • Type conversion, truncation, underflow, or overflow can occur when some expressions are evaluated. See Chapter 1, "Data Types".

  • If either operand in a numeric expression is NULL, the result is NULL.

  • Since NVL takes two parameters, both designated as an "expression", TimesTen does not permit NULL in either position. If there is a NULL value in an expression, comparison operators and other predicates evaluate to NULL. See Chapter 5, "Search Conditions" for more information on evaluation of comparison operators and predicates containing NULL values. TimesTen permits inserting NULL, but in general INSERT takes only specific values, and not general expressions.

  • The query optimizer and execution engine permit multiple rowid lookups when a predicate specifies a disjunct of rowid equalities or uses IN. For example, multiple fast rowid lookups are executed for:

    WHERE ROWID = :v1 OR ROWID = :v2
    
  • or equivalently:

    WHERE ROWID IN (:v1, :v2)
    
  • The ? or :DynamicParameter can be used as a dynamic parameter in an expression.

Examples

This example shows a dynamic parameter in the WHERE clause of any SELECT statement:

SELECT * FROM purchasing.orders
  WHERE partnumber = ? AND ordernumber > ?
  ORDER BY ordernumber;

This example shows a dynamic parameter in the WHERE and SET clauses of an UPDATE statement:

UPDATE purchasing.parts
  SET salesprice = :dynamicparameter1
  WHERE partnumber = :dynamicparameter2;

This example shows a dynamic parameter in the WHERE clause of a DELETE statement:

DELETE FROM purchasing.orderitems
  WHERE itemnumber BETWEEN ? AND ?;

This example shows a dynamic parameter in the VALUES clause of an INSERT statement. In this example, both ? and :dynamicparameter are used where :dynamicparameter1 corresponds to both the second and fourth columns of the purchasing.orderitems table. Therefore, only four distinct dynamic parameters need to be passed to this expression with the second parameter used for both the second and fourth columns.

INSERT INTO purchasing.orderitems VALUES  
   (?,:dynamicparameter1,
      :dynamicparameter2,
      :dynamicparameter1,?);

This example demonstrates that both ? and :dynamicparameter can be used in the same SQL statement and shows the semantic difference between repeating both types of dynamic parameters.

Examples of bitwise operators:

Command> SELECT 0x183D & 0x00FF FROM dual;
< 003D >
1 row found.
Command> SELECT ~255 FROM dual;
< -256 >
1 row found.
Command> SELECT 0x08 | 0x0F FROM dual;
< 0F >
1 row found.

Subqueries

TimesTen supports subqueries in INSERT...SELECT, CREATE VIEW or UPDATE statements and in the SET clause of an UPDATE statement, in a search condition and as a derived table. TimesTen supports table subqueries and scalar subqueries. It does not support row subqueries. A subquery can specify an aggregate with a HAVING clause or joined table. It can also be correlated.

SQL syntax

[NOT] EXISTS | [NOT] IN (Subquery)
Expression {= | <> | > | >= | < | <= } [ANY | ALL] (Subquery)
Expression [NOT] IN (ValueList | Subquery)

Description

TimesTen supports queries with the characteristics listed in each section.

Table subqueries

  • A subquery can appear in the WHERE clause or HAVING clause of any statement except one that creates a materialized view. Only one table subquery can be specified in a predicate. These predicates can be specified in a WHERE or HAVING clause, an OR expression within a WHERE or HAVING clause, or an ON clause of a joined table. They cannot be specified in a CASE expression, a materialized view, or a HAVING clause that uses the + operator for outer joins.

  • A subquery can be specified in an EXISTS or NOT EXISTS predicate, a quantified predicate with ANY or ALL, or a comparison predicate. The allowed operators for both comparison and quantified predicates are: =, <, >, <=, >=, <>. The subquery cannot be connected to the outer query through a UNIQUE or NOT UNIQUE operator.

  • Only one subquery can be specified in a quantified or comparison predicate. Specify the subquery as either the right operand or the left operand of the predicate, but not both.

  • The subquery should not have an ORDER BY clause.

  • FIRST NumRows is not supported in subquery statements.

  • In a query specified in a quantified or comparison predicate, the underlying SELECT must have a single expression in the select list. In a query specified in a comparison predicate, if the underlying select returns a single row, the return value is the select result. If the underlying select returns no row, the return value is NULL. It is an error if the subquery returns multiple rows.

Scalar subqueries

A scalar subquery returns a single value.

  • A nonverifiable scalar subquery has a predicate such that the optimizer cannot detect at compile time that the subquery returns at most one row for each row of the outer query. The subquery cannot be specified in an OR expression.

  • Neither outer query nor any scalar subquery should have a DISTINCT modifier.

Examples

Examples of supported subqueries for a list of customers having at least one unshipped order:

SELECT customers.name FROM customers
  WHERE EXISTS (SELECT 1 FROM orders
    WHERE customers.id = orders.custid
    AND orders.status = 'unshipped');

SELECT customers.name FROM customers
  WHERE customers.id = ANY 
    (SELECT orders.custid FROM orders
  WHERE orders.status = 'unshipped');

SELECT customers.name FROM customers 
  WHERE customers.id IN 
    (SELECT orders.custid FROM orders 
  WHERE orders.status = 'unshipped');

In this example, list items are shipped on the same date as when they are ordered:

SELECT line_items.id FROM line_items 
  WHERE line_items.ship_date = 
    (SELECT orders.order_date FROM orders 
  WHERE orders.id = line_items.order_id);

Constants

A constant is a literal value.

SQL syntax

{IntegerValue | FloatValue |FloatingPointLiteral|
    FixedPointValue | 'CharacterString'|
    'NationalCharacterString' | HexadecimalLiteral |
    'DateString' | DateLiteral |'TimeString' | 
    TimeLiteral | 'TimestampString' | TimestampLiteral |
    IntervalLiteral | BINARY_FLOAT_INFINITY |
    BINARY_DOUBLE_INFINITY | -BINARY_FLOAT_INFINITY |
    -BINARY_DOUBLE_INFINITY | BINARY_FLOAT_NAN |
     BINARY_DOUBLE_NAN
}
ConstantDescription
IntegerValueA whole number compatible with TT_INTEGER, TT_BIGINT or TT_SMALLINT data types or an unsigned whole number compatible with the TT_TINYINT data type. For example:

155, 5, -17

FloatValueA floating-point number compatible with the BINARY_FLOAT or BINARY_DOUBLE data types. Examples:

.2E-4, 1.23e -4, 27.03, -13.1

FloatingPointLiteralFloating point literals are compatible with the BINARY_FLOAT and BINARY_DOUBLE data types. f or F indicates that the number is a 32-bit floating point number (of type BINARY_FLOAT). d or D indicates that the number is a 64-bit floating point number (of type BINARY_DOUBLE).

For example: 123.23F, 0.5d

FixedPointValueA fixed-point number compatible with the BINARY_FLOAT, BINARY_DOUBLE or NUMBER data types. For example:

27.03

CharacterStringA character string compatible with CHAR or VARCHAR2 data types. String constants are delimited by single quotation marks. For example:

'DON''T JUMP!'

Two single quotation marks in a row are interpreted as a single quotation mark, not as string delimiters or the empty string.

NationalCharacterStringA character string compatible with NCHAR or NVARCHAR2 data types. National string constants are preceded by an indicator consisting of either N or n, and delimited by single quotation marks. For example:
N'Here''s how!'

Two single quotation marks in a row are interpreted as a single quotation mark.

The contents of a national string constant may consist of any combination of:

  • ASCII characters

  • UTF-8 encoded Unicode characters

  • Escaped Unicode characters

ASCII characters and UTF-8 encoded characters are converted internally to their corresponding UTF-16 format Unicode equivalents.

Escaped Unicode characters are of the form \uxxxx, where xxxx is the four hex-digit representation of the Unicode character. For example:

N'This is an \u0061'

is equivalent to:

N'This is an a'

The \u itself can be escaped with another \. The sequence \\u is always converted to \u. No other escapes are recognized.

HexadecimalLiteralHexadecimal literals containing digits 0 - 9 and A - F (or a - f) are compatible with the BINARY, VARBINARY, CHAR, VARCHAR2 and BLOB data types. A HexadecimalLiteral constant should be prefixed with the characters "0x." For example:
0xFFFAB0880088343330FFAA7

or

0x000A001231

Hexadecimal digits provided with an odd length are pre-fixed with a zero to make it even. For example, the value 0x123 is converted to 0x0123.

If you provide a character literal, the binary values of the characters are used. For example, the following demonstrates what is stored when inserting a hexadecimal literal and a character literal in a VARBINARY column colbin in table tabvb:

Command> insert into tabvb values (0x1234);
1 row inserted.
Command> insert into tabvb values ('1234');
1 row inserted.
Command> select colbin from tabvb;
< 1234 >
< 31323334 >
2 rows found.

However, Oracle differs in that it only accepts character literals, such as '1234', and translates the character literal as a binary literal of 0x1234. As a result, insert into tabvb values ('1234'); behaves differently between Oracle and TimesTen. Oracle does not accept 0x1234 as a hexadecimal literal.

DateStringA string of the format YYYY-MM-DD HH:MI:SS enclosed in single quotation marks ('). For example:
'2007-01-27 12:00:00'

The YYYY field must have a 4-digit value. The MM and DD fields must have 2-digit values. The only spaces allowed are trailing spaces (after the day field). The range is from '-4713-01-01' (January 1, 4712 BC) to '9999-12-31', (December 31, 9999). The time component is not required. For example:

'2007-01-27'

For TT_DATE data types, the string is of format YYYY-MM-DD and ranges from '1753-01-01' to '9999-12-31'.

If you are using TimesTen type mode, see Oracle TimesTen In-Memory Database Release 6.0.3 documentation for information about DateString.

DateLiteralFormat: DATE DateString. For example:
DATE '2007-01-27' or DATE '2007-01-27 12:00:00'

For TT_DATE data types, use the literal TT_DATE. For example:

TT_DATE '2007-01-27'. 

Do not specify a time portion with the TT_DATE literal.

The DATE keyword is case-insensitive.

TimesTen also supports ODBC date-literal syntax.

For example:

{d '2007-01-27'}. 

See ODBC documentation for details.

If you are using TimesTen type mode, see Oracle TimesTen In-Memory Database Release 6.0.3 documentation for information about DateLiteral</code>.

TimeStringA string of the format HH:MM:SS enclosed in single quotation marks ('). For example:
'20:25:30'

The range is '00:00:00' to '23:59:59', inclusive. Every component must be two digits. The only spaces allowed are trailing spaces (after the seconds field).

TimeLiteralFormat: TIME TimeString. For example:
TIME '20:25:30'

The TIME keyword is case-insensitive.

Usage examples:

INSERT INTO timetable VALUES (TIME '10:00:00');

SELECT * FROM timetable WHERE col1 < TIME '10:00:00';

TimesTen also supports ODBC time-literal syntax.

For example:

{t '12:00:00'}
TimestampStringA string of the format YYYY-MM-DD HH:MI:SS [.FFFFFFFFF] -enclosed in single quotation marks('). The range is from '-4713-01-01' (January 1, 4712 BC) to '9999-12-31' (December 31, 9999). The year field must be a 4-digit value. All other fields except for the fractional part must be 2-digit values. The fractional field can consist of 0 to 9 digits. For TT_TIMESTAMP data types, a string of format YYYY-MM-DD HH:MM:SS[.FFFFFF] enclosed in single quotation marks('). The range is from '1753-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999'. The fractional field can consist of 0 to 6 digits.

If you have a CHAR column called C1, and want to enforce the TIME comparison, you can do the following:

SELECT * FROM testable WHERE C1 = TIME '12:00:00'

In this example, each CHAR value from C1 is converted into a TIME value before comparison, provided that values in C1 conform to the proper TIME syntax.

If you are using TimesTen type mode, see Oracle TimesTen In-Memory Database Release 6.0.3 documentation for information on TimestampString.

TimestampLiteralFormat: TIMESTAMP TimestampString

For example:

TIMESTAMP '2007-01-27 11:00:00.000000'

For TIMESTAMP data types, the fraction field supports from 0 to 9 digits of fractional seconds. For TT_TIMESTAMP data types, the fraction field supports from 0 to 6 digits of fractional seconds.

The TIMESTAMP keyword is case-insensitive.

Literal syntax can be used if you want to enforce DATE/TIME/TIMESTAMP comparisons for CHAR and VARCHAR2 data types.

TimesTen also supports ODBC timestamp literal syntax. For example:

{ts '9999-12-31 12:00:00'}

If you are using TimesTen type mode, see Oracle TimesTen In-Memory Database Release 6.0.3 documentation for information about TimestampLiteral.

IntervalLiteralFormat: INTERVAL [+\-] CharacterString IntervalQualifier.

For example INTERVAL '8' DAY

BINARY_FLOAT_INFINITY|

BINARY_DOUBLE_INFINITY

INF (positive infinity) is an IEEE floating-point value that is compatible with the BINARY_FLOAT and BINARY_DOUBLE data types. Use the constant values BINARY_FLOAT_INFINITY or BINARY_DOUBLE_INFINITY to represent positive infinity.
-BINARY_FLOAT_INFINITY|

-BINARY_DOUBLE_INFINITY

-INF (negative infinity) is an IEEE floating-point value that is compatible with the BINARY_FLOAT and BINARY_DOUBLE data types. Use the constant values -BINARY_FLOAT_INFINITY and -BINARY_DOUBLE_INFINITY to represent negative infinity.
BINARY_FLOAT_NAN|

BINARY_DOUBLE_NAN

NaN ("not a number") is an IEEE floating-point value that is compatible with the BINARY_FLOAT and BINARY_DOUBLE data types. Use the constant values BINARY_FLOAT_NAN or BINARY_DOUBLE_NAN to represent NaN ("not a number").


Format models

A format model is a character literal that describes the format of datetime and numeric data stored in a character string. When you convert a character string into a date or number, a format model determines how TimesTen interprets the string.

This section covers the following format models:


Number format models

Use number format models in the following functions:

  • In the TO_CHAR function to translate a value of NUMBER, BINARY_FLOAT, or BINARY_DOUBLE data type to VARCHAR2 data type.

  • In the TO_NUMBER function to translate a value of CHAR or VARCHAR2 data type to NUMBER data type.

The default american_america NLS language and territory setting is used.

A number format model is composed of one or more number format elements. The table lists the elements of a number format model. Negative return values automatically contain a leading negative sign and positive values automatically contain a leading space unless the format model contains the MI, S, or PR format element.

Table 3-1 Number format elements

ElementExampleDescription

, (comma)

9,999

Returns a comma in the specified position. You can specify multiple commas in a number format model.

Restrictions:

  • A comma element cannot begin a number format model.

  • A comma cannot appear to the right of the decimal character or period in a number format model.

. (period)

99.99

Returns a decimal point, which is a period (.) in the specified position.

Restriction:

You can specify only one period in a format model.

$


$9999

Returns value with leading dollar sign.

0

0999

9990

Returns leading zeros.

Returns trailing zeros.

9

9999

Returns value with the specified number of digits with a leading space if positive or with a leading minus if negative.

Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the fixed-point number.

B

B9999

Returns blanks for the integer part of a fixed-point number when the integer part is zero (regardless of zeros in the format model).

C

C999

Returns in the specified position the ISO currency symbol.

D

99D99

Returns the decimal character in the specified position. The default is a period (.).

Restriction:

You can specify only one decimal character in a number format model.

EEEE

9.9EEEE

Returns a value in scientific notation.

G

9G999

Returns the group separator in the specified position. You can specify multiple group separators in a number format model.

Restriction:

A group separator cannot appear to the right of a decimal character or period in a number format model.

L

L999

Returns the local currency symbol in the specified position.

MI

999MI

Returns negative value with a trailing minus sign (-).

Returns positive value with a trailing blank.

Restriction:

The MI format element can appear only in the last position of a number format model.

PR

999PR

Returns negative value in angle brackets (< >).

Returns positive value with a leading and trailing blank.

Restriction:

The PR format element can appear only in the last position of a number format model.

RN

RN

Returns a value as Roman numerals in uppercase.

rn

rn

Returns a value as Roman numerals in lowercase.

Value can be an integer between 1 and 3999.

S

S9999

Returns negative value with a leading minus sign (-).

Returns positive value with a leading plus sign (+).

S

9999S

Returns negative value with a trailing minus sign (-).

Returns positive value with a trailing plus sign (+).

Restriction:

The S format element can appear only in the first or last position of a number format model.

TM

TM

The text minimum number format model returns (in decimal output) the smallest number of characters possible. This element is case insensitive.

The default is TM9, which returns the number in fixed notation unless the output exceeds 64 characters. If the output exceeds 64 characters, then TimesTen automatically returns the number in scientific notation.

Restrictions:

  • You cannot precede this element with any other element.

  • You can follow this element only with one 9 or one E or (e), but not with any combination of these. The following statement returns an error:

    SELECT TO_NUMBER (1234, 'TM9e') FROM dual;

U

U9999

Returns the euro or other dual currency symbol in the specified position.

V

999V99

Returns a value multiplied by 10n (and if necessary, rounds it up), where n is the number of 9s after the V.

X

XXXX

Returns the hexadecimal value of the specified number of digits. If the specified number is not an integer, then TimesTen rounds it to an integer.

Restrictions:

  • This element accepts only positive values or 0. Negative values return an error.

  • You can precede this element only with 0 (which returns leading zeros) or FM. Any other elements return an error. If you specify neither 0 nor FM with X, then the return always has a leading blank.



Datetime format models

Use datetime format models in the following functions:

  • In the TO_CHAR or TO_DATE functions to translate a character value that is in a format other than the default format for a datetime value.

  • In the TO_CHAR function to translate a datetime value that is in a format other than the default format into a string.

The total length of a datetime format model cannot exceed 22 characters.

The default american_america NLS language and territory setting is used.

A datetime format model is composed of one or more datetime format elements, which are shown in Table 3-2.

Table 3-2 Datetime format elements

ElementDescription

-/,.;:"text"

Punctuation and quoted text is reproduced in the result.

AD

A.D.

AD indicator with or without periods.

AM

A.M.

Meridian indicator with or without periods.

BC

B.C.

BC indicator with or without periods.

D

Day of week (1-7).

DAY

Name of day, padded with blanks to display width of widest name of day.

DD

Day of month (1-31).

DDD

Day of year.

DL

Returns a value in the long date format. In the default AMERICAN_AMERICA locale, this is equivalent to specifying the format 'fmDay, Month dd, yyyy'.

Restriction:

Specify this format only with the TS element, separated by white space.

DS

Returns a value in the short date format. In the default AMERICAN_AMERICA locale, this is equivalent to specifying the format 'MM/DD/RRRR'.

Restriction:

Specify this format only with the TS element, separated by white space.

DY

Abbreviated name of day.

FM

Returns a value with no leading or trailing blanks.

FX

Requires exact matching between the character data and the format model.

HH

Hour of day (1-12).

HH24

Hour of day (0-23).

J

Julian day: The number of days since January 1, 4712 BC. Numbers specified with J must be integers.

MI

Minute (0-59).

MM

Month (01-12. January = 01).

MON

Abbreviated name of month.

MONTH

Name of month padded with blanks to display width of the widest name of month.

RM

Roman numeral month (I-XII. January = I).

RR

Stores 20th century dates in the 21st century using only two digits.

RRRR

Rounds year. Accepts either 4-digit or 2-digit input. If 2-digit, provides the same return as RR. If you do not want this functionality, then enter the 4-digit year.

SS

Second (0-59).

SSSSS

Seconds past midnight (0-86399).

TS

Returns a value in the short time format.

Restriction:

Specify this format only with the DL or DS element, separated by white space.

X

Local radix character.

Example: 'HH:MI:SSXFF'.

Y,YYY

Year with comma in this position.

YYYY

SYYYY

4-digit year. S prefixes BC dates with a minus sign.

YYY

YY

Y

Last 3, 2, or 1 digit (s) of year.



Format model for ROUND and TRUNC date functions

The table lists the format models you can use with the ROUND and TRUNC date functions and the units to which they round and truncate dates. The default model DD returns the date rounded or truncated to the day with a time of midnight.

Format modelRounding or truncating unit
CC

SCC

Century: If the last 2 digits of a 4-digit year are between 01 and 99 (inclusive), then the century is one greater than the first 2 digits of that year.

If the last 2 digits of a 4-digit year are 00, then the century is the same as the first 2 digits of that year.

For example, 2002 returns 21; 2000 returns 20.

SYYYY

YYYY

YEAR

SYEAR

YYY

YY

Y

Year. All year output rounds up on "MݲJuly 1
IYYY

IYY

IY

I

ISO year
QQuarter (rounds up on the sixteenth day of the second month of the quarter)
MONTH

MON

MM

RM

Name of month (rounds up on the sixteenth day)
WWSame day of the week as the first day of the year
IWSame day of the week as the first day of the ISO week, which is Monday
WSame day of the week as the first day of the month
DDD

DD

J

Day of year
DAY

DY

D

Starting day of the week
HH

HH12

HH24

Hour
MIMinute


Format model for TO_CHAR of TimesTen datetime data types

Use this format model when invoking the TO_CHAR function to convert a datetime value of TT_TIMESTAMP or TT_DATE. In addition, use this format model when invoking the TO_CHAR function to convert any numeric value other than NUMBER or ORA_FLOAT.

  • If a numeric value does not fit in the specified format, TimesTen truncates the value.

  • The format string cannot exceed 50 characters.

  • D always results in a decimal point. Its value cannot be changed with an NLS parameter.

  • If a float with an absolute value less than 1e-126 or greater than 1e126 is specified as input to the TO_CHAR function, TimesTen returns an error.

FormatDescription
DDDay of month (1-31)
MMMonth (1-12)
MONMonth (three character prefix)
MONTHMonth (full name blank-padded to 9 characters)
YYYYYear (four digits)
Y,YYYYear (with comma as shown)
YYYYear (last three digits)
YYYear (last two digits)
YYear (last digit)
QQuarter
HHHour (1-12)
HH12Hour (1-12)
HH24Hour (0-23)
MIMinute (0-59)
SSSecond (0-59)
FFFractions of a second to a precision of 6 digits
FFnFractions of a second to the precision specified by n
AMMeridian indicator
A.M.Meridian indicator
PMMeridian indicator
P.M.Meridian indicator
- /  ,  . ; :Punctuation to be output
"text"Text to be output
9Digit
0Leading or trailing zero
.Decimal point
,Comma
EEEEScientific notation
SSign mode
BBlank mode. If there are no digits, the string is filled with blanks.
FMNo-blank mode (fill mode). If this element is used, trailing and leading spaces are suppressed.
$
Leading dollar sign.


CASE expressions

Specifies a conditional value. Both simple and searched case expressions are supported. The CASE expression can be specified anywhere an expression can be specified and can be used as often as needed.

Instead of using a series of IF statements, the CASE expression enables you to use a series of conditions that return the appropriate values when the conditions are met. With CASE, you can simplify queries and write more efficient code.

SQL syntax

The syntax for a searched CASE expression is:

CASE
  {WHEN SearchCondition THEN Expression1}[…] 
   [ELSE Expression2]
END

The syntax for a simple CASE expression is:

CASE Expression 
  {WHEN CompExpression THEN Expression1}[…]
   [ELSE Expression2] 
END

Parameters

CASE has the parameters:

ParameterDescription
WHEN SearchConditionSpecifies the search criteria. This clause cannot specify a subquery.
WHEN CompExpressionSpecifies the operand to be compared.
ExpressionSpecifies the first operand to be compared with each CompExpression.
THEN Expression1Specifies the resulting expression.
ELSE Expression2If condition is not met, specifies the resulting expression. If no ELSE clause is specified, TimesTen adds an ELSE NULL clause to the expression.

Description

You cannot specify the CASE expression in the value clause of an INSERT statement.

Examples

To specify a searched CASE statement that specifies the value of a color, use:

SELECT CASE 
  WHEN color=1 THEN 'red' 
  WHEN color=2 THEN 'blue' 
  ELSE 'yellow' 
END FROM cars;

To specify a simple CASE statement that specifies the value of a color, use:

SELECT CASE color 
  WHEN 1 THEN 'red' 
  WHEN 2 THEN 'blue' 
  ELSE 'yellow' 
END FROM cars;

ROWID

TimesTen assigns a unique ID called a rowid to each row stored in a table. The rowid has data type ROWID. You can examine a rowid by querying the ROWID pseudocolumn.

Because the ROWID pseudocolumn is not a real column, it does not require database space and cannot be updated, indexed or dropped.

The rowid value persists throughout the life of the table row, but the system can reassign the rowid to a different row after the original row is deleted. Zero is not a valid value for a rowid.

Rowids persists through recovery, backup and restore operations. They do not persist through replication, ttMigrate or ttBulkCp operations.

See "Expression specification" for more information on rowids. See "ROWID data type" for more information about the ROWID data type.


ROWNUM psuedocolumn

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which the row was selected. The first row selected has a ROWNUM of 1, the second a ROWNUM of 2, and so on.

Use ROWNUM to limit the number of rows returned by a query as in this example:

SELECT * FROM employees WHERE ROWNUM < 10;

The order in which rows are selected depends on the index used and the join order. If you specify an ORDER BY clause, ROWNUM is assigned before sorting. However, the presence of the ORDER BY clause may change the index used and the join order. If the order of selected rows changes, the ROWNUM value associated with each selected row could also change.

For example, the following query may return a different set of employees than the preceding query if a different index is used:

SELECT * FROM employees WHERE ROWNUM < 10 ORDER BY last_name;

Conditions testing for ROWNUM values greater than a positive integer are always false. For example, the following query returns no rows:

SELECT * FROM employees WHERE ROWNUM > 1;

Use ROWNUM to assign unique values to each row of a table. For example:

UPDATE my_table SET column1 = ROWNUM;

If your query contains either FIRST NumRows or ROWS m TO n, do not use ROWNUM to restrict the number of rows returned. For example, the following query results in an error message:

SELECT FIRST 2 * FROM employees WHERE ROWNUM <1 ORDER BY employee_id;
2974: Using rownum to restrict number of rows returned cannot be combined with 
first N or rows M to N
PKe1M"MPK*AOEBPS/img_text/truthtable.htm^ Description of the illustration truthtable.gif

This is a description of truthtable.gif. It shows tables for AND, OR, and NOT.

The AND table has the following column headings: AND, T, F, ?. The AND column contains the following row headings: T, F, ?. The table contains the following three rows:


T F ?
F F F
? F ?

The OR table has the following column headings: OR, T, F, ?. The OR column contains the following row headings: T, F, ?. The table contains the following three rows:


T T T
T F ?
T ? ?

The NOT table has two columns. The heading of the first column is NOT. The second column has no heading. The NOT column contains the following row headings: T, F, ?. The untitled column contains the following values: F, T, ?.

End of description.

PKrѦPK*A OEBPS/img_text/tablecompress.htmB Description of the illustration tablecompress.gif

This graphic shows a compressed column group of STATE compressed into a dictionary table that has the full name of the state and the number of occurrences for the entry.

PKaGBPK*AOEBPS/reserved.htm4 Reserved Words

8 Reserved Words

TimesTen reserves words for use in SQL statements.

To use one of these words as an identifier (such as a table name or column name), enclose the reserved word in quotes. Otherwise, syntax errors may occur.

Reserved words
AGING
ALL
ANY
AS
BETWEEN
BINARY_DOUBLE_INFINITY
BINARY_DOUBLE_NAN
BINARY_FLOAT_INFINITY
BINARY_FLOAT_NAN
CASE
CHAR
COLUMN
CONNECTION
CONSTRAINT
CROSS
CURRENT_SCHEMA
CURRENT_USER
CURSOR
DATASTORE_OWNER
DATE
DECIMAL
DEFAULT
DESTROY
DISTINCT
FIRST
FLOAT
FOR
FOREIGN
FROM
GROUP
HAVING
INNER
INTEGER
INTERSECT
INTERVAL
INTO
IS
JOIN
LEFT
LIKE
LONG
MINUS
NULL
ON
ORA_SYSDATE
ORDER
PRIMARY
PROPAGATE
PUBLIC
READONLY
RIGHT
ROWNUM
ROWS
SELECT
SELF
SESSION_USER
SET
SMALLINT
SOME
SYSDATE
SYSTEM_USER
TO
TT_SYSDATE
UID
UNION
UNIQUE
UPDATE
USER
USING
VARCHAR
WHEN
WHERE
WITH

PK 44PK*A OEBPS/toc.ncx  Oracle® TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2) Cover Table of Contents Oracle TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2) Preface What's New Data Types Names, Namespace and Parameters Expressions Functions Search Conditions SQL Statements Privileges Reserved Words Index Copyright PKk PK*AOEBPS/content.opf> Oracle® TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2) en-US E21642-04 Oracle Corporation Oracle Corporation Oracle® TimesTen In-Memory Database SQL Reference, 11g Release 2 (11.2.2) 2012-09-19T19:40:10Z Provides a reference for SQL statements, expressions, and functions used with the Oracle TimesTen In-Memory Database, including TimesTen SQL extensions. It also describes data types. PKhHC>PK*AOEBPS/dcommon/prodbig.gif GIF87a!!!)))111BBBZZZsss{{ZRRcZZ!!1!91)JB9B9)kkcJJB991ssc絽Zcc!!{祽BZc!9B!c{!)c{9{Z{{cZB1)sJk{{Z{kBsZJ91)Z{!{BcsRsBc{9ZZk甽kBkR!BZ9c)JJc{!))BZks{BcR{JsBk9k)Zck!!BZ1k!ZcRBZcZJkBk1Z9c!R!c9kZRZRBZ9{99!R1{99R{1!1)c1J)1B!BJRkk{ƽ絵ތkk絵RRs{{{{JJsssBBkkk!!9ss{{ZZssccJJZZRRccRRZZ))cBBJJ99JJ!!c11991199Z11!c!!))Z!!!1BRck{)!cJBkZRZ,HP)XRÇEZ֬4jJ0 @ "8pYҴESY3CƊ@*U:lY0_0#  5tX1E: C_xޘeKTV%ȣOΏ9??:a"\fSrğjAsKJ:nOzO=}E1-I)3(QEQEQEQEQEQEQE֝Hza<["2"pO#f8M[RL(,?g93QSZ uy"lx4h`O!LŏʨXZvq& c՚]+: ǵ@+J]tQ]~[[eϸ (]6A&>ܫ~+כzmZ^(<57KsHf妬Ϧmnẁ&F!:-`b\/(tF*Bֳ ~V{WxxfCnMvF=;5_,6%S>}cQQjsOO5=)Ot [W9 /{^tyNg#ЄGsֿ1-4ooTZ?K Gc+oyڙoNuh^iSo5{\ܹ3Yos}$.nQ-~n,-zr~-|K4R"8a{]^;I<ȤL5"EԤP7_j>OoK;*U.at*K[fym3ii^#wcC'IIkIp$󿉵|CtĈpW¹l{9>⪦׺*ͯj.LfGߍԁw] |WW18>w.ӯ! VӃ :#1~ +މ=;5c__b@W@ +^]ևՃ7 n&g2I8Lw7uҭ$"&"b eZ":8)D'%{}5{; w]iu;_dLʳ4R-,2H6>½HLKܹR ~foZKZ࿷1[oZ7׫Z7R¢?«'y?A}C_iG5s_~^ J5?œ tp]X/c'r%eܺA|4ծ-Ե+ْe1M38Ǯ `|Kյ OVڅu;"d56, X5kYR<̭CiطXԮ];Oy)OcWj֩}=܅s۸QZ*<~%뺃ȶp f~Bðzb\ݳzW*y{=[ C/Ak oXCkt_s}{'y?AmCjޓ{ WRV7r. g~Q"7&͹+c<=,dJ1V߁=T)TR՜*N4 ^Bڥ%B+=@fE5ka}ędܤFH^i1k\Sgdk> ֤aOM\_\T)8靠㡮3ģR: jj,pk/K!t,=ϯZ6(((((((49 xn_kLk&f9sK`zx{{y8H 8b4>ÇНE|7v(z/]k7IxM}8!ycZRQ pKVr(RPEr?^}'ðh{x+ՀLW154cK@Ng C)rr9+c:׹b Жf*s^ fKS7^} *{zq_@8# pF~ [VPe(nw0MW=3#kȵz晨cy PpG#W:%drMh]3HH<\]ԁ|_W HHҡb}P>k {ZErxMX@8C&qskLۙOnO^sCk7ql2XCw5VG.S~H8=(s1~cV5z %v|U2QF=NoW]ո?<`~׮}=ӬfԵ,=;"~Iy7K#g{ñJ?5$y` zz@-~m7mG宝Gٱ>G&K#]؃y1$$t>wqjstX.b̐{Wej)Dxfc:8)=$y|L`xV8ߙ~E)HkwW$J0uʟk>6Sgp~;4֌W+חc"=|ř9bc5> *rg {~cj1rnI#G|8v4wĿhFb><^ pJLm[Dl1;Vx5IZ:1*p)إ1ZbAK(1ׅ|S&5{^ KG^5r>;X׻K^? s fk^8O/"J)3K]N)iL?5!ƾq:G_=X- i,vi2N3 |03Qas ! 7}kZU781M,->e;@Qz T(GK(ah(((((((Y[×j2F}o־oYYq $+]%$ v^rϭ`nax,ZEuWSܽ,g%~"MrsrY~Ҿ"Fت;8{ѰxYEfP^;WPwqbB:c?zp<7;SBfZ)dϛ; 7s^>}⍱x?Bix^#hf,*P9S{w[]GF?1Z_nG~]kk)9Sc5Ո<<6J-ϛ}xUi>ux#ţc'{ᛲq?Oo?x&mѱ'#^t)ϲbb0 F«kIVmVsv@}kҡ!ˍUTtxO̧]ORb|2yԵk܊{sPIc_?ħ:Ig)=Z~' "\M2VSSMyLsl⺿U~"C7\hz_ Rs$~? TAi<lO*>U}+'f>7_K N s8g1^CeКÿE ;{+Y\ O5|Y{/o+ LVcO;7Zx-Ek&dpzbӱ+TaB0gNy׭ 3^c T\$⫫?F33?t._Q~Nln:U/Ceb1-im WʸQM+VpafR3d׫é|Aү-q*I P7:y&]hX^Fbtpܩ?|Wu󭏤ʫxJ3ߴm"(uqA}j.+?S wV ~ [B&<^U?rϜ_OH\'.;|.%pw/ZZG'1j(#0UT` Wzw}>_*9m>󑓀F?EL3"zpubzΕ$+0܉&3zڶ+jyr1QE ( ( ( ( ( ( ( (UIdC0EZm+]Y6^![ ԯsmܶ捆?+me+ZE29)B[;я*wGxsK7;5w)}gH~.Ɣx?X\ߚ}A@tQ(:ͧ|Iq(CT?v[sKG+*רqҍck <#Ljα5݈`8cXP6T5i.K!xX*p&ќZǓϘ7 *oƽ:wlຈ:Q5yIEA/2*2jAҐe}k%K$N9R2?7ýKMV!{W9\PA+c4w` Wx=Ze\X{}yXI Ү!aOÎ{]Qx)#D@9E:*NJ}b|Z>_k7:d$z >&Vv󃏽WlR:RqJfGإd9Tm(ҝEtO}1O[xxEYt8,3v bFF )ǙrPNE8=O#V*Cc𹾾&l&cmCh<.P{ʦ&ۣY+Gxs~k5$> ӥPquŽўZt~Tl>Q.g> %k#ú:Kn'&{[yWQGqF}AЅ׮/}<;VYZa$wQg!$;_ $NKS}“_{MY|w7G!"\JtRy+贾d|o/;5jz_6fHwk<ѰJ#]kAȎ J =YNu%dxRwwbEQEQEQEQEQEQEQEQEQE'fLQZ(1F)hQ@X1KEQE-Q@ 1KE3h=iPb(((1GjZ(-ʹRPbR@ 1KE7`bڒyS0(-&)P+ ڎԴP11F)h&:LRmQ@Q@Š((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((([ufT5K9 ر1S^q|&o2R}E"Ȟib!8ct@>vz\][j3>˘]lNTC\ xo>#,/uY.wI匡܌ FF=cD}w09>&ݪNY'4QTմuHtu D&MZ4%uL䏕xoG; +ooy۳nspq8=} hPE?NѷU95m6R.]B5 |V2]yS9#n@}*%Jw}fvۜآ(ow:O7|Osዹd0jefұY5fXA`㏔(?⏈uG/u$_f+7d(d=w(%9N>x{Ρ\yzI,$f6< AR}E?<+kq-ljthgI+#-AEN=[MTKP}B-̦T^9d@;ZEczvv Ү`GlNOW5-[MѭT-,`g]L)lXqhOMմfݮ4Br%*8%IPEcYH4yGپgn͹񎹭(oyZnۄ?fsscku>Lx­n ] 0%A; OnQESԵm7F[SP"u2ĥNbp DZ QEQEQEQEQEQEQEQEQEQEQEQEQEgmk+='CGW ;£FWW ;£FP oz ԖLTH(N̠&00s5_|LVyA# ; l9#q3C'C?IWPϟ <,~$xj)|Sywu,RFP^UUJM`r|PV?xHIc=B֦Y$;]XRz?IaY?TT~O4 O.4/Fүc˃n/mm(r`n#\ލΟ$:tRk N!V9 H$gOQm}ldm4[{$%LT,@$-SYz6[Ӓ/淑Uq%𦉯j{U3Zn#Ϋde+b9q_w.E>nwlMo8u~CķskV\}ibHT#s9F$K7c +w|% HGU FH6,ۘ#; >3kM8rWT;#nrv{e|RፎomJ%[CܒFPrN~RYr >ᩯ|+O %/t$c J\ vxy|'`? OR7Ul>&|Etx : 8%nFq8eo.cW]m> si:įyAT]ЬMmSkyg{h]zԎe%|=NJ>Z{<rc2)#$H9Si3nu-~I4K.cc0#  @/[7wȡvVqr+jEE@i C񗄄3ޤ-jeC%n(˜0n:;IaXTW ;£FWW ;£FP oz ԖLTH(N̠&00s5_|LVyA# ; l9#q3C'C?IWPo5og K£$yQWa ߃kc^8,T 9F_PNpV >\p29Voo>o 1 Q!A*ŏqCq$o iqG(;z֤O|I}[SLKe$7|̏ X&ߴ_t'6K{Kaj31;GZO[f%&`*bA0F ɬQ6~ x>Zg&yco%ʳ(q(FF8<_> ?MkP,MTIHd0&,Cag;y_]覮 ?J Z|. ZkWcKFn@ysk(ý{I5<{?ZYF&& V \"'/EgVIrQy6h%X4裰oc &|s]G>oZy5=vSs<P Y`gh(((((((((((((+5.K^! k6};}kb+G𶍠:g]j׏y9.1ֶ( { h~(,{{H0\y6! ۨ(  [F%gKY%32y&\ ˒z('oikkQ2 ζ({/$Ð$%pGNÞk2O 4m. "9 Q\X9eִ{K(d*m,Q}MnQ@~:v]& [}d[7m`Õ @<acoiqv$0vdpV(-ZxİYqހ(i;G^ֶ(ym"h%BG"WR0Acijc#aȠ\;WyESt7Fk}/OGk ĥHPpϰvѭᯉXEۙtgkRH(  #s fgKq`m& ,?|}&"^&v<#o;MF> 47B+tk,MVW ɉpY."B8-5h&&psw&AV;Sٜ2OBQ_?²Yo;7o׵>Tlv]}zǨ_w##\NI&=2Rk?J&Odt4[G"0Y3&THL t:M)u] tIM͒8]UA?/ckxCω__NA^|?}_݈4DfrO%@˷ ۥeP7N׵ v˄]dX2Csx37iF52!ѕO9,x-湨 Od̮?{[DFi0Oe6H o8,vlHFKtU(<6:mqq,p$0UEےI<9d?KHtf$?G!FM8$<G5+6=fmSKԦ[veBVڊsh#B_]oz~.k4is s>x3ÍkGnUKd1q329'#g>7Sv6I-  eUwcYp>,D.13@o_*c>xOS|4dyY'?72gg~^sn|c=્mS[d})UfK3a];waTg17[}:T~>Ί68̄dwTl|t%.ɤjڇL&yecFr!g|nY]^[0mH3Ig הxoR>֤S{W,q9d r}/|ɯfy|ٮ,d8ʰdHPI<𶨚1]=UUA<A"8A'wa\ vH2u,gvqXkݬ4pHApAz櫥X]ƙGsgp%0`ξ YRY,QFU?tn}I oUjP5ROwv g#WVx>x46;4C02I8>(/U&[jrDj 6~u9<ƥs~.&{xdIXdhK8'S8ָ?gK\ΗJBx%ϒm^K)u#pIf?0b$y7:gbM/R!gajP0}C^<o<N!f$s SZzw]ɍ<@msKE@;XuVS3ȯ/"G7K6%%B9d>ax;sbyU.ecAp 7=y'xkO~|YO kP)hGwwvG&vp .~x!-][ž+`1o&0EcG4QEQEQ^'k5߅-Xeo% cp ZL@Ex/ɮWt1H#AiXЌF~`7d /k;>[L3 dq@QEQ^W VԵ\jȋ%+88'=R(((((((((((((((}ox]LIڋ%ct|ig$ȸZH@ສג:zX_ "h%$E [pAj iw6L|KX32A= @]/Ti|M/[n`w˄#n<8v>%xQ~ ZھE*gQFR~-Ip 뺕Ư ~YRf}u!pPvT'%d\:|5w.'.z12+HX|梖$ 994~DmZ6I0y$ v.p=kx_mkz8^5sv'{!wtGD $ZOÿ>ck.x#\[Ȩd\2$z1Ѷ~.GY˿HEb3)Z PHOoYI5-RO\$P w<z+|/j_cE+ j^0[&6g2I' ]*Y?)w|Y utw0r) F)>w⻻ .j;27'8SSᗃa?t5xDIL@ɀh<?O5 =eosT5K÷W OJ ` K-_&,r A#|9=v#)/2y<./nhz͟t;-^IJH%s["(s?|C}6Z|gՕk2bt VS0g7ë J.s))*|i#8ڹ<3⫫ym>*k3A*9VWR0A|GP޷50ya/-R F|ɸu*SjW7 x#Lm"GxP* a?\ (<???6޽???6޽ Q6gmh+oc[ƚo _YTv02n$ a#v7{x<:vxbX֬9^{BTG !qǨ9?92cF&;{9w>(Pwm R}su_\\K$˦[Λ^)"X0 ?IaY?TT'Qx~;Qbjz8،G 2hF'?SwÖRj/MKTG+# #d*3H)^9 4 Zxׯs 剼)":I7kWg Vuo?@kfD;0H>둆 y'_I/LOIl4.?0RQGݷ<Cθj1Il7őD qhg 9?|.O .o[4| B4i~IljXV6~}9wUd!VZm_z-ťޱpcѺ#e $w2Aax7>3BԮq"c('OB=ux.WԂcx o Vuo?]ŞOj>4 Inګ/7Q@q5?]x7ź}:1OU« i]_?\\t!D E+I$NP&|IvSWEsZ;ve JV 'F bݮ[GϗH]J)g':߉%GōV+)ckXDuQq mF>ENĽv.OĶz ( ( ( ( ( ( ( ( ( (8xcV/|#smWŠ(< |E񖛨(F伏Un$||;'Ɨm#WͷeqaAEx?9 /YlF*y98%֣(o2I2@12K:(| O?|F3"Q~?~dCuo-QRHPF Ab<~oo7xKzkq%[$ nWBT y9 -=rݴOwpT 0X=a_JC[Gwim^3ڻ (/ _׆K]Be7A¸?}d症޽3u FI TeqyNFG|׮Q@~,|-=MYO13K3X<8?'Gu\G.nog9]G/,[??`n<vr9j'ym"h%BG"WR0A%| }?Q^3t [- r6msv'!o﵍OQwv~&%7AtŠ'aŬ^Okm)}l3Y P02I Ïඥ|Z'5M>DY`@@Mps>Ee%+, 6E(Dtn(Sk,5il;ëaGZآ?x?Z:ڤ_u$&Mݭ]x*Oa^Es~ ޥ}k-S7zpҭmȥTlRz?|2WgCg}Ǘݿw?m{۞Š+55hM4Za )~^{ (=P` p@897Lco/t{dwC"#icAS5P_4  x~EVAijSmĒ$+ǁ_zIv>oc({aEq~>g62Z#,#'ÖylQ4F;y/<Řs;\ڥ񶥡Yܸo@J)uKKc# dɤjڇK1ecFČ7Sӭ-nI}nFdָƗ|5Նb֖[NJxJ鷎p 5Dӯ˺XW y`@!pA¼8fm^Ժ(1#ȁX.Мwx#(ůD5/x]2=qd亀,IF2X8FEz5~ZZCit]zqj?k^}GR֓b41i,9䁓\?=Hj'v0"v*sXYG;B֢ߤ$HLEPyo.r>^WMo4p\-%eEc{FGP+4JgF-E;@u #8>.QEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEko-ıH^I$`I$NTIiROa[@ \`Pv >-Ğ9Ӭ=R KX϶C=đ(S*Cm*O=3szW~2z]xv($y$rM{Xz][Gmgn":(dII5r9&͎'/ӮSס߰'n.4Pi6!WzΣ_LרX_[zueI4/8<:=o :l"O`tBU8@@}9#- -DW*]Su[K;|E̒p@&$[{O3ɲK`$Yʌyv<^GZ̛zW. #QfKW(~qWPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPTtuIHD&Mݬ*%u|dx'PEPEPEPEPEPEPEP;='M.,Ki}̐¨6Iː2,NOQ@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@Q@PK{ssPK*AOEBPS/dcommon/contbig.gif`GIF87a!!!111999BBBJJJRRRccckkksss{{{skk{{ZRRRJJƽ{sZRJRJB91)kcZB9)sskZRJ1޽ƽ{{ssskkkcƵZZRccZRRJJJB{BB9991ssckkZccR))!RRB!!JJ1))99!11ƌ)1R)k֔)s1RZJR{BJs9R1J!11J1J9k{csZk!1J!)cBR9J1B)91B!cRs{!)s!){1B!k!s!{ksksckckZc9B)1!)!)BJ9B1919έƌ!!)JJcZZ{!!!1RR{JJsBBkJJ{!!9BB{1!!J9)!!Z!!c1!!kR!!s9Z!BckJs)19!!c!!ZRZ,H rrxB(Kh" DժuICiи@S z$G3TTʖ&7!f b`D 0!A  k,>SO[!\ *_t  Exr%*_}!#U #4 & ֩3|b]L ]t b+Da&R_2lEٱZ`aC)/яmvUkS r(-iPE Vv_{z GLt\2s!F A#葡JY r|AA,hB}q|B`du }00(䡆<pb,G+oB C0p/x$…– ]7 @2HFc ) @AD \0 LHG',(A` `@SC)_" PH`}Y+_|1.K8pAKMA @?3҄$[JPA)+NH I ,@8G0/@R T,`pF8Ѓ)$^$ DDTDlA@ s;PKPK*AOEBPS/dcommon/darbbook.cssPKPK*A!OEBPS/dcommon/O_signature_clr.JPG"(JFIF``C    $.' ",#(7),01444'9=82<.342C  2!!22222222222222222222222222222222222222222222222222" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (?O '~MQ$Vz;OlJi8L%\]UFjޙ%ԯS;rA]5ފ<׈]j7Ouyq$z'TQuw7Ŀ KX߁M2=S'TQt?.5w'97;~pq=" ~k?`'9q6 E|yayM^Om'fkC&<5x' ?A?Zx'jß={=SßM gVC.5+Hd֪xc^)Җufz{Cީ|D Vkznq|+Xa+{50rx{|OG.OϞ~f/ xxX[2H )c+#jpUOZYX\=SG ߨC|K@;_߆'e?LT?]:?>w ڔ`D^So~xo[Ӡ3i7B:Q8 Vc-ďoi:FM292~y_*_闱YN\Fr=xZ3鳎OwW_QEzW~c]REeaSM}}Hӏ4&.E]u=gMѠ+mF`rNn$w9gMa꺢nTuhf2Xv>އ a(Û6߭?<=>z'TQuw7Ŀ KX߁M2=S'TQt?.5Kko\.8S$TOX߀Gw?Zx汴X)C7~.i6(Щ=+4{mGӭ¸-]&'t_kV*I<1)4thtIsqpQJ+> \m^[aJ5)ny:4o&QEnyAEPEEss 72,PDۢ׃K W{Wjr+wگ iM/;pd?~&?@;7E4gv8 $l'z'TQuw7Ŀ Gֱ=ɿ&G?. iR(5W*$|?w᫼gkmIbHe/_t>tg%y.l}N5[]+Mk0ĠeHdPrsst'UiC,y8`V%9ZIia|ܪvi מYG,o}+kk{YbyIeb*sAtի82zWoEK5z*o-eo;n(P u-I)4Š(HQEQEQEQEhz(X/Đ?}Bk˩ ݏrk0]4>8XzV? }6$}d^F>nU K ?Bտk_9׾x~w'ߞ  uDŽtL ؈5c-E/"|_Oo.IH쐍=i*Iw5(ںw?t5s.)+tQ2dUt5Vĺ.jZ"@IRrZƅY4ߡ_;}ų(KyQf1Aǵt?sZg+?F5_oQR&Dg߿]6FuRD u>ڿxl7?IT8'shj^=.=J1rj1Wl$얲cPx;E,p$֟ˏkw qg"45(ǛkV/=+ũ)bYl~K#˝J_כ5&\F'I#8/|wʾ_Xj Q:os^T1.M_|TO.;?_  jF?g N 8nA2F%i =qW,G=5OU u8]Rq?wr'˻S+۾.ܼ 87Q^elo/T*?L|ۚ<%<,/v_OKs B5f/29n0=zqQq(ª=VX@*J(э(f5qJN_EVǞQEOuoѕOuoa5}gO?:߂8Wא|cڽ~]N&O( (<]>͠@VQ=^~U ̴m&\խ5i:}|}r~9՝f}_>'vVֲ$~^f30^in{\_.O F8to}?${φ|#x^#^n~w=~k~?'KRtO.㌡h![3Zu*ٷճ(ԟ]z_/W1(ԟ]v~g|Yq<ז0 ; b8֮s,w9\?uEyStKaª@\,)) (!EPEPEPEPEPzѧts{v>C/"N6`d*J2gGӧWqBq_1ZuΓ\X]r?=Ey88Mp&pKtO-"wR2 K^-Z< \c>V0^@O7x2WFjs<׻kZ(<Т(OFw/6$1[:ޯԯ#q~4|,LVPem=@=YLUxӃV}AUbcUB.Ds5*kٸAeG>PJxt͝ b88?*$~@ׯD VkraiJs}Q.20x&mXξ,Z]“A-J#`+-E/"<]\a'tZGy.(|lދ~gMK OZdxDŽU9T6ϯ^<Ϡt5CZ]].t۫S=s`ڳ%8iVK:nqe+#<.T6U>zWoy3^I {F?J~=G}k)K$$;$de8*G Uӟ4Ocºw}|]4=ݣ\x$ʠms?q^ipw\"ȿPs^Z Q_0GڼU.t}ROM[G#]8wٞ ӫ87}Cgw vHȩBM55vof =A_٭`Ygx[6 P,5}>蚊(0(+?>+?> k|TuXq6_ +szk :u_ Z߶Ak_U}Jc2u/1[_»ݸG41-bሬ۴}}Eȹפ_c?5gi @cL\L<68hF_Ih>X4K7UТ sMj =J7CKo>Օ5s:߀t ~ηaٿ?|gdL8+gG%o?x`دOqȱwc¨&TW_V_aI=dpG!wu۞սZ1yL50$(l3(:~'ַo A}a3N*[0ǭ HKQV}G@֜$ 9of$ArNqUOgË05#m?D)^_h//5_/<?4}Jį+GkpG4"$ r| >S4Ђ"S 1%R:ȝ 8;PKPz PK*AOEBPS/dcommon/feedback.gif7GIF89a'%(hp|fdx?AN5:dfeDGHɾTdQc`g*6DC\?ؘ||{;=E6JUՄfeA= >@,4`H.|`a (Q 9:&[|ځ,4p Y&BDb,!2@, $wPA'ܠǃ@CO~/d.`I @8ArHx9H75j L 3B/` P#qD*s 3A:3,H70P,R@ p!(F oԥ D;"0 ,6QBRɄHhI@@VDLCk8@NBBL2&pClA?DAk%$`I2 #Q+l7 "=&dL&PRSLIP)PɼirqМ'N8[_}w;PK-PK*AOEBPS/dcommon/booklist.gifGIF89a1޵֥΄kZ{Jk1Rs!BZ)B),@I9Z͓Ca % Dz8Ȁ0FZЌ0P !x8!eL8aWȠFD(~@p+rMS|ӛR$ v "Z:]ZJJEc{*=AP  BiA ']j4$*   & 9q sMiO?jQ = , YFg4.778c&$c%9;PKː5PK*AOEBPS/dcommon/cpyr.htm1 Oracle Legal Notices

Oracle Legal Notices

Copyright Notice

Copyright © 1994-2012, Oracle and/or its affiliates. All rights reserved.

Trademark Notice

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.

License Restrictions Warranty/Consequential Damages Disclaimer

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

Warranty Disclaimer

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

Restricted Rights Notice

If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA 94065.

Hazardous Applications Notice

This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.

Third-Party Content, Products, and Services Disclaimer

This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.

Alpha and Beta Draft Documentation Notice

If this document is in prerelease status:

This documentation is in prerelease status and is intended for demonstration and preliminary use only. It may not be specific to the hardware on which you are using the software. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to this documentation and will not be responsible for any loss, costs, or damages incurred due to the use of this documentation.

Oracle Logo

PKN61PK*AOEBPS/dcommon/masterix.gif.GIF89a1ޜΌscJk1Rs!Bc1J),@IS@0"1 Ѿb$b08PbL,acr B@(fDn Jx11+\%1 p { display: none; } /* Class Selectors */ .ProductTitle { font-family: sans-serif; } .BookTitle { font-family: sans-serif; } .VersionNumber { font-family: sans-serif; } .PrintDate { font-family: sans-serif; font-size: small; } .PartNumber { font-family: sans-serif; font-size: small; } PKeӺ1,PK*AOEBPS/dcommon/larrow.gif#GIF87a絵ƌֵƽ{{ss֜ƔZZ{{{{ZZssZZccJJJJRRBBJJJJ991111))!!{,@pH,Ȥrl:ШtpHc`  өb[.64ꑈ53=Z]'yuLG*)g^!8C?-6(29K"Ĩ0Яl;U+K9^u2,@@ (\Ȱ Ë $P`lj 8x I$4H *(@͉0dа8tA  DсSP v"TUH PhP"Y1bxDǕ̧_=$I /& .)+ 60D)bB~=0#'& *D+l1MG CL1&+D`.1qVG ( "D2QL,p.;u. |r$p+5qBNl<TzB"\9e0u )@D,¹ 2@C~KU 'L6a9 /;<`P!D#Tal6XTYhn[p]݅ 7}B a&AƮe{EɲƮiEp#G}D#xTIzGFǂEc^q}) Y# (tۮNeGL*@/%UB:&k0{ &SdDnBQ^("@q #` @1B4i@ aNȅ@[\B >e007V[N(vpyFe Gb/&|aHZj@""~ӎ)t ? $ EQ.սJ$C,l]A `8A o B C?8cyA @Nz|`:`~7-G|yQ AqA6OzPbZ`>~#8=./edGA2nrBYR@ W h'j4p'!k 00 MT RNF6̙ m` (7%ꑀ;PKl-OJPK*AOEBPS/dcommon/index.gifGIF89a1޵ΥΥ{sc{BZs,@IM" AD B0 3.R~[D"0, ]ШpRNC  /& H&[%7TM/`vS+-+ q D go@" 4o'Uxcxcc&k/ qp zUm(UHDDJBGMԃ;PK(PK*AOEBPS/dcommon/bookbig.gif +GIF89a$!!!)))111999BBBJJJRRRZZZccckkksss{{{skkB991)))!!B11))1!JB9B9!!cZ9ƭƽssk{ZZRccZRRJJJBBB9c!!ν)1)k{s絽ƌkssֽZccJRRBJJ{9BB)11)99!!))11!!k!JZ!)RcJccBcs)1c)JZ!BR!)BZ)99J!Rk9!c11B)Z{)9Bkc1kB9BZ!Z{9Rs)Jkksk9kB1s1Jk9Rƥc{k9s)Z{1k91)s1Rk)Jc1J!))BZ!1k{csc{)19B!)Bcsc{ksc{kZs!RkJkJkքc{9Zks{ck9R)Bks9R9R1J!)Z1B!)c)9)99BR19kksBBJcc{ccBBZ))9kk!!199c11ZBB{9!!R!!Z!!c))!!kR!!s!!BcksRZ1c9B)R91c1)Z!R9B9k1)RcZ{)!1B9JB9B)!)J9B!& Imported from GIF image: bookbig.gif,$!!!)))111999BBBJJJRRRZZZccckkksss{{{skkB991)))!!B11))1!JB9B9!!cZ9ƭƽssk{ZZRccZRRJJJBBB9c!!ν)1)k{s絽ƌkssֽZccJRRBJJ{9BB)11)99!!))11!!k!JZ!)RcJccBcs)1c)JZ!BR!)BZ)99J!Rk9!c11B)Z{)9Bkc1kB9BZ!Z{9Rs)Jkksk9kB1s1Jk9Rƥc{k9s)Z{1k91)s1Rk)Jc1J!))BZ!1k{csc{)19B!)Bcsc{ksc{kZs!RkJkJkքc{9Zks{ck9R)Bks9R9R1J!)Z1B!)c)9)99BR19kksBBJcc{ccBBZ))9kk!!199c11ZBB{9!!R!!Z!!c))!!kR!!s!!BcksRZ1c9B)R91c1)Z!R9B9k1)RcZ{)!1B9JB9B)!)J9BH`\Ȑ:pظа"A6DBH,V@Dڹ'G"v Æ ܥ;n;!;>xAܽ[G.\rQC wr}BŊQ A9ᾑ#5Y0VȒj0l-GqF>ZpM rb ;=.ސW-WѻWo ha!}~ْ ; t 53 :\ 4PcD,0 4*_l0K3-`l.j!c Aa|2L4/1C`@@md;(H*80L0L(h*҇҆o#N84pC (xO@ A)J6rVlF r  fry†$r_pl5xhA+@A=F rGU a 1х4s&H Bdzt x#H%Rr (Ѐ7P`#Rщ'x" #0`@~i `HA'Tk?3!$`-A@1l"P LhʖRG&8A`0DcBH sq@AXB4@&yQhPAppxCQ(rBW00@DP1E?@lP1%T` 0 WB~nQ@;PKGC PK*AOEBPS/dcommon/rarrow.gif/GIF87a絵ƌֵƽ{{ss֜ƔZZ{{{{ZZssZZccJJJJRRBBJJJJ991111))!!{,@pH,Ȥrl:ШLlԸ NCqWEd)#34vwwpN|0yhX!'+-[F 'n5 H $/14w3% C .90" qF 7&E "D mnB|,c96) I @0BW{ᢦdN p!5"D`0 T 0-]ʜ$;PKJV^PK*AOEBPS/dcommon/mix.gifkGIF89aZZZBBBJJJkkk999sss!!!111cccֽ{{{RRR)))猌ƭ{s{sks!,@@pH,B$ 8 t:<8 *'ntPP DQ@rIBJLNPTVEMOQUWfj^!  hhG H  kCúk_a Ǥ^ h`B BeH mm  #F` I lpǎ,p B J\Y!T\(dǏ!Gdˆ R53ټ R;iʲ)G=@-xn.4Y BuU(*BL0PX v`[D! | >!/;xP` (Jj"M6 ;PK枰pkPK*AOEBPS/dcommon/doccd_epub.jsM /* Copyright 2006, 2012, Oracle and/or its affiliates. All rights reserved. Author: Robert Crews Version: 2012.3.17 */ function addLoadEvent(func) { var oldOnload = window.onload; if (typeof(window.onload) != "function") window.onload = func; else window.onload = function() { oldOnload(); func(); } } function compactLists() { var lists = []; var ul = document.getElementsByTagName("ul"); for (var i = 0; i < ul.length; i++) lists.push(ul[i]); var ol = document.getElementsByTagName("ol"); for (var i = 0; i < ol.length; i++) lists.push(ol[i]); for (var i = 0; i < lists.length; i++) { var collapsible = true, c = []; var li = lists[i].getElementsByTagName("li"); for (var j = 0; j < li.length; j++) { var p = li[j].getElementsByTagName("p"); if (p.length > 1) collapsible = false; for (var k = 0; k < p.length; k++) { if ( getTextContent(p[k]).split(" ").length > 12 ) collapsible = false; c.push(p[k]); } } if (collapsible) { for (var j = 0; j < c.length; j++) { c[j].style.margin = "0"; } } } function getTextContent(e) { if (e.textContent) return e.textContent; if (e.innerText) return e.innerText; } } addLoadEvent(compactLists); function processIndex() { try { if (!/\/index.htm(?:|#.*)$/.test(window.location.href)) return false; } catch(e) {} var shortcut = []; lastPrefix = ""; var dd = document.getElementsByTagName("dd"); for (var i = 0; i < dd.length; i++) { if (dd[i].className != 'l1ix') continue; var prefix = getTextContent(dd[i]).substring(0, 2).toUpperCase(); if (!prefix.match(/^([A-Z0-9]{2})/)) continue; if (prefix == lastPrefix) continue; dd[i].id = prefix; var s = document.createElement("a"); s.href = "#" + prefix; s.appendChild(document.createTextNode(prefix)); shortcut.push(s); lastPrefix = prefix; } var h2 = document.getElementsByTagName("h2"); for (var i = 0; i < h2.length; i++) { var nav = document.createElement("div"); nav.style.position = "relative"; nav.style.top = "-1.5ex"; nav.style.left = "1.5em"; nav.style.width = "90%"; while (shortcut[0] && shortcut[0].toString().charAt(shortcut[0].toString().length - 2) == getTextContent(h2[i])) { nav.appendChild(shortcut.shift()); nav.appendChild(document.createTextNode("\u00A0 ")); } h2[i].parentNode.insertBefore(nav, h2[i].nextSibling); } function getTextContent(e) { if (e.textContent) return e.textContent; if (e.innerText) return e.innerText; } } addLoadEvent(processIndex); PKo"nR M PK*AOEBPS/dcommon/toc.gifGIF89a1ΥΥ{c{Z{JkJk1Rk,@IK% 0| eJB,K-1i']Bt9dz0&pZ1o'q(؟dQ=3S SZC8db f&3v2@VPsuk2Gsiw`"IzE%< C !.hC IQ 3o?39T ҍ;PKv I PK*AOEBPS/dcommon/topnav.gifGIF89a1ֽ筽ޭƔkZZk{Bc{,@ ) l)-'KR$&84 SI) XF P8te NRtHPp;Q%Q@'#rR4P fSQ o0MX[) v + `i9gda/&L9i*1$#"%+ ( E' n7Ȇ(,҅(L@(Q$\x 8=6 'נ9tJ&"[Epljt p#ѣHb :f F`A =l|;&9lDP2ncH R `qtp!dȐYH›+?$4mBA9 i@@ ]@ꃤFxAD*^Ŵ#,(ε  $H}F.xf,BD Z;PK1FAPK*AOEBPS/dcommon/bp_layout.css# @charset "utf-8"; /* bp_layout.css Copyright 2007, Oracle and/or its affiliates. All rights reserved. */ body { margin: 0ex; padding: 0ex; } h1 { display: none; } #FOOTER { border-top: #0d4988 solid 10px; background-color: inherit; color: #e4edf3; clear: both; } #FOOTER p { font-size: 80%; margin-top: 0em; margin-left: 1em; } #FOOTER a { background-color: inherit; color: gray; } #LEFTCOLUMN { float: left; width: 50%; } #RIGHTCOLUMN { float: right; width: 50%; clear: right; /* IE hack */ } #LEFTCOLUMN div.portlet { margin-left: 2ex; margin-right: 1ex; } #RIGHTCOLUMN div.portlet { margin-left: 1ex; margin-right: 2ex; } div.portlet { margin: 2ex 1ex; padding-left: 0.5em; padding-right: 0.5em; border: 1px #bcc solid; background-color: #f6f6ff; color: black; } div.portlet h2 { margin-top: 0.5ex; margin-bottom: 0ex; font-size: 110%; } div.portlet p { margin-top: 0ex; } div.portlet ul { list-style-type: none; padding-left: 0em; margin-left: 0em; /* IE Hack */ } div.portlet li { text-align: right; } div.portlet li cite { font-style: normal; float: left; } div.portlet li a { margin: 0px 0.2ex; padding: 0px 0.2ex; font-size: 95%; } #NAME { margin: 0em; padding: 0em; position: relative; top: 0.6ex; left: 10px; width: 80%; } #PRODUCT { font-size: 180%; } #LIBRARY { color: #0b3d73; background: inherit; font-size: 180%; font-family: serif; } #RELEASE { position: absolute; top: 28px; font-size: 80%; font-weight: bold; } #TOOLS { list-style-type: none; position: absolute; top: 1ex; right: 2em; margin: 0em; padding: 0em; background: inherit; color: black; } #TOOLS a { background: inherit; color: black; } #NAV { float: left; width: 96%; margin: 3ex 0em 0ex 0em; padding: 2ex 0em 0ex 4%; /* Avoiding horizontal scroll bars. */ list-style-type: none; background: transparent url(../gifs/nav_bg.gif) repeat-x bottom; } #NAV li { float: left; margin: 0ex 0.1em 0ex 0em; padding: 0ex 0em 0ex 0em; } #NAV li a { display: block; margin: 0em; padding: 3px 0.7em; border-top: 1px solid gray; border-right: 1px solid gray; border-bottom: none; border-left: 1px solid gray; background-color: #a6b3c8; color: #333; } #SUBNAV { float: right; width: 96%; margin: 0ex 0em 0ex 0em; padding: 0.1ex 4% 0.2ex 0em; /* Avoiding horizontal scroll bars. */ list-style-type: none; background-color: #0d4988; color: #e4edf3; } #SUBNAV li { float: right; } #SUBNAV li a { display: block; margin: 0em; padding: 0ex 0.5em; background-color: inherit; color: #e4edf3; } #SIMPLESEARCH { position: absolute; top: 5ex; right: 1em; } #CONTENT { clear: both; } #NAV a:hover, #PORTAL_1 #OVERVIEW a, #PORTAL_2 #OVERVIEW a, #PORTAL_3 #OVERVIEW a, #PORTAL_4 #ADMINISTRATION a, #PORTAL_5 #DEVELOPMENT a, #PORTAL_6 #DEVELOPMENT a, #PORTAL_7 #DEVELOPMENT a, #PORTAL_11 #INSTALLATION a, #PORTAL_15 #ADMINISTRATION a, #PORTAL_16 #ADMINISTRATION a { background-color: #0d4988; color: #e4edf3; padding-bottom: 4px; border-color: gray; } #SUBNAV a:hover, #PORTAL_2 #SEARCH a, #PORTAL_3 #BOOKS a, #PORTAL_6 #WAREHOUSING a, #PORTAL_7 #UNSTRUCTURED a, #PORTAL_15 #INTEGRATION a, #PORTAL_16 #GRID a { position: relative; top: 2px; background-color: white; color: #0a4e89; } PK3( # PK*AOEBPS/dcommon/bookicon.gif:GIF87a!!!)))111999BBBJJJRRRZZZccckkksss{{{ޭ{{ZRRcZZRJJJBB)!!skRB9{sν{skskcZRJ1)!֭ƽ{ZZRccZJJBBB999111)JJ9BB1ZZB!!ﭵBJJ9BB!!))Jk{)1!)BRZJ{BsR!RRJsJ!J{s!JsBkks{RsB{J{c1RBs1ZB{9BJ9JZ!1BJRRs!9R!!9Z9!1)J19JJRk19R1Z)!1B9R1RB!)J!J1R)J119!9J91!9BkksBBJ119BBR!))9!!!JB1JJ!)19BJRZckތ1)1J9B,H*\hp >"p`ƒFF "a"E|ժOC&xCRz OBtX>XE*O>tdqAJ +,WxP!CYpQ HQzDHP)T njJM2ꔀJ2T0d#+I:<жk 'ꤱF AB @@nh Wz' H|-7f\A#yNR5 /PM09u UjćT|q~Yq@&0YZAPa`EzI /$AD Al!AAal 2H@$ PVAB&c*ؠ p @% p-`@b`uBa l&`3Ap8槖X~ vX$Eh`.JhAepA\"Bl, :Hk;PKx[?:PK*AOEBPS/dcommon/conticon.gif^GIF87a!!!)))111999BBBJJJRRRZZZccckkksss{{{ZRR޽{{ssskkkcccZ991ccRZZBBJJZck)19ZcsBJZ19J!k{k)Z1RZs1!B)!J91{k{)J!B!B911)k{cs!1s!9)s!9!B!k)k1c!)Z!R{9BJcckZZcBBJ99B119{{!!)BBRBBZ!))999R99Z!!999c1!9!)19B1)!B9R,  oua\h2SYPa aowwxYi 9SwyyxxyYSd $'^qYȵYvh ч,/?g{н.J5fe{ڶyY#%/}‚e,Z|pAܠ `KYx,ĉ&@iX9|`p ]lR1khٜ'E 6ÅB0J;t X b RP(*MÄ!2cLhPC <0Ⴁ  $4!B 6lHC%<1e H 4p" L`P!/,m*1F`#D0D^!AO@..(``_؅QWK>_*OY0J@pw'tVh;PKp*c^PK*AOEBPS/dcommon/blafdoc.cssL@charset "utf-8"; /* Copyright 2002, 2011, Oracle and/or its affiliates. All rights reserved. Author: Robert Crews Version: 2011.10.7 */ body { font-family: Tahoma, sans-serif; /* line-height: 125%; */ color: black; background-color: white; font-size: small; } * html body { /* http://www.info.com.ph/~etan/w3pantheon/style/modifiedsbmh.html */ font-size: x-small; /* for IE5.x/win */ f\ont-size: small; /* for other IE versions */ } h1 { font-size: 165%; font-weight: bold; border-bottom: 1px solid #ddd; width: 100%; } h2 { font-size: 152%; font-weight: bold; } h3 { font-size: 139%; font-weight: bold; } h4 { font-size: 126%; font-weight: bold; } h5 { font-size: 113%; font-weight: bold; display: inline; } h6 { font-size: 100%; font-weight: bold; font-style: italic; display: inline; } a:link { color: #039; background: inherit; } a:visited { color: #72007C; background: inherit; } a:hover { text-decoration: underline; } a img, img[usemap] { border-style: none; } code, pre, samp, tt { font-family: monospace; font-size: 110%; } caption { text-align: center; font-weight: bold; width: auto; } dt { font-weight: bold; } table { font-size: small; /* for ICEBrowser */ } td { vertical-align: top; } th { font-weight: bold; text-align: left; vertical-align: bottom; } ol ol { list-style-type: lower-alpha; } ol ol ol { list-style-type: lower-roman; } td p:first-child, td pre:first-child { margin-top: 0px; margin-bottom: 0px; } table.table-border { border-collapse: collapse; border-top: 1px solid #ccc; border-left: 1px solid #ccc; } table.table-border th { padding: 0.5ex 0.25em; color: black; background-color: #f7f7ea; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; } table.table-border td { padding: 0.5ex 0.25em; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; } span.gui-object, span.gui-object-action { font-weight: bold; } span.gui-object-title { } p.horizontal-rule { width: 100%; border: solid #cc9; border-width: 0px 0px 1px 0px; margin-bottom: 4ex; } div.zz-skip-header { display: none; } td.zz-nav-header-cell { text-align: left; font-size: 95%; width: 99%; color: black; background: inherit; font-weight: normal; vertical-align: top; margin-top: 0ex; padding-top: 0ex; } a.zz-nav-header-link { font-size: 95%; } td.zz-nav-button-cell { white-space: nowrap; text-align: center; width: 1%; vertical-align: top; padding-left: 4px; padding-right: 4px; margin-top: 0ex; padding-top: 0ex; } a.zz-nav-button-link { font-size: 90%; } div.zz-nav-footer-menu { width: 100%; text-align: center; margin-top: 2ex; margin-bottom: 4ex; } p.zz-legal-notice, a.zz-legal-notice-link { font-size: 85%; /* display: none; */ /* Uncomment to hide legal notice */ } /*************************************/ /* Begin DARB Formats */ /*************************************/ .bold, .codeinlinebold, .syntaxinlinebold, .term, .glossterm, .seghead, .glossaryterm, .keyword, .msg, .msgexplankw, .msgactionkw, .notep1, .xreftitlebold { font-weight: bold; } .italic, .codeinlineitalic, .syntaxinlineitalic, .variable, .xreftitleitalic { font-style: italic; } .bolditalic, .codeinlineboldital, .syntaxinlineboldital, .titleinfigure, .titleinexample, .titleintable, .titleinequation, .xreftitleboldital { font-weight: bold; font-style: italic; } .itemizedlisttitle, .orderedlisttitle, .segmentedlisttitle, .variablelisttitle { font-weight: bold; } .bridgehead, .titleinrefsubsect3 { font-weight: bold; } .titleinrefsubsect { font-size: 126%; font-weight: bold; } .titleinrefsubsect2 { font-size: 113%; font-weight: bold; } .subhead1 { display: block; font-size: 139%; font-weight: bold; } .subhead2 { display: block; font-weight: bold; } .subhead3 { font-weight: bold; } .underline { text-decoration: underline; } .superscript { vertical-align: super; } .subscript { vertical-align: sub; } .listofeft { border: none; } .betadraft, .alphabetanotice, .revenuerecognitionnotice { color: #e00; background: inherit; } .betadraftsubtitle { text-align: center; font-weight: bold; color: #e00; background: inherit; } .comment { color: #080; background: inherit; font-weight: bold; } .copyrightlogo { text-align: center; font-size: 85%; } .tocsubheader { list-style-type: none; } table.icons td { padding-left: 6px; padding-right: 6px; } .l1ix dd, dd dl.l2ix, dd dl.l3ix { margin-top: 0ex; margin-bottom: 0ex; } div.infoboxnote, div.infoboxnotewarn, div.infoboxnotealso { margin-top: 4ex; margin-right: 10%; margin-left: 10%; margin-bottom: 4ex; padding: 0.25em; border-top: 1pt solid gray; border-bottom: 1pt solid gray; } p.notep1 { margin-top: 0px; margin-bottom: 0px; } .tahiti-highlight-example { background: #ff9; text-decoration: inherit; } .tahiti-highlight-search { background: #9cf; text-decoration: inherit; } .tahiti-sidebar-heading { font-size: 110%; margin-bottom: 0px; padding-bottom: 0px; } /*************************************/ /* End DARB Formats */ /*************************************/ @media all { /* * * { line-height: 120%; } */ dd { margin-bottom: 2ex; } dl:first-child { margin-top: 2ex; } } @media print { body { font-size: 11pt; padding: 0px !important; } a:link, a:visited { color: black; background: inherit; } code, pre, samp, tt { font-size: 10pt; } #nav, #search_this_book, #comment_form, #comment_announcement, #flipNav, .noprint { display: none !important; } body#left-nav-present { overflow: visible !important; } } PKʍPK*AOEBPS/dcommon/rightnav.gif&GIF89a1ֽ筽ޭƔkZZk{Bc{,@ ) l)- $CҠҀ ! D1 #:aS( c4B0 AC8 ְ9!%MLj Z * ctypJBa H t>#Sb(clhUԂ̗4DztSԙ9ZQҀEPEPEPEPEPEPEPM=iԍP Gii c*yF 1׆@\&o!QY00_rlgV;)DGhCq7~..p&1c:u֫{fI>fJL$}BBP?JRWc<^j+χ5b[hֿ- 5_j?POkeQ^hֿ1L^ H ?Qi?z?+_xɔŪ\썽O]χ>)xxV/s)e6MI7*ߊޛv֗2J,;~E4yi3[nI`Ѱe9@zXF*W +]7QJ$$=&`a۾?]N T䏟'X)Ɣkf:j |>NBWzYx0t!* _KkoTZ?K Gc+UyڹgNuh^iSo5{\ܹ3Yos}.>if FqR5\/TӮ#]HS0DKu{($"2xִ{SBJ8=}Y=.|Tsц2UЫ%.InaegKo z ݎ3ֹxxwM&2S%';+I',kW&-"_¿_ Vq^ܫ6pfT2RV A^6RKetto^[{w\jPZ@ޢN4/XN#\42j\(z'j =~-I#:q[Eh|X:sp* bifp$TspZ-}NM*B-bb&*xUr#*$M|QWY ~p~- fTED6O.#$m+t$˙H"Gk=t9r娮Y? CzE[/*-{c*[w~o_?%ƔxZ:/5𨴟q}/]22p qD\H"K]ZMKR&\C3zĽ[PJm]AS)Ia^km M@dК)fT[ijW*hnu Ͳiw/bkExG£@f?Zu.s0(<`0ֹoxOaDx\zT-^ѧʧ_1+CP/p[w 9~U^[U<[tĽwPv[yzD1W='u$Oeak[^ |Gk2xv#2?¹TkSݕ| rݞ[Vi _Kz*{\c(Ck_܏|?u jVڔ6f t?3nmZ6f%QAjJf9Rq _j7Z-y.pG$Xb]0')[_k;$̭?&"0FOew7 z-cIX岛;$u=\an$ zmrILu uٞ% _1xcUW%dtÀx885Y^gn;}ӭ)場QEQ@Q@Q@Q@Q@Q@!4xPm3w*]b`F_931˜[ן+(> E ly;<;MF-qst+}DH @YKlLmؤciN<|]IU)Lw(8t9FS(=>og<\Z~u_+X1ylsj'eՃ*U3`C!N9Q_WܱhKc93^ua>H ƕGk=8~e#_?{ǀe-[2ٔ7;=&K挑5zsLdx(e8#{1wS+ΝVkXq9>&yஏh$zq^0~/j@:/«Vnce$$uoPp}MC{$-akH@ɫ1O !8R9s5ԦYmϧ'OUṡ5T,!Ԛ+s#1Veo=[)g>#< s)ƽُA^䠮ωFUj(ǩ|N3Jڷ睁ϱuږZYGOTsI<&drav?A^_f׻B$,O__ԿC`it{6>G׈C~&$y؎v1q9Sc1fH[ѽ>,gG'0'@Vw,BO [#>ﱺg5ΒFVD%Yr:O5 Tu+O멃]ی38Ze}R&ѝ_xzc1DXgس;<,_,{ƽY'AS#oF.M#~cBuEx7G+Y)(5q+GCV;qF+CLQ)qEC&6z𿊘z}?&w=+)??&\g{;V??׻xGœdٿ׼-Nc')3K]N)iLTӿCdb7Q^a N sd>Fz[0S^s'Zi 77D}kWus ab~~H(>.fif9,~|Jk;YN3H8Y(t6Q݉k͇_÷Z+2߄&[ +Tr^藺97~c܎=[f1RrBǓ^kEMhxYVm<[џ6| kqbѱ| YA{G8p?\UM7Z66 g1U1igU69 u5Pƪ:VVZC=[@ҹ¨$kSmɳО\vFz~i3^a Osŧυ9Q}_3 όO{/wgoet39 vO2ea;Ύ7$U#?k+Ek&dpzbӱ+TaB0gN{[N7Gי}U7&@?>Fz~E!a@s ?'67XxO*!?qi]֏TQN@tI+\^s8l0)2k!!iW8F$(yOּT.k,/#1:}8uT˾+5=O/`IW G֯b.-<= HOm;~so~hW5+kS8s.zwE| ?4ӿw/K N 9?j(#0UT` Wzw}:_*9m>󑓀F?ELzv=8q:=WgJ`nDr Zе<ֹ](Q@Q@Q@Q@Q@Q@Q@Q@ 'IdC0EYJVcMty_~u+Sw-aO n<[YJgL#6i g5ЖDZ14cʝ!!\/M}/_AYR__>oC? _?7_G#RERW쏞KB}JxGSkǕA pƱơP m]hwB7U$Zq M95"3q1ioATߚ{g.t uu2k=;h#YB= fgS :TdLԃ!44mFK{Hrd^7oz|BVr<{)6AXգV»|>*/hS܏z͆OM=Εq (s|s׊LKQI :9NJ)P+!ʣoAF>+=@I}"x/}۠1aנc¹4emC:>p_xWKX` >R3_S½èųp3޺u3N e یbmͺ<_ mnݮ1Op?Gm)Qb%N585'%Ahs\6yw!"&Ɨ._wk)}GP;Z!#\"< *oƾ\)}N>"լ/~]Lg}pBG X?<zZ#x69S=6) jzx=y9O&>+e!!? ?s~k5Gʏ)?*ce7Ox~k5􇔾Q/e7/Ԑ#3OgNC0] ;_FiRl>Q.g>!%k#ú:Kn'&}?U@\pџPtp)v<{_i}Oվֲ3XIYIx~b<D?(=_JXH=bbi=Oh?_ C_O)}oW쏜? %Ƶ;-RYFi`wۭ{ϖZMtQ$"c_+ԃx1*0b;ԕ݋ESQEQEQEQEQEQEQEQEQEQZ(1F)h1K@XLRE&9P (bf{RӨ&)PEPEPbԴPGKZ(iإbn(:A%S0(-&)P+ ڎԴP11F)h&:LRmQ@Q@Š(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((PKje88PK*AOEBPS/dcommon/help.gif!GIF89a1εֵ֜֜{kZsBc{,@ )sƠTQ$8(4ʔ%ŌCK$A HP`$h8ŒSd+ɡ\ H@%' 6M HO3SJM /:Zi[7 \( R9r ERI%  N=aq   qƦs *q-n/Sqj D XZ;PKއ{&!PK*AOEBPS/names.htm>h Names, Namespace and Parameters

2 Names, Namespace and Parameters

This chapter presents general rules for names and parameters used in TimesTen SQL statements. It includes the following topics:

Basic names

Basic names identify columns, tables, views and indexes. Basic names must follow these rules:

  • The maximum length of a basic name is 30 characters.

  • A name can consist of any combination of letters (A to Z a to z), decimal digits (0 to 9), $, #, @, or underscore (_). For identifiers, the first character must be a letter (A-Z a-z) and not a digit or special character. However, for parameter names, the first character can be a letter (A-Z a-z), a decimal digit (0 to 9), or special characters $, #, @, or underscore (_). Neither a cache group name nor a cache group table name can contain #.

  • TimesTen changes lowercase letters (a to z) to the corresponding uppercase letters (A to Z). Thus names are not case-sensitive.

  • If you enclose a name in quotation marks, you can use any combination of characters even if they are not in the set of legal characters. When the name is enclosed in quotes, the first character in the name can be any character, including one or more spaces.

    If a column, table, or index is initially defined with a name enclosed in quotation marks and the name does not conform to the rule noted in the second bullet, then that name must always be enclosed in quotation marks whenever it is subsequently referenced.

  • Unicode characters are not allowed in names.

Owner names

The owner name is the user name of the account that created the table. Tables and indexes defined by TimesTen itself have the owner SYS or TTREP. User objects cannot be created with owner names SYS or TTREP. TimesTen converts all owner and table names to upper case.

Owners of tables in TimesTen are determined by the user ID settings or login names. For cache groups, Oracle table owner names must always match TimesTen table owner names.

Owner names may be specified by the user during table creation, in addition to being automatically determined if they are left unspecified. See "CREATE TABLE". When creating owner names, follow the same rules as those for creating basic names. See "Basic names".

Compound identifiers

Basic names and user names are simple names. In some cases, simple names are combined to form a compound identifier, which consists of an owner name combined with one or more basic names, with periods (.) between them.

In most cases you can abbreviate a compound identifier by omitting one of its parts. If you do not use a fully qualified name, a default value is automatically used in place of the missing part. For example, if you omit the owner name (and the period) when you refer to tables you own, TimesTen generates the owner name by using your login name.

A complete compound identifier, including all of its parts, is called a fully qualified name. Different owners can have tables and indexes with the same name. The fully qualified name of these objects must be unique.

The following are compound identifiers:

  • Column identifier: [[Owner.]TableName.]ColumnName

  • [Owner.]IndexName

  • Table identifier: [Owner.]TableName

  • Row identifier: [[Owner.]TableName.]rowid

Namespace

In SQL syntax, each name of an object that share the same namespace must be unique, so that when referenced in any SQL syntax, the exact object can be found.

The following objects owned by the same user share one namespace and so the names for each of these objects must be unique within that namespace: tables, views, materialized views, sequences, private synonyms, PL/SQL packages, functions, procedures, and cache groups.

Indexes are created in their own namespace.

Because tables and views are in the same namespace, a table and a view owned by the same user cannot have the same name. However, tables and indexes are in different namespaces. Therefore, a table and an index owned by the same user can have the same name.

Tables that are owned by separate users can have the same name, since they exist in separate user namespaces.

If the object name provided is not qualified with the user that owns it, then the search order for an object is as follows:

  1. Search for any match from all object names within the current user namespace. If there is a match, the object name is resolved.

  2. If no match is found in the user namespace, search for any match from the PUBLIC namespace, which contains objects such as public synonyms. Public synonyms are pre-defined for SYS and TTREP objects. If there is a match, the object name is resolved. Otherwise, the object does not exist.

Dynamic parameters

Dynamic parameters are used to pass information between an application program and TimesTen. They are placeholders in SQL commands and are replaced at runtime with actual values.

A dynamic parameter name must be preceded by a colon (:) when used in a SQL command and must conform to the TimesTen rules for basic names. However, unlike identifiers, parameter names can start with any of the following characters:

  • Uppercase letters: A to Z

  • Lowercase letters: a to z

  • Digits: 0 to 9

  • Special characters: # $ @ _


Note:

Instead of using a :DynamicParameter sequence, the application can use a ? for each dynamic parameter.

Enhanced ":" style parameter markers have this form:

:parameter [INDICATOR] :indicator

The :indicator is considered to be a component of the :parameter. It is not counted as a distinct parameter. Do not specify '?' for this style of parameter marker.

Duplicate parameter names

Consider this SQL statement:

SELECT * FROM t1 WHERE c1=:a AND c2=:a AND c3=:b AND c4=:a;

Traditionally in TimesTen, multiple instances of the same parameter name in a SQL statement are considered to be multiple occurrences of the same parameter. When assigning parameter numbers to parameters, TimesTen assigns parameter numbers only to the first occurrence of each parameter name. The second and subsequent occurrences of a given name do not get their own parameter numbers. In this case, a TimesTen application binds a value for every unique parameter in a SQL statement. It cannot bind different values for different occurrences of the same parameter name nor can it leave any parameters or parameter occurrences unbound.

In Oracle Database, multiple instances of the same parameter name in a SQL statement are considered to be different parameters. When assigning parameter numbers, Oracle assigns a number to each parameter occurrence without regard to name duplication. An Oracle application, at a minimum, binds a value for the first occurrence of each parameter name. For the subsequent occurrences of a given parameter, the application can either leave the parameter occurrence unbound or it can bind a different value for the occurrence.

The following table shows a query with the parameter numbers that TimesTen and Oracle Database assign to each parameter.

QueryTimesTen parameter numberOracle Database parameter number
SELECT *

FROM t1

WHERE c1=:a11
AND c2=:a12
AND c3=:b23
AND c4=:a;14

The total number of parameter numbers for TimesTen in this example is 2. The total number of parameters for Oracle Database in this example is 4. The parameter bindings provided by an application produce different results for the traditional TimesTen behavior and the Oracle behavior.

You can use the DuplicateBindMode general connection attribute to determine whether applications use traditional TimesTen parameter binding for duplicate occurrences of a parameter in a SQL statement or Oracle-style parameter binding. Oracle-style parameter binding is the default.

Inferring data type from parameters

Consider this statement:

SELECT :a FROM dual;

TimesTen cannot infer the data type of parameter a from the query. TimesTen returns this error:

2778: Cannot infer type of parameter from its use
The command failed.

Use the CAST function to declare the data type for parameters:

SELECT CAST (:a AS NUMBER) FROM dual;
PKh͜>>PK*AOEBPS/search.htm Search Conditions

5 Search Conditions

A search condition specifies criteria for choosing rows to select, update, or delete. Search conditions are parameters that can exist in clauses and expressions of any DML statements, such as INSERT...SELECT, UPDATE and CREATE VIEW and some DDL statements, such as CREATE VIEW.


Search condition general syntax

A search condition is a single predicate or several predicates connected by the logical operators AND or OR. A predicate is an operation on expressions that evaluates to TRUE, FALSE, or UNKNOWN. If a predicate evaluates to TRUE for a row, the row qualifies for further processing. If the predicate evaluates to FALSE or NULL for a row, the row is not available for operations.

SQL syntax

[NOT] 
{BetweenPredicate | ComparisonPredicate | InPredicate |
    LikePredicate| NullPredicate | InfinitePredicate | NaNPredicate |
QuantifiedPredicate |(SearchCondition)} 
[{AND | OR} [NOT] 
{BetweenPredicate | ComparisonPredicate |InPredicate |
    LikePredicate|NullPredicate | QuantifiedPredicate |(SearchCondition)}
] [...]

Parameters

ComponentDescription
NOT, AND, ORLogical operators with the following functions:
  • NOT negates the value of the predicate that follows it.

  • AND evaluates to TRUE if both the predicates it joins evaluate to TRUE.

  • OR evaluates to TRUE if either predicate it joins evaluates to TRUE, and to FALSE if both predicates evaluates to FALSE.

  • See "Description" for a description of how these operators work when predicates evaluate to NULL.

BetweenPredicateDetermines whether an expression is within a certain range of values. For example: A BETWEEN B AND C is equivalent to A >= B AND A<= C.
ComparisonPredicateCompares two expressions or list of two expressions using one of the operators <, <=, >, >=, =, <>.
InPredicateDetermines whether an expression or list of expressions matches an element within a specified set.
ExistsPredicateDetermines whether a subquery returns any row.
LikePredicateDetermines whether an expression contains a particular character string pattern.
NullPredicateDetermines whether a value is NULL.
InfinitePredicateDetermines whether an expression is infinite (positive or negative infinity).
NaNPredicateDetermines whether an expression is the undefined result of an operation ("not a number").
QuantifiedPredicateDetermines whether an expression or list of expressions bears a particular relationship to a specified set.
(SearchCondition)One of the above predicates, enclosed in parentheses.

Description

  • Predicates in a search condition are evaluated as follows:

    • Predicates in parentheses are evaluated first.

    • NOT is applied to each predicate.

    • AND is applied next, left to right.

    • OR is applied last, left to right.

    Figure 5-1 shows the values that result from logical operations. A question mark (?) represents the NULL value.

Figure 5-1 Values that result from logical operations

Description of Figure 5-1 follows
Description of "Figure 5-1 Values that result from logical operations"

  • When the search condition for a row evaluates to NULL, the row does not satisfy the search condition and the row is not operated on.

  • You can compare only compatible data types.

    • TT_TINYINT, TT_SMALLINT, TT_INTEGER, TT_BIGINT, NUMBER, BINARY_FLOAT and BINARY_DOUBLE are compatible.

    • CHAR, VARCHAR2, BINARY, and VARBINARY are compatible, regardless of length.

    • CHAR, VARCHAR2, NCHAR, NVARCHAR2, TT_TIME, DATE and TIMESTAMP are compatible.

  • See Chapter 3, "Expressions" for information on value extensions during comparison operations.

  • See "Numeric data types" for information about how TimesTen compares values of different but compatible types.


ALL/ NOT IN predicate (subquery)

The ALL or NOT IN predicate indicates that the operands on the left side of the comparison must compare in the same way with all of the values that the subquery returns. The ALL predicate evaluates to TRUE if the expression or list of expressions relates to all rows returned by the subquery as specified by the comparison operator. Similarly, the NOT IN predicate evaluates to TRUE if the expression or list of expressions does not equal the value returned by the subquery.

SQL syntax

RowValueConstructor {CompOp ALL| NOT IN} (Subquery)

The syntax for RowValueConstructor:

RowValueConstructorElement | (RowValueConstuctorList) | Subquery

The syntax for RowValueConstructorList:

RowValueConstructorElement [{, RowValueConstructorElement} ... ]

The syntax for RowValueConstructorElement:

Expression | NULL

The syntax for CompOp:

{= | <> | > | >= | < | <= }

Parameters

ComponentDescription
ExpressionThe syntax of expressions is defined under "Expression specification". Both numeric and non-numeric expressions are allowed for ALL predicates, but both expression types must be compatible with each other.
=
Is equal to.
<>Is not equal to.
>Is greater than.
>=Is greater than or equal to.
<
Is less than.
<=
Is less than or equal to.
SubqueryThe syntax of subqueries is defined under "Subqueries"

Description

  • The ALL predicate, which returns zero or more rows, uses a comparison operator modified with the keyword ALL. See "Numeric data types" for information about how TimesTen compares values of different but compatible types.

  • If RowValueConstructorList is specified only the operators = and <> are allowed.

Examples

Examples of NOT IN with subqueries:

SELECT * FROM customers 
WHERE cid NOT IN
(SELECT cust_id FROM returns)
AND cid > 5000;

SELECT * FROM customers 
WHERE cid NOT IN
(SELECT cust_id FROM returns)
AND cid NOT IN
(SELECT cust_id FROM complaints);

SELECT COUNT(*) From customers 
WHERE cid NOT IN
(SELECT cust_id FROM returns)
AND cid NOT IN
(SELECT cust_id FROM complaints);

Select all books that are not from exclBookList or if the price of the book is higher than $20.

SELECT * FROM books 
 WHERE id NOT IN (SELECT id FROM exclBookList) OR books.price>20;

The following query returns the employee_id and job_id from the job_history table. It illustrates use of expression list and subquery with the NOT IN predicate.

Command> SELECT employee_id, job_id FROM job_history 
       > WHERE (employee_id, job_id)
       > NOT IN (SELECT employee_id, job_id FROM employees);
< 101, AC_ACCOUNT >
< 101, AC_MGR >
< 102, IT_PROG >
< 114, ST_CLERK >
< 122, ST_CLERK >
< 176, SA_MAN >
< 200, AC_ACCOUNT >
< 201, MK_REP >
8 rows found.

ALL/NOT IN predicate (value list)

The ALL/NOT IN quantified predicate compares an expression or list of expressions with a list of specified values. The ALL predicate evaluates to TRUE if all the values in the ValueList relate to the expression or list of expressions as indicated by the comparison operator. Similarly, the NOT IN predicate evaluates to TRUE if the expression or list of expressions does not equal one of the values in the list.

SQL syntax

RowValueConstructor {CompOp ALL | NOT IN} ValueList

The syntax for RowValueConstructor:

RowValueConstructorElement | (RowValueConstuctorList) | 

The syntax for RowValueConstructorList:

RowValueConstructorElement[{, RowValueConstructorElement} ... ]

The syntax for RowValueConstructorElement:

Expression | NULL

The syntax for CompOp:

{= | <> | > | >= | < | <= }

The syntax for more than one element in the ValueList:

({Constant | ? | :DynamicParameter} [,...] )

The syntax for one element in the ValueList not enclosed in parentheses:

Constant | ? | :DynamicParameter

The syntax for an empty ValueList:

( )

The syntax for the ValueList for a list of expressions:

(({Constant | ? | :DynamicParameter} [,...]))

Parameters

ComponentDescription
ExpressionSpecifies a value to be obtained. The values in ValueList must be compatible with the expression. For information on the syntax of expressions, see "Expression specification".
=
Is equal to.
<>Is not equal to.
>Is greater than.
>=Is greater than or equal to.
<
Is less than.
<=
Is less than or equal to.
ALLThe predicate is TRUE if all the values in the ValueList relate to the expression or list of expressions as indicated by the comparison operator.
ValueListA list of values that are compared against the expression's or list of expression's value. The ValueList cannot contain a column reference or a subquery. The ValueList can be nested if the left operand of the ValueList is a list.

Elements of the ValueList:

  • Constant—Indicates a specific value. See "Constants".

  • ?,:DynamicParameter—Placeholder for a dynamic parameter in a prepared SQL statement. The value of the dynamic parameter is supplied when the statement is executed.

  • Empty list, which are sometimes generated by SQL generation tools.


Description

  • If X is the value of Expression, and (a,b, ..., z) represents the elements in ValueList, and OP is a comparison operator, then the following is true:

    • X OP ALL (a,b,...,z) is equivalent to X OP a AND X OP b AND...AND X OP z.

  • If X is the value of Expression and (a,b,..., z) are the elements in a Value­List, then the following is true:

    • X NOT IN (a,b,...,z) is equivalent to NOT (X IN (a,b,...,z)).

  • All character data types are compared in accordance with the current value of the NLS_SORT session parameter.

  • NULL cannot be specified in ValueList.

  • See "Numeric data types" for information about how TimesTen compares values of different but compatible types.

  • NOT IN or NOT EXISTS with ALL can be specified in an OR expression.

  • IN and EXISTS with ALL can be specified in an OR expression.

  • When evaluating an empty ValueList, the result of Expression NOT IN is true.

  • If RowValueConstructorList is specified only the operators = and <> are allowed.

Examples

To query an empty select list for a NOT IN condition:

SELECT * FROM t1 WHERE x1 NOT IN ();

ANY/ IN predicate (subquery)

An ANY predicate compares two expressions using a comparison operator. The predicate evaluates to TRUE if the first expression relates to anyrow returned by the subquery as specified by the comparison operator. Similarly, the IN predicate compares an expression or list of expressions with a table subquery. The IN predicate evaluates to TRUE if the expression or list of expressions is equal to a value returned by a subquery.

SQL syntax

RowValueConstructor {CompOp ANY| IN} (Subquery)

The syntax for RowValueConstructor:

RowValueConstructorElement | (RowValueConstuctorList) | Subquery

The syntax for RowValueConstructorList:

RowValueConstructorElement[{, RowValueConstructorElement} ... ]

The syntax for RowValueConstructorElement:

Expression | NULL

The syntax for CompOp:

{= | <> | > | >= | < | <= }

Parameters

ComponentDescription
ExpressionThe syntax of expressions is defined under "Expression specification". Both numeric and non-numeric expressions are allowed for ANY predicates, but both expression types must be compatible with each other.
=
Is equal to.
<>Is not equal to.
>Is greater than.
>=Is greater than or equal to.
<
Is less than.
<=
Is less than or equal to.
SubqueryThe syntax of subqueries is defined under "Subqueries".

Description

The ANY predicate, which returns zero or more rows, uses a comparison operator modified with the keyword ANY. See "Numeric data types" for information about how TimesTen compares values of different but compatible types.

Examples

This example retrieves a list of customers having at least one unshipped order:

SELECT customers.name FROM customers 
WHERE customers.id = ANY 
(SELECT orders.custid FROM orders 
WHERE orders.status = 'unshipped');

This is an example of an IN predicate with subquery. It SELECTs customers having at least one unshipped order:

SELECT customers.name FROM customers 
WHERE customers.id IN 
(SELECT orders.custid FROM orders 
WHERE orders.status = 'unshipped');

This example uses an aggregate query that specifies a subquery with IN to find the maximum price of a book in the exclBookList:

SELECT MAX(price) FROM books WHERE id IN (SELECT id FROM exclBookList);

This example illustrates the use of a list of expressions with the IN predicate and a subquery.

SELECT * FROM t1 WHERE (x1,y1) IN (SELECT x2,y2 FROM t2);

This example illustrates the use of a list of expressions with the ANY predicate and a subquery.

SELECT * FROM t1 WHERE (x1,y1) < ANY (SELECT x2,y2 FROM t2);

The following example illustrates the use of a list of expressions with the ANY predicate.

Command> columnlabels on;
Command> SELECT * FROM t1;
X1, Y1
< 1, 2 >
< 3, 4 >
2 rows found.
Command> SELECT * FROM t2;
X2, Y2
< 3, 4 >
< 1, 2 >
2 rows found.

ANY/ IN predicate (value list)

The ANY/IN quantified predicate compares an expression or list of expressions with a list of specified values. The ANY predicate evaluates to TRUE if one or more of the values in the ValueList relate to the expression or list of expressions as indicated by the comparison operator. Similarly, the IN predicate evaluates to TRUE if the expression or list of expressions is equal to one of the values in the list.

SQL syntax

RowValueConstructor {CompOp {ANY| SOME} | IN} ValueList

The syntax for RowValueConstructor:

RowValueConstructorElement | (RowValueConstuctorList) |

The syntax for RowValueConstructorList:

RowValueConstructorElement[{, RowValueConstructorElement} ... ]

The syntax for RowValueConstructorElement:

Expression | NULL

The syntax for CompOp:

{= | <> | > | >= | < | <= }

The syntax for more than one element in the ValueList:

({Constant | ? | :DynamicParameter} [,...] )

The syntax for one element in the ValueList not enclosed in parentheses:

Constant | ? | :DynamicParameter

The syntax for an empty ValueList:

( )

The syntax for the ValueList for a list of expressions:

(({Constant | ? | :DynamicParameter} [,...]))

Parameters

ComponentDescription
ExpressionSpecifies a value to be obtained. The values in ValueList must be compatible with the expression. For information on the syntax of expressions, see "Expression specification".
=
Is equal to.
<>Is not equal to.
>Is greater than.
>=Is greater than or equal to.
<
Is less than.
<=
Is less than or equal to.
{ANY|

SOME}

The predicate is TRUE if one or more of the values in the -ValueList relate to the expression or list of expressions as indicated by the comparison operator. SOME is a synonym for ANY.
ValueListA list of values that are compared against the expression's or list of expression's value. The ValueList cannot contain a column reference or a subquery. The ValueList can be nested if the left operand of the ValueList is a list.

Elements of the ValueList:

  • Constant—Indicates a specific value. See "Constants".

  • ?,:DynamicParameter—Placeholder for a dynamic parameter in a prepared SQL statement. The value of the dynamic parameter is supplied when the statement is executed.

  • Empty list, which are sometimes generated by SQL generation tools.


Description

  • If X is the value of Expression, and (a,b, ..., z) represents the elements in ValueList, and OP is a comparison operator, then the following is true:

    • X OP ANY (a,b,...,z) is equivalent to X OP a OR X OP b OR...OR X OP z.

  • If X is the value of Expression and (a,b,..., z) are the elements in a Value­List, then the following is true:

    • X IN (a,b,...,z) is equivalent to X = a OR X = b OR...OR X = z.

  • All character data types are compared in accordance with the current value of the NLS_SORT session parameter.

  • NULL cannot be specified in ValueList.

  • See "Numeric data types" for information about how TimesTen compares values of different but compatible types.

  • When evaluating an empty ValueList, the result of Expression IN is false.

Examples

Select all item numbers containing orders of 100, 200, or 300 items.

SELECT DISTINCT OrderItems.ItemNumber 
FROM OrderItems
WHERE OrderItems.Quantity = ANY (100, 200, 300)

Get part numbers of parts whose weight is 12, 16, or 17.

SELECT Parts.PartNumber FROM Parts 
WHERE Parts.Weight IN (12, 16, 17);

Get part number of parts whose serial number is '1123-P-01', '1733-AD-01', :SerialNumber or :SerialInd, where :SerialNumber and :SerialInd are dynamic parameters whose values are supplied at runtime.

SELECT PartNumber FROM Purchasing.Parts 
WHERE SerialNumber
IN ('1123-P-01', '1733-AD-01',:SerialNumber, :SerialInd);

To query an empty select list for IN condition:

SELECT * FROM t1 WHERE x1 IN ();

Illustrates the use of a list of expressions with in:

SELECT * FROM t1 WHERE (x1,y1) IN ((1,2), (3,4));

The following example illustrates the use of a list of expressions for the IN predicate. The query returns the department_name for departments with department_id = 240 and location_id = 1700.


Note:

The expression on the right side of the IN predicate must be enclosed in double parentheses (( )).

Command> SELECT department_name FROM departments 
       > WHERE (department_id, location_id) IN ((240,1700));
< Government Sales >
1 row found.

BETWEEN predicate

A BETWEEN predicate determines whether a value is:

  • Greater than or equal to a second value, and

  • Less than or equal to a third value.

The predicate evaluates to TRUE if a value falls within the specified range.

SQL syntax

Expression1 [NOT] BETWEEN Expression2 AND Expression3

Parameters

ParameterDescription
Expression1, Expression2, Expression3The syntax for expressions is defined in "Expression specification". Both numeric and non-numeric expressions are allowed in BETWEEN predicates, but all expressions must be compatible with each other.

Description

  • BETWEEN evaluates to FALSE and NOT BETWEEN evaluates to TRUE if the second value is greater than the third value.

  • Consult the following table if either Expression2 or Expression3 is NULL for BETWEEN or NOT BETWEEN:

    Expression2Expression3BETWEENNOT BETWEEN
    <= Expression1NULLNULLNULL
    > Expression1NULLFALSETRUE
    NULL>= Expression1NULLNULL
    NULL< Expression1NULLNULL

  • Expression2 and Expression3 constitute a range of possible values for which Expression2 is the lowest possible value and Expression3 is the highest possible value within the specified range. In the BETWEEN predicate, the low value must be specified first.

    Comparisons are conducted as described in "Comparison predicate".

  • The BETWEEN predicate is not supported for NCHAR types.

Examples

Parts sold for under $250.00 and over $1500.00 are discounted 25 percent.

UPDATE Purchasing.Parts 
SET SalesPrice = SalesPrice * 0.75
WHERE SalesPrice NOT BETWEEN 250.00 AND 1500.00;

Comparison predicate

A comparison predicate compares two expressions using a comparison operator. The predicate evaluates to TRUE if the first expression relates to the second expression as specified by the comparison operator.

SQL syntax

RowValueConstructor CompOp RowValueConstructor2

The syntax for RowValueConstructor:

RowValueConstructorElement | (RowValueConstuctorList) | ScalarSubquery

The syntax for RowValueConstructorList:

RowValueConstructorElement[{, RowValueConstructorElement} ... ]

The syntax for RowValueConstructor2 (one expression)

Expression

The syntax for RowValueConstructor2 (list of expressions)

((Expression[,...]))

The syntax for CompOp:

{= | <> | > | >= | < | <= }

Parameters

ComponentDescription
ExpressionThe syntax for expressions is defined under "Expression specification". Both numeric and non-numeric expressions are allowed in comparison predicates, but both expressions must be compatible with each other.
ScalarSubqueryA subquery that returns a single value. Scalar subqueries and their restrictions are defined under "Subqueries".
=
Is equal to.
<>Is not equal to.
>Is greater than.
>=Is greater than or equal to.
<
Is less than.
<=
Is less than or equal to.

Description

  • All character data types are compared in accordance with the current value of the NLS_SORT session parameter.

  • If RowValueConstructorList is specified only the operators = and <> are allowed.

  • See "Numeric data types" for information about how TimesTen compares values of different but compatible types.

  • If either side of a comparison predicate evaluates to UNKNOWN or NULL, this implies that neither the predicate nor the negation of the predicate is TRUE.

  • The NULL value itself can be used directly as an operand of an operator or predicate. For example, the (1 = NULL) comparison is supported. This is the same as if you cast NULL to the appropriate data type, as follows: (1 = CAST(NULL AS INT)). Both methods are supported and return the same results.

Examples

Retrieve part numbers of parts requiring fewer than 20 delivery days:

SELECT PartNumber FROM Purchasing.SupplyPrice 
WHERE DeliveryDays < 20;

The query returns the last_name of employees where salary=9500 and commission_pct=.25.


Note:

The expression on the right side of the equal sign must be enclosed in double parentheses (( )).

Command> SELECT last_name FROM employees 
       > WHERE(salary,commission_pct) = ((9500,.25));
< Bernstein >
1 row found.

The query returns the last_name of the employee whose manager_id = 205. The employee's department_id and manager_id is stored in both the employees and departments tables. A subquery is used to extract the information from the departments table.

Command> SELECT last_name FROM employees 
       > WHERE (department_id, manager_id) =
       > (SELECT department_id, manager_id FROM departments 
       > WHERE manager_id = 205);
< Gietz >
1 row found.

EXISTS predicate

An EXISTS predicate checks for the existence or nonexistence of a table subquery. The predicate evaluates to TRUE if the subquery returns at least one row for EXISTS and no rows for NOT EXISTS

SQL syntax

[NOT] EXISTS (Subquery)

Parameters

The EXISTS predicate has the following parameter:

ParameterDescription
SubqueryThe syntax of subqueries is defined under "Subqueries"

Description

  • When a subquery is introduced with EXISTS, the subquery functions as an existence test. EXISTS tests for the presence or absence of an empty set of rows. If the subquery returns at least one row, the subquery evaluates to true.

  • When a subquery is introduced with NOT EXISTS, the subquery functions as an absence test. NOT EXISTS tests for the presence or absence of an empty set of rows. If the subquery returns no rows, the subquery evaluates to true.

  • If join order is issued using the ttOptSetOrder built-in procedure that conflicts with the join ordering requirements of the NOT EXISTS subquery, the specified join order is ignored, TimesTen issues a warning and the query is executed.

  • The following table describes supported and unsupported usages of EXISTS and NOT EXISTS in TimesTen;

    Query/subquery descriptionNot ExistsExists
    Aggregates in subquerySupportedSupported
    Aggregates in main querySupportedSupported
    Subquery in OR clauseSupportedSupported
    Join ordering using the ttOptSetOrder built-in procedureLimited supportSupported

Examples

Get a list of customers having at least one unshipped order.

SELECT customers.name FROM customers
WHERE EXISTS (SELECT 1 FROM orders 
WHERE customers.id = orders.custid 
AND orders.status = 'unshipped');

Get a list of customers having no unshipped orders.

SELECT customers.name FROM customers
WHERE NOT EXISTS (SELECT 1 FROM orders 
WHERE customers.id = orders.custid 
AND orders.status = 'unshipped');

IS INFINITE predicate

An IS INFINITE predicate determines whether an expression is infinite (positive infinity (INF) or negative infinity (-INF)).

SQL syntax

Expression IS [NOT] INFINITE

Parameters

ParameterDescription
ExpressionExpression to test.

7`ȟ

Description

  • An IS INFINITE predicate evaluates to TRUE if the expression is positive or negative infinity.

  • An IS NOT INFINITE predicate evaluates to TRUE if expression is neither positive nor negative infinity.

  • The expression must either resolve to a numeric data type or to a data type that can be implicitly converted to a numeric data type.

  • Two positive infinity values are equal to each other. Two negative infinity values are equal to each other.

  • Expressions containing floating-point values may generate Inf, -Inf, or NaN. This can occur either because the expression generated overflow or exceptional conditions or because one or more of the values in the expression was Inf, -Inf, or NaN. Inf and NaN are generated in overflow or division by 0 conditions.

  • Inf, -Inf, and NaN values are not ignored in aggregate functions. NULL values are. If you want to exclude Inf and NaN from aggregates (or from any selection), use both the IS NOT NAN and IS NOT INFINITE predicates.

  • Negative infinity (-INF) sorts lower than all other values. Positive infinity (INF) sorts higher than all other values, but lower than NaN ("not a number") and the NULL value.

  • For more information on Inf and NaN, see "INF and NAN".


IS NAN predicate

An IS NAN predicate determines whether an expression is the undefined result of an operation (that is, is "not a number" or NaN).

SQL syntax

Expression IS [NOT] NAN

Parameters

ParameterDescription
ExpressionExpression to test.

Description

  • An IS NAN predicate evaluates to TRUE if the expression is "not a number."

  • An IS NOT NAN predicate evaluates to TRUE if expression is not "not a number."

  • The expression must either resolve to a numeric data type or to a data type that can be implicitly converted to a numeric data type.

  • Two NaN ("not a number") values are equal to each other.

  • Expressions containing floating-point values may generate Inf, -Inf, or NaN. This can occur either because the expression generated overflow or exceptional conditions or because one or more of the values in the expression was Inf, -Inf, or NaN. Inf and NaN are generated in overflow or division by 0 conditions.

  • Inf, -Inf, and NaN values are not ignored in aggregate functions. NULL values are. If you want to exclude Inf and NaN from aggregates (or from any selection), use both the IS NOT NAN and IS NOT INFINITE predicates.

  • NaN ("not a number") sorts higher than all other values including positive infinity, but lower than the NULL value.

  • For more information on Inf and NaN, see "INF and NAN".


IS NULL predicate

The IS NULL predicate determines whether an expression has the value NULL. The predicate evaluates to TRUE if the expression is NULL. If the NOT option is used, the predicate evaluates to TRUE if the expression is NOT NULL.

SQL syntax

{ColumnName | Constant | Expression | LOBDataType} IS [NOT] NULL

Parameters

ParameterDescription
ColumnNameThe name of a column from which a value is to be taken. Column names are discussed in Chapter 2, "Names, Namespace and Parameters".
ConstantA specific value. See "Constants".
ExpressionExpression to test.
LOBDataTypeValue to test that is in a CLOB, BLOB, or NCLOB data type.

Examples

Use IS NULL to identify the president of the company, who is the only person without a manager.

Command> SELECT * FROM employees 
 > WHERE manager_id IS NULL;
< 100, Steven, King, SKING, 515.123.4567, 1987-06-17 00:00:00, AD_PRES, 24000, 
<NULL>, <NULL>, 90 >
1 row found.

The following statement uses IS NULL to identify all locations without a state or province.

Command> SELECT * FROM locations
       > WHERE state_province IS NULL;
< 1000, 1297 Via Cola di Rie, 00989, Roma, <NULL>, IT >
< 1100, 93091 Calle della Testa, 10934, Venice, <NULL>, IT >
< 1300, 9450 Kamiya-cho, 6823, Hiroshima, <NULL>, JP >
< 2000, 40-5-12 Laogianggen, 190518, Beijing, <NULL>, CN >
< 2300, 198 Clementi North, 540198, Singapore, <NULL>, SG >
< 2400, 8204 Arthur St, <NULL>, London, <NULL>, UK >
6 rows found.

LIKE predicate

A LIKE predicate evaluates to TRUE if the source contains a given pattern. The LIKE predicate matches a portion of one character value to another by searching the source for the pattern specified.

SQL syntax

Source [NOT] LIKE Pattern 
 [ESCAPE {'EscapeChar' | {? | :DynamicParameter} }]

The syntax for Pattern is as follows:

Expression [ || Expression ] [ ... ]

Parameters

ParameterDescription
SourceThis source is searched for all occurances of the pattern. The source may be an expression, column, character string resulting from a function, or any combination of these that results in a character string used for the source on which the pattern is matched. The source can be a CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. For more information on expressions, see Chapter 3, "Expressions". For more information on searching within a national character string within NCHAR, NVARCHAR, or NCLOB, see "Pattern matching for strings of NCHAR, NVARCHAR2, and NCLOB data types".
PatternDescribes a character pattern that you are searching for in the source with one or more expressions. The data type of the pattern should be a character string data type, such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.

Multiple expressions may be concatenated to form the character string used for the pattern.

The pattern consists of characters including digits and special characters. For example, NAME LIKE 'Annie' evaluates to TRUE only for a name of Annie with no spaces.

You can also use the predicate to test for a partial match by using one or more of the following symbols:

_ Represents any single character.

For example: BOB and TOM both satisfy the predicate NAME LIKE '_O_'.

% Represents any string of zero or more characters.

For example, MARIE and RENATE both satisfy the predicate NAME LIKE '%A%'.

You can use the _ or % symbols multiple times and in any combination in a pattern. However, you cannot use the symbols literally within a pattern unless you use the ESCAPE clause and precede the symbols with the escape character, described by the EscapeChar parameter.

ExpressionAny expression included in the pattern may be a column, a dynamic parameter, or the result of a function that evaluates to a character string. The syntax for expressions is defined in "Expression specification".
EscapeCharDescribes an optional escape character which can be used to interpret the symbols _ and % literally in the pattern.

The escape character must be a single character. When it appears in the pattern, it must be followed by the escape character itself, the _ symbol or the % symbol. Each such pair represents a single literal occurrence of the second character in the pattern. The escape character is always case sensitive. The escape character cannot be _ or %.

?

DynamicParameter

Indicates a dynamic parameter in a prepared SQL statement. The parameter value is supplied when the statement is executed.

Description

  • As long as no escape character is specified, the _ or % symbols in the pattern act as wild card characters. If an escape character is specified, the wild card or escape character that follows is treated literally. If the character following an escape character is not a wild card or the escape character, an error results.

  • When providing a combination of expressions, columns, character strings, dynamic parameters, or function results to make up the pattern, you can concatenate items together using the || operator to form the final pattern.

  • Case is significant in all conditions comparing character expressions that use the LIKE predicate.

  • If the value of the expression, the pattern, or the escape character is NULL, the LIKE predicate evaluates to NULL.

  • The LIKE predicate may be slower when used on a multibyte character set.

  • For more information on searching within a national character string within NCHAR, NVARCHAR, or NCLOB, see "Pattern matching for strings of NCHAR, NVARCHAR2, and NCLOB data types".

Examples

Find employees whose last name begins with 'Sm'.

Command> SELECT employee_id, last_name,first_name FROM employees
       > WHERE last_name LIKE 'Sm%'
       > ORDER BY employee_id,last_name,first_name;
< 159, Smith, Lindsey >
< 171, Smith, William >
2 rows found.

Find employees whose last name begins with 'SM'. This query returns no results because there are no employees whose last_name begins with upper case 'SM'.

Command> SELECT employee_id, last_name,first_name from employees
       > WHERE last_name LIKE 'SM%' 
       > ORDER BY employee_id,last_name,first_name;
0 rows found.

However, by upper casing the source value of the last name column, you can find all names that begin with 'SM'.

Command> SELECT employee_id, last_name, first_name FROM employees 
 > WHERE UPPER(last_name) LIKE ('SM%');
< 159, Smith, Lindsey >
< 171, Smith, William >
2 rows found.

Use a dynamic parameter denoted by ? to find employees whose last name begins with 'Sm' at execution time.

Command> SELECT employee_id, last_name,first_name FROM employees
       > WHERE last_name like ?
       > ORDER BY employee_id,last_name,first_name;
 
Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.
 
Enter Parameter 1 '_QMARK_1' (VARCHAR2) > 'Sm%'
< 159, Smith, Lindsey >
< 171, Smith, William >
2 rows found.

Use a bind variable denoted by :a to find employees whose last name begins with 'Sm' at execution time.

Command> SELECT employee_id, last_name,first_name FROM employees 
       > WHERE last_name LIKE :a 
       > ORDER BY employee_id,last_name,first_name;
 
Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.
 
Enter Parameter 1 'A' (VARCHAR2) > 'Sm%'
< 159, Smith, Lindsey >
< 171, Smith, William >
2 rows found.

For employees whose last name begins with 'Smit', find the last name of the manager. Display the first name and last name of the employee and the last name of the manager.

Command> SELECT e1.first_name || ' ' || e1.last_name||' works for '||e2.last_name
       >    FROM employees e1, employees e2
       >    WHERE e1.manager_id = e2.employee_id
       >    AND e1.last_name like 'Smit';
< Lindsey Smith works for Partners >
< William Smith works for Cambrault >
2 rows found.

This query pattern references the last_name column as the pattern for which to search:

Command> SELECT e1.first_name || ' ' || e1.last_name||
> ' works for ' || e2.last_name
> FROM employees e1, employees e2
> WHERE e1.manager_id = e2.employee_id
> AND 'Smith' like e1.last_name;
< Lindsey Smith works for Partners >
< William Smith works for Cambrault >
2 rows found.

The pattern can be a column or the result of a function. The following uses the UPPER function on both the source last_name column as well as the 'ma' search string for which you are searching:

Command> SELECT last_name, first_name FROM employees
       > WHERE upper(last_name) LIKE UPPER('ma%');
< Markle, Steven >
< Marlow, James >
< Mallin, Jason >
< Matos, Randall >
< Marvins, Mattea >
< Mavris, Susan >
6 rows found.

The following query demonstrates using a dynamic parameter to request the pattern.

Command> SELECT first_name || ' ' || last_name 
 > FROM employees WHERE last_name like ?;
 
Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.
 
Enter Parameter 1 '_QMARK_1' (VARCHAR2) > 'W%'
< Matthew Weiss >
< Alana Walsh >
< Jennifer Whalen >
3 rows found.

The following query demonstrates combining a character string with a dynamic parameter in the pattern.

Command> SELECT first_name || ' ' || last_name 
 > FROM employees WHERE last_name like 'W' || ?;
 
Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.
 
Enter Parameter 1 '_QMARK_1' (VARCHAR2) > '%'
< Matthew Weiss >
< Alana Walsh >
< Jennifer Whalen >
3 rows found.

Pattern matching for strings of NCHAR, NVARCHAR2, and NCLOB data types

The LIKE predicate can be used for pattern matching for strings of type NCHAR, NVARCHAR2, and NCLOB. The pattern matching characters are:

CharacterDescription
U+005F SPACING UNDERSCORERepresents any single Unicode character.
U+0025 PERCENT SIGNRepresents any string of zero or more Unicode characters.

Description

  • The escape character is similarly supported as a single Unicode character or parameter.

  • The types of the LIKE operands can be any combination of character types.

  • Case-insensitive and accent-insensitive NLS_SORT is supported with the LIKE predicate.

Examples

In these examples, the Unicode character U+0021 EXCLAMATION MARK is being used to escape the Unicode character U+005F SPACING UNDERSCORE. Unicode character U+0025 PERCENT SIGN is not escaped, and assumes its pattern matching meaning.

VendorName is an NCHAR or NVARCHAR2 column.

SELECT VendorName FROM Purchasing.Vendors
WHERE VendorName LIKE N'ACME!_%' ESCAPE N'!';

This example is equivalent:

SELECT VendorName FROM Purchasing.Vendors
WHERE VendorName LIKE N'ACME!\u005F\u0025' ESCAPE N'!';
PKbxF`7`PK*A OEBPS/toc.htm\J Table of Contents

Contents

Title and Copyright Information

Preface

What's New

1 Data Types

2 Names, Namespace and Parameters

3 Expressions

4 Functions

5 Search Conditions

6 SQL Statements

7 Privileges

8 Reserved Words

Index

PKdTaJ\JPK*AOEBPS/state.htm SQL Statements

6 SQL Statements

This chapter provides information about the SQL statements available in TimesTen.

SQL statements are generally considered to be either Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements.

DML statements modify database objects. INSERT, UPDATE and DELETE are examples of DML statements.

DDL statements modify the database schema. CREATE TABLE and DROP TABLE are examples of DDL statements.

Comments within SQL statements

A comment can appear between keywords, parameters, or punctuation marks in a statement. You can include a comment in a statement in two ways:

  • Begin the comment with a slash and an asterisk (/*). Proceed with the text of the comment. The text can span multiple lines. End the comment with an asterisk and a slash. (*/). You do not need to separate the opening and terminating characters from the text by a space or line break.

  • Begin the comment with two hyphens (--). Proceed with the text of the comment. The text cannot extend to a new line. End the comment with a line break.


ALTER ACTIVE STANDBY PAIR

You can change an active standby pair by:

  • Adding or dropping a subscriber database

  • Altering store attributes. Only the PORT and TIMEOUT attributes can be set for subscribers.

  • Including tables, sequences or cache groups in the replication scheme

  • Excluding tables, sequences or cache groups from the replication scheme

See "Making other changes to an active standby pair" in Oracle TimesTen In-Memory Database Replication Guide.

Required privilege

ADMIN

SQL syntax

ALTER ACTIVE STANDBY PAIR { 
      SubscriberOperation | 
      StoreOperation | InclusionOperation |
      NetworkOperation } [...]

Syntax for SubscriberOperation:

{ADD | DROP } SUBSCRIBER FullStoreName

Syntax for StoreOperation:

ALTER STORE FullStoreName SET StoreAttribute

Syntax for InclusionOperation:

    [{ INCLUDE | EXCLUDE }{TABLE [[Owner.]TableName [,...]]|
         CACHE GROUP [[Owner.]CacheGroupName [,...]]|
         SEQUENCE [[Owner.]SequenceName [,...]]} [,...]]

Syntax for NetworkOperation:

ADD ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
      { { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost }
          PRIORITY Priority } [...] 
DROP ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
      { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost } [...] 

Parameters

ParameterDescription
ADD SUBSCRIBER FullStoreNameIndicates a subscriber database. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
DROP SUBSCRIBER FullStoreNameIndicates that updates should no longer be sent to the specified subscriber database. This operation fails if the replication scheme has only one subscriber. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
ALTER STORE FullStoreName SET StoreAttributeIndicates changes to the attributes of a database. Only the PORT and TIMEOUT attributes can be set for subscribers. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.

For information on StoreAttribute clauses, see "CREATE ACTIVE STANDBY PAIR".

FullStoreNameThe database, specified as one of the following:
  • SELF

  • The prefix of the database file name

For example, if the database path is directory/subdirectory/data.ds0, then data is the database name that should be used.

This is the database file name specified in the DataStore attribute of the DSN description with optional host ID in the form:

DataStoreName [ON Host]

Host can be either an IP address or a literal host name assigned to one or more IP addresses, as described in "Configuring host IP addresses" in Oracle TimesTen In-Memory Database Replication Guide. Host names containing special characters must be surrounded by double quotes. For example: "MyHost-500".

{INCLUDE|EXCLUDE}

{[TABLE [Owner.]TableName[,...]|

CACHE GROUP

[[Owner.]CacheGroupName]|[,...]

SEQUENCE [[Owner.]SequenceName [,...]}

[,...]

Includes in or excludes from replication the tables, sequences or cache groups listed.

INCLUDE adds the tables, sequences or cache groups to replication. Use one INCLUDE clause for each object type (table, sequence or cache group).

EXCLUDE removes the tables, sequences or cache groups from replication. Use one EXCLUDE clause for each object type (table, sequence or cache group).

ADD ROUTE MASTER FullStoreName SUBSCRIBER FullStoreNameAdds NetworkOperation to replication scheme. Enables you to control the network interface that a master store uses for every outbound connection to each of its subscriber stores. In the context of the ADD ROUTE clause, each master database is a subscriber of the other master database and each read-only subscriber is a subscriber of both master databases.

Can be specified more than once.

For FullStoreName, "ON host" must be specified.

DROP ROUTE MASTER FullStoreName SUBSCRIBER FullStoreNameDrops NetworkOperation from replication scheme.

Can be specified more than once.

For FullStoreName, "ON host" must be specified.

MASTERIP MasterHost | SUBSCRIBERIP SubscriberHostMasterHost and SubscriberHost are the IP addresses for the network interface on the master and subscriber stores. Specify in dot notation or canonical format or in colon notation for IPV6.

Clause can be specified more than once. Valid for both ADD and DROP ROUTE MASTER.

PRIORITY PriorityVariable expressed as an integer from 1 to 99. Denotes the priority of the IP address. Lower integral values have higher priority. An error is returned if multiple addresses with the same priority are specified. Controls the order in which multiple IP addresses are used to establish peer connections.

Required syntax of NetworkOperation clause. Follows MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost clause.


Description

  • You must stop the replication agent before altering an active standby pair. The exceptions are for those objects and statements that are automatically replicated and included based on the values of the DDL_REPLICATION_LEVEL and DDL_REPLICATION_ACTION attributes, as described in "ALTER SESSION".

  • You may only alter the active standby pair replication scheme on the active database. See "Making other changes to an active standby pair" in Oracle TimesTen In-Memory Database Replication Guide for more information.

  • You may not use ALTER ACTIVE STANDBY PAIR when using Oracle Clusterware with TimesTen. See "Restricted commands and SQL statements" in Oracle TimesTen In-Memory Database Replication Guide for more information.

    Instead, perform the tasks described in "Changing the schema" section of the Oracle TimesTen In-Memory Database Replication Guide.

  • Use ADD SUBSCRIBER FullStoreName to add a subscriber to the replication scheme.

  • Use DROP SUBSCRIBER FullStoreName to drop a subscriber from the replication scheme.

  • Use ALTER STORE FullStoreName SET StoreAttribute to change the attributes for the specified database. Only the PORT and TIMEOUT attributes can be set for subscribers.

  • Use the INCLUDE or EXCLUDE clause to include the listed tables, sequences or cache groups in the replication scheme or to exclude them from the replication scheme. Use one INCLUDE or EXCLUDE clause for each object type (table, sequence or cache group). The ALTER ACTIVE STANDBY statement is not necessary for those objects and statements that are automatically replicated and included based on the values of the DDL_REPLICATION_LEVEL and DDL_REPLICATION_ACTION attributes, as described in "ALTER SESSION". However, if DDL_REPLICATION_LEVEL=2 and DDL_REPLICATION_ACTION="EXCLUDE," use the INCLUDE clause to include replicated objects into the replication scheme.

  • When DDL_REPLICATION_LEVEL=2, the INCLUDE clause can only be used with empty tables on the active database. The contents of the corresponding tables on the standby and any subscribers will be truncated before the table is added to the replication scheme.

Examples

Add a subscriber to the replication scheme.

ALTER ACTIVE STANDBY PAIR
    ADD SUBSCRIBER rep4;

Drop two subscribers from the replication scheme.

ALTER ACTIVE STANDBY PAIR
    DROP SUBCRIBER rep3
    DROP SUBSCRIBER rep4;

Alter the store attributes of the rep3 and rep4 databases.

ALTER ACTIVE STANDBY PAIR
    ALTER STORE rep3 SET PORT 23000 TIMEOUT 180
    ALTER STORE rep4 SET PORT 23500 TIMEOUT 180;

Add a table, a sequence and two cache groups to the replication scheme.

ALTER ACTIVE STANDBY PAIR
    INCLUDE TABLE my.newtab
    INCLUDE SEQUENCE my.newseq
    INCLUDE CACHE GROUP my.newcg1, my.newcg2;

Add NetworkOperation clause to active standby pair:

ALTER ACTIVE STANDBY PAIR
ADD ROUTE MASTER rep1 ON "machine1" SUBSCRIBER rep2 ON "machine2"
MASTERIP "1.1.1.1" PRIORITY 1 SUBSCRIBERIP "2.2.2.2" PRIORITY 1;

See also


CREATE ACTIVE STANDBY PAIR
DROP ACTIVE STANDBY PAIR

ALTER CACHE GROUP

The ALTER CACHE GROUP statement enables changes to the state, interval and mode of AUTOREFRESH.

Updates on Oracle tables can be propagated back to the TimesTen cache group with the use of AUTOREFRESH. AUTOREFRESH can be enabled when the cache group is a user managed cache group or is defined as READONLY with an AUTOREFRESH clause.

Any values or states set by ALTER CACHE GROUP are persistent. They are stored in the database and survive daemon and cache agent restarts.

For a description of cache group types, see "User managed and system managed cache groups".

Required privilege

No privilege is required for the cache group owner.

ALTER ANY CACHE GROUP for another user's cache group.

SQL syntax

This statement changes the AUTOREFRESH mode of the cache group, which determines which rows are updated during an autorefresh operation:

ALTER CACHE GROUP [Owner.]GroupName
        SET AUTOREFRESH MODE
        {INCREMENTAL | FULL}

This statement changes the AUTOREFRESH interval on the cache group:

ALTER CACHE GROUP [Owner.]GroupName 
        SET AUTOREFRESH INTERVAL IntervalValue 
        {MINUTE[S] | SECOND[S] | MILLISECOND[S] }

This statement alters the AUTOREFRESH state:

ALTER CACHE GROUP [Owner.]GroupName 
        SET AUTOREFRESH STATE
        {ON | OFF | PAUSED}

Parameters

ParameterDescription
[Owner.]GroupNameName assigned to the new cache group.
AUTOREFRESHIndicates that changes to Oracle tables should be automatically propagated to TimesTen. For details, see "AUTOREFRESH in cache groups".
MODEDetermines which rows in the cache are updated during an autorefresh. If the INCREMENTAL clause is specified, TimesTen refreshes only rows that have been changed on Oracle since the last propagation. If the FULL clause is specified or if there is neither FULL nor INCREMENTAL clause specified, TimesTen updates all rows in the cache with each autorefresh. The default mode is INCREMENTAL.
INTERVAL

IntervalValue

Indicates the interval at which autorefresh should occur in units of minutes, seconds or milliseconds. An integer value that specifies how often AUTOREFRESH should be scheduled, in minutes, seconds or milliseconds. The default value is 10 minutes. If the specified interval is not long enough for an AUTOREFRESH to complete, a runtime warning is generated and the next AUTOREFRESH waits until the current one finishes. An informational message is generated in the support log if the wait queue reaches 10.
STATESpecifies whether AUTOREFRESH should be changed to on, off or paused. By default, the AUTOREFRESH STATE is ON.
ONAUTOREFRESH is scheduled to occur at the specified interval.
OFFA scheduled AUTOREFRESH is cancelled, and TimesTen does not try to maintain the information necessary for an INCREMENTAL refresh. Therefore if AUTOREFRESH is turned on again at a later time, the first refresh is FULL.
PAUSEDA scheduled AUTOREFRESH is cancelled, but TimesTen tries to maintain the information necessary for an INCREMENTAL refresh. Therefore if AUTOREFRESH is turned on again at a later time, a full refresh may not be necessary.

Description

  • A refresh does not occur immediately after issuing ALTER CACHE GROUP...SET AUTOREFRESH STATE. This statement only changes the state of AUTOREFRESH. When the transaction that contains the ALTER CACHE GROUP statement is committed, the cache agent is notified to schedule an AUTOREFRESH immediately, but the commit goes through without waiting for the completion of the refresh. The scheduling of the autorefresh operation is part of the transaction, but the refresh itself is not.

  • If you issue an ALTER CACHE GROUP... SET AUTOREFRESH STATE OFF statement and there is an autorefresh operation currently running, then:

    • If LockWait interval is 0, the ALTER statement fails with a lock timeout error.

    • If LockWait interval is non-zero, then the current autorefresh transaction is rolled back, and the ALTER statement continues. This affects all cache groups with the same autorefresh interval.

  • Replication cannot occur between cache groups with AUTOREFRESH and cache groups without AUTOREFRESH.

  • If the ALTER CACHE GROUP statement is part of a transaction that is being replicated, and if the replication scheme has the RETURN TWOSAFE attribute, the transaction may fail.

  • You cannot execute the ALTER CACHE GROUP statement when performed under the serializable isolation level. An error message is returned when attempted.

See also


CREATE CACHE GROUP

ALTER FUNCTION

The ALTER FUNCTION statement recompiles a standalone stored function. Explicit recompilation eliminates the need for implicit runtime recompilation and prevents associated runtime compilation errors and performance overhead.

To recompile a function that is part of a package, recompile the package using the ALTER PACKAGE statement.

Required privilege

No privilege is required for the PL/SQL function owner.

ALTER ANY PROCEDURE for another user's function.

SQL syntax

ALTER FUNCTION [Owner.]FunctionName COMPILE
      [CompilerParametersClause [...]] 
      [REUSE SETTINGS] 

Parameters

ParameterDescription
[Owner.]FunctionNameName of the function to be recompiled.
COMPILERequired keyword that causes recompilation of the function. If the function does not compile successfully, use the ttIsql command SHOW ERRORS to display the compiler error messages.
CompilerParametersClauseUse this optional clause to specify a value for one of the PL/SQL persistent compiler parameters. The PL/SQL persistent compiler parameters are PLSQL_OPTIMIZE_LEVEL, PLSCOPE_SETTINGS and NLS_LENGTH_SEMANTICS.

You can specify each parameter once in the statement.

If you omit a parameter from this clause and you specify REUSE SETTINGS, then if a value was specified for the parameter in an earlier compilation, TimesTen uses that earlier value. If you omit a parameter and either you do not specify REUSE SETTINGS or no value has been specified for the parameter in an earlier compilation, then TimesTen obtains the value for the parameter from the session environment.

REUSE SETTINGSUse this optional clause to prevent TimesTen from dropping and reacquiring compiler switch settings. When you specify REUSE SETTINGS, TimesTen preserves the existing settings and uses them for the compilation of any parameters for which values are not specified.

Description

  • The ALTER FUNCTION statement does not change the declaration or definition of an existing function. To redeclare or redefine a function, use the CREATE FUNCTION statement.

  • TimesTen first recompiles objects upon which the function depends, if any of those objects are invalid.

  • TimesTen also invalidates any objects that depend on the function, such as functions that call the recompiled function or package bodies that define functions that call the recompiled function.

  • If TimesTen recompiles the function successfully, then the function becomes valid. If recompiling the function results in compilation errors, then TimesTen returns an error and the function remains invalid. Use the ttIsql command SHOW ERRORS to display compilation errors.

  • During recompilation, TimesTen drops all persistent compiler settings, retrieves them again from the session, and stores them at the end of compilation. To avoid this process, specify the REUSE SETTINGS clause.

See also


CREATE FUNCTION

ALTER PACKAGE

The ALTER PACKAGE statement explicitly recompiles a package specification, package body, or both. Explicit recompilation eliminates the need for implicit runtime recompilation and prevents associated runtime compilation errors.

This statement recompiles all package objects together. You cannot use the ALTER PROCEDURE or ALTER FUNCTION statement to individually recompile a procedure or function that is part of a package.

Required privilege

No privilege is required for the package owner.

ALTER ANY PROCEDURE for another user's package.

SQL syntax

ALTER PACKAGE [Owner.]PackageName COMPILE
      [PACKAGE|SPECIFICATION|BODY]
      [CompilerParametersClause [...]] 
      [REUSE SETTINGS] 

Parameters

ParameterDescription
[Owner.]PackageNameName of the package to be recompiled.
COMPILERequired clause used to force the recompilation of the package specification, package body, or both.
[PACKAGE|SPECIFICATION|BODY]Specify PACKAGE to recompile both the package specification and the body. Specify SPECIFICATION to recompile the package specification. Specify BODY to recompile the package body.

PACKAGE is the default.

CompilerParametersClauseUse this optional clause to specify a value for one of the PL/SQL persistent compiler parameters. The PL/SQL persistent compiler parameters are PLSQL_OPTIMIZE_LEVEL, PLSCOPE_SETTINGS and NLS_LENGTH_SEMANTICS.

You can specify each parameter once in the statement.

If you omit a parameter from this clause and you specify REUSE SETTINGS, then if a value was specified for the parameter in an earlier compilation, TimesTen uses that earlier value. If you omit a parameter and either you do not specify REUSE SETTINGS or no value has been specified for the parameter in an earlier compilation, then TimesTen obtains the value for the parameter from the session environment.

REUSE SETTINGSUse this optional clause to prevent TimesTen from dropping and reacquiring compiler switch settings. When you specify REUSE SETTINGS, TimesTen preserves the existing settings and uses them for the compilation of any parameters for which values are not specified.

Description

  • When you recompile a package specification, TimesTen invalidates local objects that depend on the specification, such as procedures that call procedures or functions in the package. The body of the package also depends on the specification. If you subsequently reference one of these dependent objects without first explicitly recompiling it, then TimesTen recompiles it implicitly at runtime.

  • When you recompile a package body, TimesTen does not invalidate objects that depend on the package specification. TimesTen first recompiles objects upon which the body depends, if any of those objects are invalid. If TimesTen recompiles the body successfully, then the body become valid.

  • When you recompile a package, both the specification and the body are explicitly recompiled. If there are no compilation errors, then the specification and body become valid. If there are compilation errors, then TimesTen returns an error and the package remains invalid.

See also


CREATE PACKAGE

ALTER PROCEDURE

The ALTER PROCEDURE statement recompiles a standalone stored procedure. Explicit recompilation eliminates the need for implicit runtime recompilation and prevents associated runtime compilation errors and performance overhead.

To recompile a procedure that is part of a package, recompile the package using the ALTER PACKAGE statement.

Required privilege

No privilege is required for the procedure owner.

ALTER ANY PROCEDURE for another user's procedure.

SQL syntax

ALTER PROCEDURE [Owner.]ProcedureName COMPILE
      [CompilerParametersClause [...]] 
      [REUSE SETTINGS] 

Parameters

ParameterDescription
[Owner.]ProcedureNameName of the procedure to be recompiled.
COMPILERequired keyword that causes recompilation of the procedure. If the procedure does not compile successfully, use the ttIsql command SHOW ERRORS to display the compiler error messages.
CompilerParametersClauseUse this optional clause to specify a value for one of the PL/SQL persistent compiler parameters. The PL/SQL persistent compiler parameters are PLSQL_OPTIMIZE_LEVEL, PLSCOPE_SETTINGS and NLS_LENGTH_SEMANTICS.

You can specify each parameter once in the statement.

If you omit a parameter from this clause and you specify REUSE SETTINGS, then if a value was specified for the parameter in an earlier compilation, TimesTen uses that earlier value. If you omit a parameter and either you do not specify REUSE SETTINGS or no value has been specified for the parameter in an earlier compilation, then TimesTen obtains the value for the parameter from the session environment.

REUSE SETTINGSUse this optional clause to prevent TimesTen from dropping and reacquiring compiler switch settings. When you specify REUSE SETTINGS, TimesTen preserves the existing settings and uses them for the compilation of any parameters for which values are not specified.

Description

  • The ALTER PROCEDURE statement does not change the declaration or definition of an existing procedure. To redeclare or redefine a procedure, use the CREATE PROCEDURE statement.

  • TimesTen first recompiles objects upon which the procedure depends, if any of those objects are invalid.

  • TimesTen also invalidates any objects that depend on the procedure, such as procedures that call the recompiled procedure or package bodies that define procedures that call the recompiled procedure.

  • If TimesTen recompiles the procedure successfully, then the procedure becomes valid. If recompiling the procedure results in compilation errors, then TimesTen returns an error and the procedure remains invalid. Use the ttIsql command SHOW ERRORS to display compilation errors.

  • During recompilation, TimesTen drops all persistent compiler settings, retrieves them again from the session, and stores them at the end of compilation. To avoid this process, specify the REUSE SETTINGS clause.

Examples

Query the system view USER_PLSQL_OBJECT_SETTINGS to check PLSQL_OPTIMIZE_LEVEL and PLSCOPE_SETTINGS for procedure query_emp. Alter query_emp by changing PLSQL_OPTIMIZE_LEVEL to 3. Verify results.

Command> SELECT PLSQL_OPTIMIZE_LEVEL, PLSCOPE_SETTINGS
       > FROM user_plsql_object_settings WHERE  name = 'QUERY_EMP';
< 2, IDENTIFIERS:NONE >
1 row found.

Command> ALTER PROCEDURE query_emp COMPILE PLSQL_OPTIMIZE_LEVEL = 3;
 
Procedure altered.
 
Command> SELECT PLSQL_OPTIMIZE_LEVEL, PLSCOPE_SETTINGS
       > FROM user_plsql_object_settings WHERE  name = 'QUERY_EMP';
< 3, IDENTIFIERS:NONE >
1 row found.

See also


CREATE PROCEDURE

ALTER REPLICATION

The ALTER REPLICATION statement adds, alters, or drops replication elements and changes the replication attributes of participating databases.

Most ALTER REPLICATION operations are supported only when the replication agent is stopped (ttAdmin -repStop). However, it is possible to dynamically add a subscriber database to a replication scheme while the replication agent is running. See "Altering Replication" in Oracle TimesTen In-Memory Database Replication Guide for more information.

Required privilege

ADMIN

SQL syntax

The ALTER REPLICATION statement has the syntax:

ALTER REPLICATION [Owner.]ReplicationSchemeName
  ElementOperation [...] | StoreOperation |
     NetworkOperation [...]

Specify ElementOperation one or more times:

ADD ELEMENT ElementName
   { DATASTORE | 
     { TABLE [Owner.]TableName [CheckConflicts] } | 
       SEQUENCE [Owner.]SequenceName }
   { MASTER | PROPAGATOR } FullStoreName
   { SUBSCRIBER FullStoreName [,... ] [ReturnServiceAttribute] } [ ... ] }
   { INCLUDE | EXCLUDE }
   { TABLE [[Owner.]TableName[,...]] | 
     CACHE GROUP [[Owner.]CacheGroupName[,...]] | 
     SEQUENCE [[Owner.]SequenceName[,...]] } [,...]

ALTER ELEMENT { ElementName | * IN FullStoreName ]
    ADD SUBSCRIBER FullStoreName [,...] [ReturnServiceAttribute] |
        ALTER SUBSCRIBER FullStoreName [,...]   |
            SET [ReturnServiceAttribute]   |
        DROP SUBSCRIBER FullStoreName [,... ]

ALTER ELEMENT * IN FullStoreName
    SET { MASTER | PROPAGATOR } FullStoreName

ALTER ELEMENT ElementName
    {SET NAME NewElementName | SET CheckConflicts}

ALTER ELEMENT ElementName 
    { INCLUDE | EXCLUDE } { TABLE [Owner.]TableName |
          CACHE GROUP [Owner.]CacheGroupName | 
          SEQUENCE [Owner.]SequenceName }[,...] 

DROP ELEMENT { ElementName | * IN FullStoreName }

CheckConflicts can only be set when replicating TABLE elements. The syntax is described in "CHECK CONFLICTS".

Syntax for ReturnServiceAttribute is:

{ RETURN RECEIPT [BY REQUEST] | NO RETURN }

StoreOperation clauses:

ADD STORE FullStoreName [StoreAttribute [... ]]
ALTER STORE FullStoreName SET StoreAttribute [... ]

Syntax for the StoreAttribute is:

[DISABLE RETURN {SUBSCRIBER | ALL} NumFailures]
[RETURN SERVICES {ON | OFF} WHEN [REPLICATION] STOPPED]
[DURABLE COMMIT {ON | OFF}]
[RESUME RETURN MilliSeconds ]
[LOCAL COMMIT ACTION {NO ACTION| COMMIT}]
[RETURN WAIT TIME Seconds]
[COMPRESS TRAFFIC {ON | OFF} ]
[PORT PortNumber ]
[TIMEOUT Seconds ]
[FAILTHRESHOLD Value]
[CONFLICT REPORTING SUSPEND AT Value ]
[CONFLICT REPORTING RESUME AT Value ]
[TABLE DEFINITION CHECKING {EXACT|RELAXED}]

Specify NetworkOperation one or more times:

ADD ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
  { { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost }
      PRIORITY Priority } [...] 

DROP ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
  { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost } [...] 

Parameters

ParameterDescription
[Owner.]ReplicationSchemeNameName assigned to the replication scheme.
ADD ELEMENT ElementNameAdds a new element to the existing replication scheme. ElementName is an identifier of up to 30 characters. With DATASTORE elements, the ElementName must be unique with respect to other DATASTORE element names within the first 20 chars.

If the element is a DATASTORE, all tables and cache groups are included in the database. SEQUENCE elements that are part of the database do not have their return services modified by this statement.

ADD ELEMENT ElementName DATASTORE

{INCLUDE | EXCLUDE}

{TABLE [[Owner.]TableName [,...]]|

CACHE GROUP [[Owner.]CacheGroupName [,...]]|

SEQUENCE [[Owner.]SequenceName[,...]]} [,...]

Adds a new DATASTORE element to the existing replication scheme. ElementName is an identifier of up to 30 characters. With DATASTORE elements, the ElementName must be unique with respect to other DATASTORE element names within the first 20 chars.

INCLUDE includes in the database only the tables and cache groups listed. Use one INCLUDE clause for each object type (table, cache group or sequence).

EXCLUDE includes in the database all tables and cache groups except the tables, cache groups and sequences listed. Use one EXCLUDE clause for each object type (table, cache group or sequence).

If the element is a sequence, RETURN attributes are not applied, no conflict checking is supported and sequences that cycle return an error.

ADD SUBSCRIBER FullStoreNameIndicates an additional subscriber database. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
ALTER ELEMENT * IN FullStoreName

SET { MASTER | PROPAGATOR } FullStoreName

Makes a change to all elements for which FullStoreName is the MASTER or PROPAGATOR. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.

This syntax can be used on a set of element names to:

  • Add, alter, or drop subscribers.

  • Set the MASTER or PROPAGATOR status of the element set.

SEQUENCE elements that are part of the database being altered do not have their return services modified by this statement.

ALTER ELEMENT ElementNameName of the element to which a subscriber is to be added or dropped.
ALTER ELEMENT

ElementName1

SET NAME ElementName2

Renames ElementName1 with the name ElementName2. You can only rename elements of type TABLE.
ALTER ELEMENT ElementName

{INCLUDE|EXCLUDE}

{TABLE [Owner.]TableName |

CACHE GROUP [Owner.]CacheGroupName |

SEQUENCE [Owner.]SequenceName} [,...]

ElementName is the name of the element to be altered.

INCLUDE adds to the database the tables and cache groups listed. Use one INCLUDE clause for each object type (table or cache group).

EXCLUDE removes from the database the tables and cache groups listed. Use one EXCLUDE clause for each object type (table, cache group or sequence).

If the element is a sequence, RETURN attributes are not applied, no conflict checking is supported and sequences that cycle return an error.

ALTER SUBSCRIBER FullStoreName

SET RETURN RECEIPT

[BY REQUEST]|NO RETURN

Indicates an alteration to a subscriber database to enable, disable, or change the return receipt service. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
CheckConflictsCheck for replication conflicts when simultaneously writing to bidirectionally replicating TABLE elements between databases. You cannot check for conflicts when replicating elements of type DATASTORE. See "CHECK CONFLICTS".
COMPRESS TRAFFIC {ON | OFF}Compress replicated traffic to reduce the amount of network bandwidth. ON specifies that all replicated traffic for the database defined by STORE be compressed. OFF (the default) specifies no compression. See "Compressing replicated traffic" in Oracle TimesTen In-Memory Database Replication Guide for details.
CONFLICT REPORTING SUSPEND AT ValueSuspends conflict resolution reporting.

Value is a non-negative integer. The default is 0 and means never suspend. Conflict reporting is suspended when the rate of conflict exceeds Value. If you set Value to 0, conflict reporting suspension is turned off.

Use this clause for table-level replication.

CONFLICT REPORTING RESUME AT ValueResumes conflict resolution reporting.

Value is a non-negative integer. Conflict reporting is resumed when the rate of conflict falls below Value. The default is 1.

Use this clause for table level replication.

DISABLE RETURN {SUBSCRIBER | ALL} NumFailuresSet the return service failure policy so that return service blocking is disabled after the number of timeouts specified by NumFailures. Selecting SUBSCRIBER applies this policy only to the subscriber that fails to acknowledge replicated updates within the set timeout period. ALL applies this policy to all subscribers should any of the subscribers fail to respond. This failure policy can be specified for either the RETURN RECEIPT or RETURN TWOSAFE service.

If DISABLE RETURN is specified but RESUME RETURN is not specified, the return services remain off until the replication agent for the database has been restarted.

See "Managing return service timeout errors and replication state changes" in Oracle TimesTen In-Memory Database Replication Guide for details.

DURABLE COMMIT {ON | OFF}Overrides the DurableCommits general connection attribute setting. DURABLE COMMIT ON enables durable commits regardless of whether the replication agent is running or stopped.
DROP ELEMENT * IN FullStoreNameDeletes the replication description of all elements for which FullStoreName is the MASTER. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
DROP ELEMENT ElementNameDeletes the replication description of ElementName.
DROP SUBSCRIBER FullStoreNameIndicates that updates should no longer be sent to the specified subscriber database. This operation fails if your replication scheme has only one subscriber. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
FAILTHRESHOLD ValueThe number of log files that can accumulate for a subscriber database. If this value is exceeded, the subscriber is set to the Failed state.

The value 0 means "No Limit." This is the default.

See "Setting the log failure threshold" in Oracle TimesTen In-Memory Database Replication Guide for more information.

FullStoreNameThe database, specified as one of the following:
  • SELF

  • The prefix of the database file name

For example, if the database path is directory/subdirectory/data.ds0, then data is the database name.

This is the database file name specified in the DataStore attribute of the DSN description with optional host ID in the form:

DataStoreName [ON Host]

Host can be either an IP address or a literal host name assigned to one or more IP addresses, as described in "Configuring host IP addresses" in Oracle TimesTen In-Memory Database Replication Guide. Host names containing special characters must be surrounded by double quotes. For example: "MyHost-500".

LOCAL COMMIT ACTION

{NO ACTION | COMMIT}

Specifies the default action to be taken for a RETURN TWOSAFE transaction in the event of a timeout.

NO ACTION: On timeout, the commit function returns to the application, leaving the transaction in the same state it was in when it entered the commit call, with the exception that the application is not able to update any replicated tables. The application can only reissue the commit. The transaction may not be rolled back. This is the default.

COMMIT: On timeout, the commit function attempts to perform a COMMIT to end the transaction locally. No more operations are possible on the same transaction.

This setting can be overridden for specific transactions by calling the ttRepSyncSet procedure with the localAction parameter.

MASTER FullStoreNameThe database on which applications update the specified element. The MASTER database sends updates to its SUBSCRIBER databases. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
NO RETURNSpecifies that no return service is to be used. This is the default.

For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

PORT PortNumberThe TCP/IP port number on which the replication agent on this database listens for connections. If not specified, the replication agent allocates a port number automatically.

All TimesTen databases that replicate to each other must use the same port number.

PROPAGATOR FullStoreNameThe database that receives replicated updates and passes them on to other databases.
RESUME RETURN MilliSecondsIf return service blocking has been disabled by DISABLE RETURN, this attribute sets the policy on when to re-enable return service blocking. Return service blocking is re-enabled as soon as the failed subscriber acknowledges the replicated update in a period of time that is less than the specified MilliSeconds.

If DISABLE RETURN is specified but RESUME RETURN is not specified, the return services remain off until the replication agent for the database has been restarted.

RETURN RECEIPT [BY REQUEST]Enables the return receipt service, so that applications that commit a transaction to a master database are blocked until the transaction is received by all subscribers.

RETURN RECEIPT applies the service to all transactions. If you specify RETURN RECEIPT BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions. For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

RETURN SERVICES {ON | OFF} WHEN [REPLICATION] STOPPEDSet the return service failure policy so that return service blocking is either enabled or disabled when the replication agent is in the "stop" or "pause" state.

OFF is the default when using the RETURN RECEIPT service. ON is the default when using the RETURN TWOSAFE service.

See "Managing return service timeout errors and replication state changes" in Oracle TimesTen In-Memory Database Replication Guide for details.

RETURN TWOSAFE [BY REQUEST]Enables the return twosafe service, so that applications that commit a transaction to a master database are blocked until the transaction is committed on all subscribers.

RETURN TWOSAFE applies the service to all transactions. If you specify RETURN TWOSAFE BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions. For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

RETURN WAIT TIME SecondsSpecifies the number of seconds to wait for return service acknowledgement. The default value is 10 seconds. A value of '0' means there is no timeout. Your application can override this timeout setting by calling the ttRepSyncSet procedure with the returnWait parameter
SET {MASTER | PROPAGATOR} FullStoreNameSets the given database to be the MASTER or PROPAGATOR of the given elements. The FullStoreName must the be database's file base name.
SUBSCRIBER FullStoreNameA database that receives updates from the MASTER databases. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
TABLE DEFINITION CHECKING {EXACT|RELAXED}Specifies type of table definition checking that occurs on the subscriber:
  • EXACT - The tables must be identical on master and subscriber.

  • RELAXED - The tables must have the same key definition, number of columns and column data types.

The default is EXACT.

TIMEOUT SecondsThe maximum number of seconds the replication agent waits for a response from the database. Default: 120 seconds.
ADD ROUTE MASTER FullStoreName SUBSCRIBER FullStoreNameAdds NetworkOperation to replication scheme. Enables you to control the network interface that a master store uses for every outbound connection to each of its subscriber stores.

Can be specified more than once.

For FullStoreName, ON "host" must be specified.

DROP ROUTE MASTER FullStoreName SUBSCRIBER FullStoreNameDrops NetworkOperation from replication scheme.

Can be specified more than once.

For FullStoreName, ON "host" must be specified.

MASTERIP MasterHost | SUBSCRIBERIP SubscriberHostMasterHost and SubscriberHost are the IP addresses for the network interface on the master and subscriber stores. Specify in dot notation or canonical format or in colon notation for IPV6.

Clause can be specified more than once. Valid for both ADD and DROP ROUTE MASTER.

PRIORITY PriorityVariable expressed as an integer from 1 to 99. Denotes the priority of the IP address. Lower integral values have higher priority. An error is returned if multiple addresses with the same priority are specified. Controls the order in which multiple IP addresses are used to establish peer connections.

Required syntax of NetworkOperation clause. Follows MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost clause.


Description

  • ALTER ELEMENT DROP SUBSCRIBER deletes a subscriber for a particular replication element.

  • ALTER ELEMENT SET NAME may be used to change the name of a replication element when it conflicts with one already defined at another database. SET NAME does not admit the use of * IN FullStoreName. The FullStoreName must be the database's file base name. For example, if the database file name is data.ds0, then data is the file base name.

  • ALTER ELEMENT SET MASTER may be used to change the master database for replication elements. The * IN FullStoreName option must be used for the MASTER operation. That is, a master database must transfer ownership of all of its replication elements, thereby giving up its master role entirely. Typically, this option is used in ALTER REPLICATION statements requested at SUBSCRIBER databases after the failure of a (common) MASTER.

  • To transfer ownership of the master elements to the subscriber:

    1. Manually drop the replicated elements by executing an ALTER REPLICATION DROP ELEMENT statement for each replicated table.

    2. Use ALTER REPLICATION ADD ELEMENT to add each table back to the replication scheme, with the newly designated MASTER / SUBSCRIBER roles.

  • ALTER REPLICATION ALTER ELEMENT SET MASTER does not automatically retain the old master as a subscriber in the scheme. If this is desired, execute an ALTER REPLICATION ALTER ELEMENT ADD SUBSCRIBER statement.


    Note:

    There is no ALTER ELEMENT DROP MASTER. Each replication element must have exactly one MASTER database, and the currently designated MASTER cannot be deleted from the replication scheme.

  • Stop the replication agent before you use the NetworkOperation clause.

  • You cannot alter the following replication schemes with the ALTER REPLICATION statement:

    • Any active standby pair. Instead, use ALTER ACTIVE STANDBY PAIR.

    • A Clusterware-managed active standby pair. Instead, perform the tasks described in "Changing the schema" section of the Oracle TimesTen In-Memory Database Replication Guide.

Examples

This example sets up replication for an additional table westleads that is updated on database west and replicated to database east.

ALTER REPLICATION r1
   ADD ELEMENT e3 TABLE westleads
     MASTER west ON "westcoast"
     SUBSCRIBER east ON "eastcoast";

This example adds an additional subscriber (backup) to table westleads.

ALTER REPLICATION r1
   ALTER ELEMENT e3
     ADD SUBSCRIBER backup ON "backupserver";

This example changes the element name of table westleads from e3 to newelementname.

ALTER REPLICATION r1
   ALTER ELEMENT e3
     SET NAME newelementname;

This example makes newwest the master for all elements for which west currently is the master.

ALTER REPLICATION r1
   ALTER ELEMENT * IN west
     SET MASTER newwest;

This element changes the port number for east.

ALTER REPLICATION r1
   ALTER STORE east ON "eastcoast" SET PORT 22251;

This example adds my.tab1 table to the ds1 database element in my.rep1 replication scheme.

ALTER REPLICATION my.rep1
  ALTER ELEMENT ds1 DATASTORE
     INCLUDE TABLE my.tab1;

This example adds my.cg1 cache group to ds1 database in my.rep1 replication scheme.

ALTER REPLICATION my.rep1
  ALTER ELEMENT ds1 DATASTORE
     INCLUDE CACHE GROUP my.cg1;

This example adds ds1 database to my.rep1 replication scheme. Include my.tab2 table, my.cg2 cache group, and my.cg3 cache group in the database.

ALTER REPLICATION my.rep1
  ADD ELEMENT ds1 DATASTORE
     MASTER rep2
     SUBSCRIBER rep1, rep3
     INCLUDE TABLE my.tab2
     INCLUDE CACHE GROUP my.cg2, my.cg3;

This example adds ds2 database to a replication scheme but exclude my.tab1 table, my.cg0 cache group and my.cg1 cache group.

ALTER REPLICATION my.rep1
  ADD ELEMENT ds2 DATASTORE
     MASTER rep2
     SUBSCRIBER rep1
     EXCLUDE TABLE my.tab1
     EXCLUDE CACHE GROUP my.cg0, my.cg1;

Add NetworkOperation clause:

ALTER REPLICATION r
ADD ROUTE MASTER rep1 ON "machine1" SUBSCRIBER rep2 ON "machine2"
MASTERIP "1.1.1.1" PRIORITY 1 SUBSCRIBERIP "2.2.2.2"
    PRIORITY 1
MASTERIP "3.3.3.3" PRIORITY 2 SUBSCRIBERIP "4.4.4.4" PRIORITY 2;

Drop NetworkOperation clause:

ALTER REPLICATION r
DROP ROUTE MASTER repl ON "machine1" SUBSCRIBER rep2 ON "machine2"
MASTERIP "1.1.1.1" SUBSCRIBERIP "2.2.2.2"
MASTERIP "3.3.3.3" SUBSCRIBERIP "4.4.4.4";

See also


ALTER ACTIVE STANDBY PAIR
CREATE ACTIVE STANDBY PAIR
CREATE REPLICATION
DROP ACTIVE STANDBY PAIR
DROP REPLICATION

To drop a table from a database, see "Altering a replicated table" in Oracle TimesTen In-Memory Database Replication Guide.


ALTER SESSION

The ALTER SESSION statement changes session parameters dynamically.

Required privilege

None

SQL syntax

ALTER SESSION SET
  {DDL_REPLICATION_ACTION={'INCLUDE'|'EXCLUDE'} | 
   DDL_REPLICATION_LEVEL={1|2} |
   NLS_SORT = {BINARY| SortName} |
   NLS_LENGTH_SEMANTICS = {BYTE|CHAR} |
   NLS_NCHAR_CONV_EXCP = {TRUE|FALSE} |
   ISOLATION_LEVEL = {SERIALIZABLE | READ COMMITTED} |
   PLSQL_TIMEOUT = n |
   PLSQL_OPTIMIZE_LEVEL = {0|1|2|3}|
   PLSCOPE_SETTINGS = {'IDENTIFIERS:ALL'|'IDENTIFIERS:NONE'} |
   PLSQL_CONN_MEM_LIMIT = n |
   REPLICATION_TRACK = TrackNumber
   } 

Parameters

ParameterDescription
DDL_REPLICATION_ACTION={'INCLUDE'|'EXCLUDE'}To include a table in the active standby pair when the table is created, set the DDL_REPLICATION_ACTION connection attribute to INCLUDE. If you do not want to include a table in the active standby pair when the table is created, set DDL_REPLICATION_ACTION to EXCLUDE. The default is INCLUDE.

If set to EXCLUDE, a subsequent ALTER ACTIVE STANDBY PAIR ... INCLUDE TABLE is required to be executed on the active database to add the table to the replication scheme. All tables must be empty on all active standby databases and subscribers as the table contents will be truncated when this statement is executed.

This attribute is only valid if DDL_REPLICATION_LEVEL=2.

See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

DDL_REPLICATION_LEVEL={1|2}Indicates whether DDL is replicated across all databases in an active standby pair. The value can be one of the following:
  • 1: Default. Add or drop a column to or from a replicated table on the active database using ALTER TABLE. The change is replicated to the table in the standby database.

  • 2: Supports replication of the creation or dropping of tables, synonyms or indexes from the active database to the standby database. This does include creating or dropping global temporary tables, but does not include CREATE TABLE AS SELECT. The CREATE INDEX statement is replicated only when the index is created on an empty table.

See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

NLS_SORT={BINARY| SortName}Indicates which collation sequence to use for linguistic comparisons.

Append _CI or _AI to either BINARY or the SortName value if you want to do case-insensitive or accent-insensitive sorting.

If you do not specify NLS_SORT, the default is BINARY.

For a complete list of supported values for SortName, see "Linguistic sorts" in Oracle TimesTen In-Memory Database Operations Guide.

For more information on case-insensitive or accent-insensitive sorting, see "Case-insensitive and accent-insensitive linguistic sorts" in Oracle TimesTen In-Memory Database Operations Guide.

NLS_LENGTH_SEMANTICS ={BYTE|CHAR}Sets the default length semantics configuration. BYTE indicates byte length semantics. CHAR indicates character length semantics. The default is BYTE.

For more information on length semantics, see "Length semantics and data storage" in Oracle TimesTen In-Memory Database Operations Guide.

NLS_NCHAR_CONV_EXCP = {TRUE|FALSE}Determines whether an error should be reported when there is data loss during an implicit or explicit character type conversion between NCHAR/NVARCHAR2 data and CHAR/VARCHAR2 data. Specify TRUE to enable error reporting. Specify FALSE to not report errors. The default is FALSE.
ISOLATION_LEVEL = {SERIALIZABLE|READ COMMITTED}Sets isolation level. Change takes effect starting with next transaction.

For a descriptions of the isolation levels, see Oracle TimesTen In-Memory Database Operations Guide.

PLSQL_TIMEOUT= nControls how long PL/SQL procedures run before being automatically terminated. n represents the time, in seconds. Specify 0 for no time limit or any positive integer. The default is 30.

When you modify this value, the new value impacts PL/SQL program units that are currently running as well as any other program units subsequently executed in the same connection.

If PL/SQL is not enabled in your database and you specify this attribute, TimesTen throws an error.

PLSQL_OPTIMIZE_LEVEL = {0|1|2|3}Specifies the optimization level used to compile PL/SQL library units. The higher the setting, the more effort the compiler makes to optimize PL/SQL library units. Possible values are 0, 1, 2 or 3. The default is 2.

If PL/SQL is not enabled in your database and you specify this attribute, TimesTen returns an error.

For more information, see "PLSQL_OPTIMIZE_LEVEL" in Oracle TimesTen In-Memory Database Reference.

PLSCOPE_SETTINGS = '{IDENTIFIERS:ALL |IDENTIFIERS:NONE}'Controls whether or not the PL/SQL compiler generates cross-reference information. Specify IDENTIFIERS:ALL to generate cross-reference information. The default is IDENTIFIERS:NONE.

If PL/SQL is not enabled in your database and you specify this attribute, TimesTen returns an error.

For more information, see "PLSCOPE_SETTINGS" in Oracle TimesTen In-Memory Database Reference.

PLSQL_CONN_MEM_LIMIT = nSpecifies the maximum amount of process heap memory that PL/SQL can use for this connection. n is an integer expressed in megabytes. The default is 100.

If PL/SQL is not enabled in your database and you specify this attribute, TimesTen returns an error.

For more information, see "PLSQL_CONN_MEM_LIMIT" in Oracle TimesTen In-Memory Database Reference.

REPLICATION_TRACK = TrackNumberWhen parallel replication is configured, specify the track to which the transactions belong for the current connection. All transactions on replicated tables are associated with a track. The track number setting is constant for the lifetime of the connection, unless specifically reset. The default track number is 0.

If the number specified is for a non-existent replication track X, the transaction is assigned to a track number computed as X modulo ReplicationParallelism.

You cannot change tracks in the middle of a transaction unless all preceding operations have been read operations.

For more information, see "Configuring user-defined parallel replication for other replication schemes" in Oracle TimesTen In-Memory Database Replication Guide.


Description

  • The ALTER SESSION statement affects commands that are subsequently executed by the session. The new session parameters take effect immediately.

  • Operations involving character comparisons support linguistic sensitive collating sequences. Case-insensitive sorts may affect DISTINCT value interpretation.

  • Implicit and explicit conversions between CHAR and NCHAR are supported.

  • Conversions between CHAR and NCHAR are not allowed when using the TIMESTEN8 character set.

  • You can use the SQL string functions with the supported character sets. For example, UPPER and LOWER functions support non-ASCII CHAR and VARCHAR2 characters as well as NCHAR and NVARCHAR2 characters.

  • Choice of character set could have an impact on memory consumption for CHAR and VARCHAR2 column data.

  • The character sets of all databases involved in a replication scheme must match.

  • To add an existing table to an active standby pair, set DDL_REPLICATION_LEVEL=2 and DDL_REPLICATION_ACTION to INCLUDE. Alternatively, you can use the ALTER ACTIVE STANDBY PAIR INCLUDE TABLE statement if DDL_REPLICATION_ACTION is set to EXCLUDE. In this case, the table must be empty and present on all databases before executing the ALTER ACTIVE STANDBY PAIR INCLUDE TABLE statement as the table contents will be truncated when this statement is executed.

  • Objects are only replicated to TimesTen instances of release 11.2.1.8 or greater that are in a replication scheme using an active standby pair.

Examples

Use the ALTER SESSION statement to change PLSQL_TIMEOUT to 60 seconds. Use a second ALTER SESSION statement to change PLSQL_OPTIMIZE_LEVEL to 3. Then call ttConfiguration to display the new values.

Command> ALTER SESSION SET PLSQL_TIMEOUT = 60;
Session altered.Command> ALTER SESSION SET PLSQL_OPTIMIZE_LEVEL = 3;
Session altered.

Command> CALL TTCONFIGURATION ();
< CkptFrequency, 600 >
< CkptLogVolume, 0 >
< CkptRate, 0 >
...
< PLSQL_OPTIMIZE_LEVEL, 3 >
< PLSQL_TIMEOUT, 60 >
...
47 rows found.

In this example, set PLSQL_TIMEOUT to 20 seconds. Attempt to execute a program that loops indefinitely. In 20 seconds, execution is terminated and an error is returned.

Command> ALTER SESSION SET PLSQL_TIMEOUT = 20;

Command> DECLARE v_timeout NUMBER;
       > BEGIN
       >   LOOP
       >     v_timeout :=0;
       >     EXIT WHEN v_timeout < 0;
       >   END LOOP;
       > END;
       > /
 8509: PL/SQL execution terminated; PLSQL_TIMEOUT exceeded

Call ttConfiguration to display the current PLSCOPE_SETTINGS value. Use the ALTER SESSION statement to change the PLSCOPE_SETTINGS value to IDENTIFIERS:ALL. Create a dummy procedure p. Query the system view SYS.USER_PLSQL_OBJECT_SETTINGS to confirm that the new setting is applied to procedure p.

Command> CALL TTCONFIGURATION ();
< CkptFrequency, 600 >
< CkptLogVolume, 0 >
< CkptRate, 0 >
...
< PLSCOPE_SETTINGS, IDENTIFIERS:NONE >
...
47 rows found.

Command> ALTER SESSION SET PLSCOPE_SETTINGS = 'IDENTIFIERS:ALL';
Session altered.
 
Command> CREATE OR REPLACE PROCEDURE p IS
       > BEGIN
       >  NULL;
       > END;
       > /
Procedure created.
 
Command> SELECT PLSCOPE_SETTINGS FROM SYS.USER_PLSQL_OBJECT_SETTINGS WHERE
       > NAME = 'p';
< IDENTIFIERS:ALL >
1 row found.

The following example uses the ALTER SESSION statement to change the NLS_SORT setting from BINARY to BINARY_CI to BINARY_AI. The database and connection character sets are WE8ISO8859P1.

Command> connect "dsn=cs;ConnectionCharacterSet=WE8ISO8859P1";
Connection successful: DSN=cs;UID=user;DataStore=/datastore/user/cs;
DatabaseCharacterSet=WE8ISO8859P1;
ConnectionCharacterSet=WE8ISO8859P1;PermSize=32;TypeMode=0;
(Default setting AutoCommit=1)
Command>#Create the Table
Command> CREATE TABLE collatingdemo (letter VARCHAR2 (10));
Command>#Insert values
Command> INSERT INTO collatingdemo VALUES ('a');
1 row inserted.
Command> INSERT INTO collatingdemo VALUES ('A');
1 row inserted.
Command> INSERT INTO collatingdemo VALUES ('Y');
1 row inserted.
Command> INSERT INTO collatingdemo VALUES ('ä');
1 row inserted.
Command>#SELECT
Command> SELECT * FROM collatingdemo;
< a >
< A >
< Y >
< ä >
4 rows found.
Command>#SELECT with ORDER BY
Command> SELECT * FROM collatingdemo ORDER BY letter;
< A >
< Y >
< a >
< ä >
4 rows found.
Command>#set NLS_SORT to BINARY_CI and SELECT
Command> ALTER SESSION SET NLS_SORT = BINARY_CI;
Command> SELECT * FROM collatingdemo ORDER BY letter;
< a >
< A >
< Y >
< Ä >
< ä >
4 rows found.
Command>#Set NLS_SORT to BINARY_AI and SELECT
Command> ALTER SESSION SET NLS_SORT = BINARY_AI;
Command> SELECT * FROM collatingdemo ORDER BY letter;
< ä >
< a >
< A >
< Y >
4 rows found.

The following example enables parallel replication and uses the ALTER SESSION statement to change the replication track number to 5 for the current connection. To enable parallel replication for replication schemes, set ReplicationApplyOrdering to 1. Then, always set REPLICATION_TRACK to a number less than or equal to ReplicationParallelism. For example, the ReplicationParallelism connection attribute could be set to 6, which is higher than the value of 5 set for REPLICATION_TRACK.

Command> ALTER SESSION SET REPLICATION_TRACK = 5;
Session altered.

The following example enables replication of adding and dropping columns, tables, synonyms and indexes by setting the following on the active database in an alter standby replication pair: DDLReplicationLevel to 2 and DDLReplicationAction to 'INCLUDE'.

Command > ALTER SESSION SET DDL_REPLICATION_LEVEL=2;
Session altered.

Command > ALTER SESSION SET DDL_REPLICATION_ACTION='INCLUDE';
Session altered.

ALTER TABLE

The ALTER TABLE statement changes an existing table definition.

Required privilege

No privilege is required for the table owner.

ALTER ANY TABLE for another user's table.

For ALTER TABLE...ADD FOREIGN KEY, the owner of the altered table must have the REFERENCES privilege on the table referenced by the foreign key clause.

SQL syntax

To add one column:

ALTER TABLE [Owner.]TableName 
  ADD [COLUMN] ColumnName ColumnDataType
    [DEFAULT DefaultVal] [[NOT] INLINE] [UNIQUE] [NULL]
  [COMPRESS (CompressColumns [,...])]

or to add multiple columns:

ALTER TABLE [Owner.]TableName 
 ADD (ColumnName ColumnDataType 
      [DEFAULT DefaultVal] [[NOT] INLINE] [UNIQUE] [NULL] [,... ] )
  [COMPRESS (CompressColumns [,...])]

To add a NOT NULL column (Note: The default clause is required):

ALTER TABLE [Owner.]TableName
  ADD [COLUMN] ColumnName ColumnDataType
    NOT NULL DEFAULT DefaultVal [[NOT] INLINE] [UNIQUE]
  [COMPRESS (CompressColumns [,...])]

To add multiple NOT NULL columns (Note: The default clause is required):

ALTER TABLE [Owner.]TableName
  ADD (ColumnName ColumnDataType
       NOT NULL DEFAULT DefaultVal [[NOT] INLINE] [UNIQUE] [,...])
  [COMPRESS (CompressColumns [,...])]

The CompressColumns syntax is as follows:

{ColumnDefinition | (ColumnDefinition [,...])} BY DICTIONARY 
   [MAXVALUES = CompressMax]
]

To remove columns. If removing columns in a compressed column group, all columns in the compressed column group must be specified.

ALTER TABLE [Owner.]TableName 
  DROP {[COLUMN] ColumnName | (ColumnName [,... ] )}

To add a primary key constraint using a range index:

ALTER TABLE [Owner.]TableName ADD CONSTRAINT ConstraintName
  PRIMARY KEY (ColumnName [,... ])

To add a primary key constraint using a hash index:

ALTER TABLE [Owner.]TableName ADD CONSTRAINT ConstraintName
  PRIMARY KEY (ColumnName [,... ])
  USE HASH INDEX PAGES = {RowPages | CURRENT}

To add a foreign key and optionally add ON DELETE CASCADE:

ALTER TABLE [Owner.]TableName 
ADD [CONSTRAINT ForeignKeyName] FOREIGN KEY
    (ColumnName [,...]) REFERENCES RefTableName
       [(ColumnName [,...])] [ON DELETE CASCADE]

To remove a foreign key:

ALTER TABLE [Owner.]TableName 
DROP CONSTRAINT ForeignKeyName

To resize a hash index:

ALTER TABLE [Owner.]TableName
SET PAGES = {RowPages | CURRENT}

To change the primary key to use a hash index:

ALTER TABLE [Owner.]TableName
USE HASH INDEX PAGES = {RowPages | CURRENT}

Change the primary key to use a range index with the USE RANGE INDEX clause:

ALTER TABLE [Owner.]TableName
USE RANGE INDEX

To change the default value of a column:

ALTER TABLE [Owner.]TableName
MODIFY (ColumnName DEFAULT DefaultVal)

To add or drop a unique constraint on a column:

ALTER TABLE Owner.]TableName
{ADD | DROP} UNIQUE (ColumnName)

To remove the default value of a column that is nullable, by changing it to NULL:

ALTER TABLE [Owner.]TableName
MODIFY (ColumnName DEFAULT NULL)

To add LRU aging:

ALTER TABLE [Owner.]TableName
ADD AGING LRU [ON | OFF]

To add time-based aging:

ALTER TABLE [Owner.]TableName
ADD AGING USE ColumnName LIFETIME num1
    {SECOND[S] | MINUTE[S] | HOUR[S] | DAY[S]}
     [CYCLE num2 {SECOND[S] | MINUTE[S] | HOUR[S] | DAY[S] }]
    [ON | OFF]

To change the aging state:

ALTER TABLE [Owner.]TableName
SET AGING {ON | OFF}

To drop aging:

ALTER TABLE [Owner.]TableName
DROP AGING

To change the lifetime for time-based aging:

ALTER TABLE [Owner.]TableName
SET AGING LIFETIME num1 {SECOND[S] | MINUTE[S] | HOUR[S] | DAY[S]}

To change the cycle for time-based aging:

ALTER TABLE [Owner.]TableName
SET AGING CYCLE num2 {SECOND[S] | MINUTE[S] | HOUR[S] | DAY[S]}

Parameters

ParameterDescription
[Owner.] TableNameIdentifies the table to be altered.
UNIQUESpecifies that in the column ColumnName each row must contain a unique value.
MODIFYSpecifies that an attribute of a given column is to be changed to a new value.
DEFAULT [DefaultVal |NULL]Specifies that the column has a default value, DefaultVal. If NULL, specifies that the default value of the columns is to be dropped. If a column with a default value of SYSDATE is added, the value of the column of the existing rows only is the system date at the time the column was added. If the default value is one of the USER functions the column value is the user value of the session that executed the ALTER TABLE statement. Currently, you cannot assign a default value for the ROWID data type.

Altering the default value of a column has no impact on existing rows.

ColumnNameName of the column participating in the ALTER TABLE statement. A new column cannot have the same name as an existing column or another new column. If you add a NOT NULL column, you must include the DEFAULT clause.
ColumnDataTypeType of the column to be added. Some types require additional parameters. See Chapter 1, "Data Types" for the data types that can be specified.
NOT NULLIf you add a column, you can specify NOT NULL for the column. If you specify NOT NULL, then you must include the DEFAULT clause.
INLINE|NOT INLINEBy default, variable-length columns whose declared column length is > 128 bytes are stored out of line. Variable-length columns whose declared column length is <= 128 bytes are stored inline. The default behavior can be overridden during table creation through the use of the INLINE and NOT INLINE keywords.
COMPRESS (CompressColumns [,...])Defines a compressed column group for a table that is enabled for compression. This can include one or more columns in the table.

Only INLINE columns are supported when you specify multiple columns in a compressed column group. You can only specify out-of-line columns in a compression group on its own.

Each compressed column group is limited to a maximum of 16 columns.

For more details on compression columns, see "In-memory columnar compression of tables".

BY DICTIONARYDefines a compression dictionary for each compressed column group.
MAXVALUES = CompressMaxCompressMax is the total number of distinct values in the table and sets the size for the compressed column group pointer column to 1, 2, or 4 bytes and sets the size for the maximum number of entries in the dictionary table.

For the dictionary table, NULL is counted as one unique value.

CompressMax takes an integer between 1 and 232-1.

The maximum size defaults to size of 232-1 if the MAXVALUES clause is omitted, which uses 4 bytes for the pointer column. An error is thrown if the value is greater than 232-1.

For more details on maximum sizing for compression dictionaries, see "In-memory columnar compression of tables".

ADD CONSTRAINT ConstraintName PRIMARY KEY (ColumnName

[,... ] ) [USE HASH INDEX PAGES = {RowPages | CURRENT}]

Adds a primary key constraint to the table. Columns of the primary key must be defined as NOT NULL.

Specify ConstraintName as the name of the index used to enforce the primary key constraint. Specify ColumnName as the name(s) of the NOT NULL column(s) used for the primary key.

Specify the USE HASH INDEX clause to use a hash index for the primary key. If not specified, a range index is used for the primary key constraint. Specify either RowPages (as a positive constant) or CURRENT to calculate the page count value. If you specify CURRENT, the current number of rows in the table is used to calculate the page count value.

See the Definition section in "Column Definition" for more details on hash indexes and pages.

CONSTRAINTSpecifies that a foreign key is to be dropped. Optionally specifies that an added foreign key is named by the user.
ForeignKeyNameName of the foreign key to be added or dropped. All foreign keys are assigned a default name by the system if the name was not specified by the user. Either the user-provided name or system name can be specified in the DROP FOREIGN KEY clause.
FOREIGN KEYSpecifies that a foreign key is to be added or dropped. See "FOREIGN KEY".
REFERENCESSpecifies that the foreign key references another table.
RefTableNameThe name of the table that the foreign key references.
[ON DELETE CASCADE]Enables the ON DELETE CASCADE referential action. If specified, when rows containing referenced key values are deleted from a parent table, rows in child tables with dependent foreign key values are also deleted.
USE HASH INDEX PAGES = {RowPages | CURRENT}Specifies that a hash index is to be used for the primary key. If the primary key already uses a hash index, then this clause is equivalent to the SET PAGES clause.
USE RANGE INDEXSpecifies that a range index is to be used for the primary key. If the primary key already uses a range index, TimesTen ignores this clause.
SET PAGESResizes the hash index based on the expected number of row pages in the table. Each row page can contain up to 256 rows of data. This number determines the number of hash buckets created for the hash index. The minimum is 1. If your estimate is too small, performance may be degraded. You can specify a constant (RowPages) or the current number of row pages. See "Column Definition" for a description of hash indexes and pages.
RowPagesThe number of row pages expected.
CURRENTUse the number of row pages currently in use.
ADD AGING LRU [ON | OFF]Adds least recently used (LRU) aging to an existing table that has no aging policy defined.

The LRU aging policy defines the type of aging (least recently used (LRU)), the aging state (ON or OFF) and the LRU aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

LRU attributes are defined by calling the ttAgingLRUConfig procedure. LRU attributes are not defined at the SQL level.

For more information about LRU aging, see "Implementing aging in your tables" in Oracle TimesTen In-Memory Database Operations Guide.

ADD AGING USE ColumnName...[ON| OFF]Adds time-based aging to an existing table that has no aging policy defined.

The time-based aging policy defines the type of aging (time-based), the aging state (ON or OFF) and the time-based aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

Time-based aging attributes are defined at the SQL level and are specified by the LIFETIME and CYCLE clauses.

Specify ColumnName as the name of the column used for time-based aging. Define the column as NOT NULL and of data type TIMESTAMP or DATE. The value of this column is subtracted from SYSDATE, truncated using the specified unit (minute, hour, day) and then compared to the LIFETIME value. If the result is greater than the LIFETIME value, then the row is a candidate for aging.

The values of the column used for aging are updated by your applications. If the value of this column is unknown for some rows, and you do not want the rows to be aged, define the column with a large default value (the column cannot be NULL).

You can define your aging column with a data type of TT_TIMESTAMP or TT_DATE. If you choose data type TT_DATE, then you must specify the LIFETIME unit as days.

For more information about time-based aging, see "Implementing aging in your tables" in Oracle TimesTen In-Memory Database Operations Guide.

LIFETIME Num1 {SECOND[S] | MINUTE[S] | HOUR[S] | DAY[S]Specify the LIFETIME clause after the ADD AGING USE ColumnName clause if you are adding the time-based aging policy to an existing table. Specify the LIFETIME clause after the SET AGING clause to change the LIFETIME setting.

The LIFETIME clause specifies the minimum amount of time data is kept in cache.

Specify Num1 as a positive integer constant to indicate the unit of time expressed in seconds, minutes, hours or days that rows should be kept in cache. Rows that exceed the LIFETIME value are aged out (deleted from the table). If you define your aging column with data type TT_DATE, then you must specify DAYS as the LIFETIME unit.

The concept of time resolution is supported. If DAYS is specified as the time resolution, then all rows whose timestamp belongs to the same day are aged out at the same time. If HOURS is specified as the time resolution, then all rows with timestamp values within that hour are aged at the same time. A LIFETIME of 3 days is different than a LIFETIME of 72 hours (3*24) or a LIFETIME of 432 minutes (3*24*60).

CYCLE Num2 {SECOND[S]| MINUTE[S]| HOUR[S]|DAY[S]}Specify the optional CYCLE clause after the LIFETIME clause if you are adding the time-based aging policy to an existing table.

CYCLE is a time-based aging attribute.

The CYCLE clause indicates how often the system should examine rows to see if data exceeds the specified LIFETIME value and should be aged out (deleted).

Specify Num2 as a positive integer constant.

If you do not specify the CYCLE clause, then the default value is 5 minutes. If you specify 0 for Num2, then the aging thread wakes up every second.

If the aging state is OFF, then aging is not done automatically and the CYCLE clause is ignored.

Specify the CYCLE clause after the SET AGING clause to change the CYCLE setting.

SET AGING {ON|OFF}Changes the aging state. The aging policy must be previously defined. ON enables automatic aging. OFF disables automatic aging. If you want to control aging with an external scheduler, then disable aging and invoke the ttAgingScheduleNow built-in procedure.
DROP AGINGDrops the aging policy from the table. After you define an aging policy, you cannot alter it. Drop aging, then redefine.
SET AGING LIFETIME Num1 {SECOND[S]| MINUTE[S]|HOUR[S] |DAY[S]}Use this clause to change the lifetime for time-based aging.

Num1 must be a positive integer constant.

If you defined your aging column with data type TT_DATE, then you must specify DAYS as the LIFETIME unit.

SET AGING CYCLE Num2 {SECOND[S]| MINUTE[S]| HOUR[S]|DAY[S]}Use this clause to change the cycle for time-based aging.

Num2 must be a positive integer constant.


Understanding partitions when using ALTER TABLE

When you create a table, an initial partition is created. If you ALTER the table, and add additional columns, secondary partitions are created. There is one secondary partition created for each ALTER TABLE statement. For a column in secondary partitions, you cannot create a primary key constraint on the column or use the column for time-based aging.

You can use ttMigrate -r -relaxedUpgrade to condense multiple partitions. This means the initial partition plus one or more secondary partitions are condensed into a single partition called the initial partition. Once you condense the partitions, you can then ALTER the table and add a primary key constraint on the column or use the column for time-based aging. This is because the columns are no longer in seconday partitions but are now in the initial partition.

If your database is involved in replication and you wish to condense multiple partitions, you must use the StoreAttribute TABLE DEFINITION CHECKING RELAXED (of the CREATE REPLICATION statement). Run ttMigrate -r -relaxedUpgrade on both the master and subscriber or on either the master or subscriber by using -duplicate.

Use ttSchema to view partition numbers for columns. ttSchema displays secondary partition number 1 as partition 1, secondary partition number 2 as partition 2 and so on.

As an example, create a table MyTab with 2 columns. Then ALTER the table adding 2 columns (Col3 and Col4) with the NOT NULL DEFAULT clause.

Command> CREATE TABLE MyTab (Col1 NUMBER, Col2 VARCHAR2 (30));
Command> ALTER TABLE MyTab ADD (Col3 NUMBER NOT NULL DEFAULT 10, Col4 TIMESTAMP          NOT NULL DEFAULT TIMESTAMP '2012-09-03 12:00:00');

Use ttSchema to verify Col3 and Col4 are in secondary partition 1.

ttschema -DSN sampledb_1122
-- Database is in Oracle type mode
create table TESTUSER.MYTAB (
        COL1 NUMBER,
        COL2 VARCHAR2(30 BYTE) INLINE,
        COL3 NUMBER NOT NULL DEFAULT 10,
        COL4 TIMESTAMP(6) NOT NULL DEFAULT TIMESTAMP '2012-09-03 12:00:00');
-- column COL3 partition 1
-- column COL4 partition 1

Attempt to add a primary key constraint on Col3 and time-based aging on Col4. You see errors because you can neither add a primary key constraint nor add time-based aging to a column that is not in the initial partition.

Command> ALTER TABLE MyTab ADD CONSTRAINT PriKey PRIMARY KEY (Col3);
 2419: All columns in a primary key constraint must be in the initial partition; column COL3 was added by ALTER TABLE
The command failed.

Command> ALTER TABLE MyTab ADD AGING USE Col4 LIFETIME 3 DAYS;
 3023: Aging column must be in the initial partition; column COL4 was added by ALTER TABLE
The command failed.

Use ttMigrate with the -relaxedUpgrade option to condense the partitions. Then use ttSchema to verify the partitions are condensed and there are no columns in secondary partition 1.

ttMigrate -c dsn=sampledb_1122 test.migrate
 
Saving user PUBLIC
User successfully saved.
 
Saving table TESTUSER.MYTAB
  Saving rows...
  0/0 rows saved.
Table successfully saved.

ttDestroy sampledb_1122

ttMigrate -r -relaxedUpgrade
 dsn=sampledb_1122 test.migrate
 
Restoring table TESTUSER.MYTAB
  Restoring rows...
  0/0 rows restored.
Table successfully restored.

ttSchema DSN=sampledb_1122
-- Database is in Oracle type mode
create table TESTUSER.MYTAB (
        COL1 NUMBER,
        COL2 VARCHAR2(30 BYTE) INLINE,
        COL3 NUMBER NOT NULL DEFAULT 10,
        COL4 TIMESTAMP(6) NOT NULL DEFAULT TIMESTAMP '2012-09-03 12:00:00');

Now add a primary key constraint on Col3 and time-based aging on Col4. The results are successful because Col3 and Col4 are in the initial partition as a result of ttMigrate. Use ttSchema to verify results.

Command> ALTER TABLE MyTab ADD CONSTRAINT PriKey PRIMARY KEY (Col3);
Command> ALTER TABLE MyTab ADD AGING USE Col4 LIFETIME 3 DAYS;

ttschema sampledb_1122
-- Database is in Oracle type mode
create table TESTUSER.MYTAB (
        COL1 NUMBER,
        COL2 VARCHAR2(30 BYTE) INLINE,
        COL3 NUMBER NOT NULL DEFAULT 10,
        COL4 TIMESTAMP(6) NOT NULL DEFAULT TIMESTAMP '2012-09-03 12:00:00')
    AGING USE COL4 LIFETIME 3 days CYCLE 5 minutes ON;
 
    alter table TESTUSER.MYTAB add constraint PRIKEY primary key (COL3);

Description

  • The ALTER TABLE statement cannot be used to alter a temporary table.

  • The ALTER TABLE ADD [COLUMN] ColumnName statement adds one or more new columns to an existing table. The new columns are added to the end of all existing rows of the table in one new partition. The ALTER TABLE ADD or DROP COLUMN statement can be used to add or drop columns from replicated tables.

    However, it cannot be used to alter a replicated table that is part of a TWOSAFE BY REQUEST transaction. If DDLCommitBehavior=1, this operation results in error 8051. If DDLCommitBehavior=0, the operation succeeds because a commit is performed before the ALTER TABLE operation, resulting in the ALTER TABLE operation being in a new transaction which is not part of the TWOSAFE BY REQUEST transaction.

  • Columns referenced by materialized views cannot be dropped.

  • Only one partition is added to the table per statement regardless of the number of columns added.

  • You can ALTER a table to add a NOT NULL column with a default value. The DEFAULT clause is required. Restrictions include:

    • You cannot add a NOT NULL column to a table that is part of a replication scheme. You must remove the table from the replication scheme first before you can add a NOT NULL column to it.

    • You cannot use the column as a primary key column. Specifically, you cannot specify the column in the statement: ALTER TABLE ADD ConstraintName PRIMARY KEY (ColumnName [,...]).

    • You cannot use the column for time-based aging. Specifically, you cannot specify the column in the statement ALTER TABLE ADD AGING USE ColumnName.

  • NULL is the initial value for all added columns, unless a default value is specified for the new column.

  • The total number of columns in the table cannot exceed 1000. In addition, the total number of partitions in a table cannot exceed 1000, one of which is used by TimesTen.

  • Use the ADD CONSTRAINT ... PRIMARY KEY clause to add a primary key constraint to a regular table or to a detailed or materialized view table. Do not use this clause on a table that already has a primary key.

  • If you use the ADD CONSTRAINT... PRIMARY KEY clause to add a primary key constraint, and you do not specify the USE HASH INDEX clause, then a range index is used for the primary key constraint.

  • If a table is replicated and the replication agent is active, you cannot use the ADD CONSTRAINT ... PRIMARY KEY clause. Stop the replication agent first.

  • Do not specify the ADD CONSTRAINT ... PRIMARY KEY clause on a global temporary table.

  • Do not specify the ADD CONSTRAINT ... PRIMARY KEY clause on a cache group table because cache group tables defined with a primary key must be defined in the CREATE CACHE GROUP statement.

  • As the result of an ALTER TABLE ADD statement, an additional read occurs for each new partition during queries. Therefore, altered tables may have slightly degraded performance. The performance can only by restored by dropping and recreating the table, or by using the ttMigrate create -c -relaxedUpgrade command, and restoring the table using the ttRestore -r -relaxedUpgrade command. Dropping the added column does not recover the lost performance or decrease the number of partitions.

  • The ALTER TABLE DROP statement removes one or more columns from an existing table. The dropped columns are removed from all current rows of the table. Subsequent SQL statements must not attempt to make any use of the dropped columns. You cannot drop columns that are in the table's primary key. You cannot drop columns that are in any of the table's foreign keys until you have dropped all foreign keys. You cannot drop columns that are indexed until all indexes on the column have been dropped. ALTER TABLE cannot be used to drop all of the columns of a table. Use DROP TABLE instead.

  • When a column is dropped from a table, all commands referencing that table need to be recompiled. An error may result at recompilation time if a dropped column was referenced. The application must re-prepare those commands, and rebuild any parameters and result columns. When a column is added to a table, the commands that contain a SELECT * statement are invalidated. Only these commands must be re-prepared. All other commands continue to work as expected.

  • When you drop a column, the column space is not freed.

  • When you add a UNIQUE constraint, there is overhead incurred (in terms of additional space and additional time). This is because an index is created to maintain the UNIQUE constraint. You cannot use the DROP INDEX statement to drop an index used to maintain the UNIQUE constraint.

  • A UNIQUE constraint and its associated index cannot be dropped if it is being used as a unique index on a replicated table.

  • Use ALTER TABLE...USE RANGE INDEX if your application performs range queries over a table's primary key.

  • Use ALTER TABLE...USE HASH INDEX if your application performs exact match lookups on a table's primary key.

  • An error is generated if a table has no primary key and either the USE HASH INDEX clause or the USE RANGE INDEX clause is specified.

  • If ON DELETE CASCADE is specified on a foreign key constraint for a child table, a user can delete rows from a parent table for which the user has the DELETE privilege without requiring explicit DELETE privilege on the child table.

  • To change the ON DELETE CASCADE triggered action, drop then redefine the foreign key constraint.

  • ON DELETE CASCADE is supported on detail tables of a materialized view. If you have a materialized view defined over a child table, a deletion from the parent table causes cascaded deletes in the child table. This, in turn, triggers changes in the materialized view.

  • The total number of rows reported by the DELETE statement does not include rows deleted from child tables as a result of the ON DELETE CASCADE action.

  • For ON DELETE CASCADE, since different paths may lead from a parent table to a child table, the following rule is enforced:

  • Either all paths from a parent table to a child table are "delete" paths or all paths from a parent table to a child table are "do not delete" paths.

    • Specify ON DELETE CASCADE on all child tables on the "delete" path.

    • This rule does not apply to paths from one parent to different children or from different parents to the same child.

  • For ON DELETE CASCADE, a second rule is also enforced:

  • If a table is reached by a "delete" path, then all its children are also reached by a "delete" path.

  • For ON DELETE CASCADE with replication, the following restrictions apply:

    • The foreign keys specified with ON DELETE CASCADE must match between the Master and subscriber for replicated tables. Checking is done at runtime. If there is an error, the receiver thread stops working.

    • All tables in the delete cascade tree have to be replicated if any table in the tree is replicated. This restriction is checked when the replication scheme is created or when a foreign key with ON DELETE CASCADE is added to one of the replication tables. If an error is found, the operation is aborted. You may be required to drop the replication scheme first before trying to change the foreign key constraint.

    • You must stop the replication agent before adding or dropping a foreign key on a replicated table.

  • The ALTER TABLE ADD/DROP CONSTRAINT statement has the following restrictions:

    • When a foreign key is dropped, TimesTen also drops the index associated with the foreign key. Attempting to drop an index associated with a foreign key using the regular DROP INDEX statement results in an error.

    • Foreign keys cannot be added or dropped on tables in a cache group.

    • Foreign keys cannot be added or dropped on tables that participate in TimesTen replication. If the operation is attempted on a table that is either being replicated or is a replicated table, TimesTen returns an error.

    • Foreign keys cannot be added or dropped on views or temporary tables.

  • After you have defined an aging policy for the table, you cannot change the policy from LRU to time-based or from time-based to LRU. You must first drop aging and then alter the table to add a new aging policy.

  • The aging policy must be defined to change the aging state.

  • The following rules determine if a row is accessed or referenced for LRU aging:

    • Any rows used to build the result set of a SELECT statement.

    • Any rows used to build the result set of an INSERT ... SELECT statement.

    • Any rows that are about to be updated or deleted.

  • Compiled commands are marked invalid and need recompilation when you either drop LRU aging from or add LRU aging to tables that are referenced in the commands.

  • Call the ttAgingScheduleNow procedure to schedule the aging process right away regardless if the aging state is ON or OFF.

  • For the time-based aging policy, you cannot add or modify the aging column. This is because you cannot add or modify a NOT NULL column.

  • Aging restrictions:

    • You cannot drop the column that is used for time-based aging.

    • Tables that are related by foreign keys must have the same aging policy.

    • For LRU aging, if a child row is not a candidate for aging, neither this child row nor its parent row are deleted. ON DELETE CASCADE settings are ignored.

    • For time-based aging, if a parent row is a candidate for aging, then all child rows are deleted. ON DELETE CASCADE (whether specified or not) is ignored.

  • Restrictions for in-memory columnar compression of tables:

    • You can only add compressed column groups with the ALTER TABLE statement if the table was enabled for compression at table creation. You can add uncompressed columns to any table, including tables enabled for compression. A table is enabled for compression during creation when OPTIMIZED FOR READ is specified. Refer to "In-memory columnar compression of tables" for more details on adding compressed column groups to a table.

    • You cannnot modify columns of a compressed column group.

    • You can drop all columns within a compressed column group with the ALTER TABLE command; when removing columns in a compressed column group, all columns in the compressed column group must be specified for removal.

Examples

Add returnrate column to parts table.

ALTER TABLE parts ADD COLUMN returnrate DOUBLE;

Add numsssign and prevdept columns to contractor table.

ALTER TABLE contractor
  ADD ( numassign INTEGER, prevdept CHAR(30) );

Remove addr1 and addr2 columns from employee table.

ALTER TABLE employee DROP ( addr1, addr2 );

Drop the UNIQUE title column of the books table.

ALTER TABLE books DROP UNIQUE (title);

Add the x1 column to the t1 table with a default value of 5:

ALTER TABLE t1 ADD (x1 INT DEFAULT 5);

Change the default value of column x1 to 2:

ALTER TABLE t1 MODIFY (x1 DEFAULT 2);

Alter table primarykeytest to add the primary key constraint c1. Use the ttIsql INDEXES command to show that the primary key constraint c1 is created and a range index is used:

Command> CREATE TABLE primarykeytest (col1 TT_INTEGER NOT NULL);
Command> ALTER TABLE primarykeytest ADD CONSTRAINT c1 
>        PRIMARY KEY (col1);
Command> INDEXES primarykeytest;

Indexes on table SAMPLEUSER.PRIMARYKEYTEST:
  C1: unique range index on columns:
    COL1
  1 index found.

1 index found on 1 table.

Alter table prikeyhash to add the primary key constraint c2 using a hash index. Use the ttIsql INDEXES command to show that the primary key constraint c2 is created and a hash index is used:

Command> CREATE TABLE prikeyhash (col1 NUMBER (3,2) NOT NULL);
Command> ALTER TABLE prikeyhash ADD CONSTRAINT c2
>        PRIMARY KEY (col1) USE HASH INDEX PAGES = 20;
Command> INDEXES prikeyhash;

Indexes on table SAMPLEUSER.PRIKEYHASH:
  C2: unique hash index on columns:
    COL1
  1 index found.

1 table found.

Attempt to add a primary key constraint on a table already defined with a primary key. You see an error:

Command> CREATE TABLE oneprikey (col1 VARCHAR2 (30) NOT NULL, 
>        col2 TT_BIGINT NOT NULL, col3 CHAR (15) NOT NULL, 
>        PRIMARY KEY (col1,col2));
Command> ALTER TABLE oneprikey ADD CONSTRAINT c2 
>        PRIMARY KEY (col1,col2);
 2235: Table can have only one primary key
The command failed.

Attempt to add a primary key constraint on a column that is not defined as NOT NULL. You see an error:

Command> CREATE TABLE prikeynull (col1 CHAR (30));
Command> ALTER TABLE prikeynull ADD CONSTRAINT c3 
>        PRIMARY KEY (col1);
 2236: Nullable column cannot be part of a primary key
The command failed.

This example illustrates the use of range and hash indexes. It creates the pkey table with col1 as the primary key. A range index is created by default. The table is then altered to change the index on col1 to a hash index. The table is altered again to change the index back to a range index.

Command> CREATE TABLE pkey (col1 TT_INTEGER PRIMARY KEY, col2 VARCHAR2 (20));
Command> INDEXES pkey;
Indexes on table SAMPLEUSER.PKEY:
   PKEY: unique range index on columns:
    COL1
 1 index found.
1 index found on 1 table.

Alter the pkey table to use a hash index:

Command> ALTER TABLE pkey USE HASH INDEX PAGES = CURRENT;
Command> INDEXES pkey;
Indexes on table SAMPLEUSER.PKEY:
  PKEY: unique hash index on columns:
    COL1
  1 index found.
1 table found.

Alter the pkey table to use a range index with the USE RANGE INDEX clause:

Command> ALTER TABLE pkey USE RANGE INDEX;
Command> INDEXES pkey;
Indexes on table SAMPLEUSER.PKEY:
  PKEY: unique range index on columns:
    COL1
  1 index found.
1 table found.

This example generates an error when attempting to alter a table to define either a range or hash index on a column without a primary key.

Command> CREATE TABLE illegalindex (Ccl1 CHAR (20));
Command> ALTER TABLE illegalindex USE RANGE INDEX;
 2810: The table has no primary key so cannot change its index type
The command failed.
Command> ALTER TABLE illegalindex USE HASH INDEX PAGES = CURRENT;
 2810: The table has no primary key so cannot change its index type
The command failed.

These examples show how time resolution works with aging. In this example, lifetime is 3 days.

  • If (SYSDATE - ColumnValue) <= 3, do not age out the row.

  • If (SYSDATE - ColumnValue) > 3, then the row is a candidate for aging.

  • If (SYSDATE - ColumnValue) = 3 days, 22 hours, then row is not aged out because lifetime was specified in days. The row would be aged out if lifetime had been specified as 72 hours.

This example alters a table by adding LRU aging. The table has no previous aging policy. The aging state is ON by default.

ALTER TABLE agingdemo3 ADD AGING LRU;
Command> DESCRIBE agingdemo3;
Table USER.AGINGDEMO3:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
  Aging lru on
1 table found.
(primary key columns are indicated with *)

This example alters a table by adding time-based aging. The table has no previous aging policy. The agingcolumn column is used for aging. LIFETIME is 2 days. CYCLE is 30 minutes.

ALTER TABLE agingdemo4
       ADD AGING USE agingcolumn LIFETIME 2 DAYS CYCLE 30 MINUTES;
Command> DESCRIBE agingdemo4;
Table USER.AGINGDEMO4:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
    AGINGCOLUMN                     TIMESTAMP (6) NOT NULL
  Aging use AGINGCOLUMN lifetime 2 days cycle 30 minutes on

This example illustrates that after you create an aging policy, you cannot change it. You must drop aging and redefine.

CREATE TABLE agingdemo5
       (agingid NUMBER NOT NULL PRIMARY KEY
       ,name VARCHAR2 (20)
       ,agingcolumn TIMESTAMP NOT NULL
       )
       AGING USE agingcolumn LIFETIME 3 DAYS OFF;
ALTER TABLE agingdemo5
      ADD AGING LRU;
 2980: Cannot add aging policy to a table with an existing aging policy. Have to
 drop the old aging first
The command failed.

Drop aging on the table and redefine with LRU aging.

ALTER TABLE agingdemo5
      DROP AGING;
ALTER TABLE agingdemo5
       ADD AGING LRU;
Command> DESCRIBE agingdemo5;
Table USER.AGINGDEMO5:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
    AGINGCOLUMN                     TIMESTAMP (6) NOT NULL
  Aging lru on
1 table found.
(primary key columns are indicated with *)

This example alters a table by setting the aging state to OFF. The table has been defined with a time-based aging policy. If you set the aging state to OFF, aging is not done automatically. This is useful if you want to use an external scheduler to control the aging process. Set aging state to OFF and then call the ttAgingScheduleNow procedure to start the aging process.

Command> DESCRIBE agingdemo4;
Table USER.AGINGDEMO4:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
    AGINGCOLUMN                     TIMESTAMP (6) NOT NULL
  Aging use AGINGCOLUMN lifetime 2 days cycle 30 minutes on

ALTER TABLE AgingDemo4
       SET AGING OFF;

Note that when you describe agingdemo4, the aging policy is defined and the aging state is set to OFF.

Command> DESCRIBE agingdemo4;
Table USER.AGINGDEMO4:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
    AGINGCOLUMN                     TIMESTAMP (6) NOT NULL
  Aging use AGINGCOLUMN lifetime 2 days cycle 30 minutes off
1 table found.
(primary key columns are indicated with *)

Call ttAgingScheduleNow to invoke aging with an external scheduler:

Command> CALL ttAgingScheduleNow ('agingdemo4');

Attempt to alter a table adding the aging column and then use that column for time-based aging. An error is generated.

Command> DESCRIBE x;
Table USER1.X:
  Columns:
   *ID                              TT_INTEGER NOT NULL
1 table found.
(primary key columns are indicated with *)
Command> ALTER TABLE x ADD COLUMN t TIMESTAMP;
Command> ALTER TABLE x ADD AGING USE t LIFETIME 2 DAYS;
 2993: Aging column cannot be nullable
The command failed.

Attempt to alter the LIFETIME clause for a table defined with time-based aging. The aging column is defined with data type TT_DATE. An error is generated because the LIFETIME unit is not expressed in DAYS.

Command> CREATE TABLE aging1 (col1 TT_DATE NOT NULL) AGING USE 
         col1 LIFETIME 2 DAYS;
Command> ALTER TABLE aging1 SET AGING LIFETIME 2 HOURS;
 2977: Only DAY lifetime unit is allowed with a TT_DATE column
The command failed.

Alter the employees table to add a new compressed column of state, which contains the full name of the state. Note that the employees table already has a compressed column group consisting of job_id and manager_id.

Command> ALTER TABLE employees 
 ADD COLUMN state VARCHAR2(20) 
 COMPRESS (state BY DICTIONARY);

Command> DESCRIBE employees; 
Table MYSCHEMA.EMPLOYEES:
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE NOT NULL
    EMAIL                           VARCHAR2 (25) INLINE NOT NULL
    PHONE_NUMBER                    VARCHAR2 (20) INLINE
    HIRE_DATE                       DATE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    SALARY                          NUMBER (8,2)
    COMMISSION_PCT                  NUMBER (2,2)
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)
    STATE                           VARCHAR2 (20) INLINE
  COMPRESS ( ( JOB_ID, MANAGER_ID ) BY DICTIONARY,
             STATE BY DICTIONARY ) OPTIMIZED FOR READ
 
1 table found.
(primary key columns are indicated with *)

The following example drops the compressed column state from the employees table:

Command> ALTER TABLE employees
 DROP state;
Command> DESCRIBE employees; 
Table MYSCHEMA.EMPLOYEES:
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE NOT NULL
    EMAIL                           VARCHAR2 (25) INLINE NOT NULL
    PHONE_NUMBER                    VARCHAR2 (20) INLINE
    HIRE_DATE                       DATE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    SALARY                          NUMBER (8,2)
    COMMISSION_PCT                  NUMBER (2,2)
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)
 COMPRESS ( ( JOB_ID, MANAGER_ID ) BY DICTIONARY ) OPTIMIZED FOR READ
 
1 table found.
(primary key columns are indicated with *)

See also


CREATE TABLE
DROP TABLE

"Implementing aging in your tables" in Oracle TimesTen In-Memory Database Operations Guide


ALTER USER

The ALTER USER statement enables a user to change the user's own password. A user with the ADMIN privilege can change another user's password.

This statement also enables a user to change another user from internal to external or from external to internal.

Required privilege

No privilege is required to change the user's own password.

ADMIN privilege is required to change another user's password.

ADMIN privilege is required to change users from internal to external and from external to internal.

SQL syntax

ALTER USER user IDENTIFIED BY {password | "password"}
ALTER USER user IDENTIFIED EXTERNALLY

Parameters

ParameterDescription
userName of the user whose password is being changed.
IDENTIFIED BYIdentification clause.
password |"password"Specifies the password that identifies the internal user to the TimesTen database.
EXTERNALLYIdentifies the operating system user to the TimesTen database. To perform database operations as an external user, the process needs a TimesTen external user name that matches the user name authenticated by the operating system or network. A password is not required by TimesTen because the user has been authenticated by the operating system at login time.

Description

  • Database users can be internal or external.

    • Internal users are defined for a TimesTen database.

    • External users are defined by an external authority, such as the operating system. External users cannot be assigned a TimesTen password.

  • If you are an internal user connected as user, execute this statement to change your TimesTen password.

  • Passwords are case-sensitive.

  • You cannot alter a user across a client/server connection. You must use a direct connection when altering a user.

  • When replication is configured, this statement is replicated.

Examples

To change the password for internal user terry to "12345" from its current setting, use:

ALTER USER terry IDENTIFIED BY "12345";
User altered.

To change user terry to an external user:

ALTER USER terry IDENTIFIED EXTERNALLY;
User altered.

To change user terry back to an internal user, provide a password:

ALTER USER terry IDENTIFIED BY "secret";
User altered.

See also


CREATE USER
DROP USER
GRANT
REVOKE

CALL

Use the CALL statement to invoke a TimesTen built-in procedure or to execute a PL/SQL procedure or function that is standalone or part of a package from within SQL.

Required privilege

The privileges required for invoking each TimesTen built-in procedure are listed in the description of each procedure in the "Built-In Procedures" section in the Oracle TimesTen In-Memory Database Reference.

No privileges are required for an owner calling its own PL/SQL procedure or function that is standalone or part of a package using the CALL statement. For all other users, the EXECUTE privilege on the procedure or function or on the package in which it is defined is required.

SQL syntax

To call a TimesTen built-in procedure:

CALL [TimesTenBuiltIn [( arguments )] 

When calling PL/SQL procedures or functions that are standalone or part of a package, you can either call these by name or as the result of an expression.

To call a PL/SQL procedure:

CALL [Owner.][Package.]ProcedureName [( arguments )] 

To call a PL/SQL function that returns a parameter, one of the following are appropriate:

CALL [Owner.][Package.]FunctionName [( arguments )] INTO :return_param

Note:

A user's own PL/SQL procedure or function takes precedence over a TimesTen built-in procedure with the same name.

Parameters

ParameterDescription
TimesTenBuiltInName of the TimesTen built-in procedure. For a full list of TimesTen built-in procedures, see "Built-In Procedures" in the Oracle TimesTen In-Memory Database Reference.
[Owner.]ProcedureNameName of the PL/SQL procedure. You can optionally specify the owner of the procedure.
[Owner.]FunctionNameName of the PL/SQL function. You can optionally specify the owner of the function.
argumentsSpecify 0 or more arguments for the PL/SQL procedure or function.
INTOIf the routine is a function, the INTO clause is required.
return_paramSpecify the host variable that stores the return value of the function.

Description

Detailed information on how to execute PL/SQL procedures or functions with the CALL statement in TimesTen is provided in "How to execute PL/SQL procedures and functions" in the Oracle TimesTen In-Memory Database PL/SQL Developer's Guide, "Using CALL to execute procedures and functions" in the Oracle TimesTen In-Memory Database C Developer's Guide, or "Using CALL to execute procedures and functions" in the Oracle TimesTen In-Memory Database Java Developer's Guide.

Examples

The following is the definition of the mytest function:

create or replace function mytest return number is
begin
  return 1;
end;
/

Perform the following to execute the mytest function in a CALL statement:

Command> variable n number;
Command> call mytest() into :n;
Command> print n;
N                    : 1

The following example creates a function that returns the salary of the employee whose employee ID is specified as input, then calls the function and displays the result that was returned.

Command> CREATE OR REPLACE FUNCTION get_sal
       >   (p_id employees.employee_id%TYPE) RETURN NUMBER IS
       >    v_sal employees.salary%TYPE := 0;
       > BEGIN
       >   SELECT salary INTO v_sal FROM employees
       >     WHERE employee_id = p_id;
       >   RETURN v_sal;
       > END get_sal;
       > /
 
Function created.
 
Command> variable n number;
Command> call get_sal(100) into :n;
Command> print n;
N                    : 24000

COMMIT

The COMMIT statement ends the current transaction and makes permanent all changes performed in the transaction. A transaction is a sequence of SQL statements treated as a single unit.

Required privilege

None

SQL syntax

COMMIT [WORK]

Parameters

The COMMIT statement enables the following optional keyword:

ParameterDescription
[WORK]Optional clause supported for compliance with the SQL standard. COMMIT and COMMIT WORK are equivalent.

Description

  • Until you commit a transaction:

    • You can see any changes you have made during the transaction but other users cannot see the changes. After you commit the transaction, the changes are visible to other users' statements that execute after the commit.

    • You can roll back (undo) changes made during the transaction with the ROLLBACK statement.

  • This statement releases transaction locks.

  • For passthrough, the Oracle transaction will also be committed.

  • A commit closes all open cursors.

Examples

Insert row into regions table of the HR schema and commit transaction. First set autocommit to 0:

Command> SET AUTOCOMMIT 0;
Command> INSERT INTO regions VALUES (5,'Australia');
1 row inserted.
Command> COMMIT;
Command> SELECT * FROM regions;
< 1, Europe >
< 2, Americas >
< 3, Asia >
< 4, Middle East and Africa >
< 5, Australia >
5 rows found.

See also

ROLLBACK


CREATE ACTIVE STANDBY PAIR

This statement creates an active standby pair. It includes an active master database, a standby master database, and may also include one or more read-only subscribers. The active master database replicates updates to the standby master database, which propagates the updates to the subscribers.

Required privilege

ADMIN

SQL syntax

CREATE ACTIVE STANDBY PAIR
  FullStoreName, FullStoreName [ReturnServiceAttribute]
    [SUBSCRIBER FullStoreName [,...]]
    [STORE FullStoreName [StoreAttribute [...]]]
    [NetworkOperation [...] ]
    [{ INCLUDE | EXCLUDE }{TABLE [[Owner.]TableName [,...]]|
         CACHE GROUP [[Owner.]CacheGroupName [,...]]|
         SEQUENCE [[Owner.]SequenceName [,...]]} [,...]]

The syntax for ReturnServiceAttribute is

{ RETURN RECEIPT [BY REQUEST] |
  RETURN TWOSAFE [BY REQUEST] |
  NO RETURN }

Syntax for StoreAttribute is:

  [ DISABLE RETURN {SUBSCRIBER | ALL} NumFailures ]
  [ RETURN SERVICES {ON | OFF} WHEN [REPLICATION] STOPPED ]
  [ DURABLE COMMIT {ON | OFF}]
  [ RESUME RETURN MilliSeconds ]
  [ LOCAL COMMIT ACTION {NO ACTION | COMMIT} ]
  [ RETURN WAIT TIME Seconds ]
  [ COMPRESS TRAFFIC {ON | OFF}
  [ PORT PortNumber ]
  [ TIMEOUT Seconds ]
  [ FAILTHRESHOLD Value ]

Syntax for NetworkOperation:

ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
  { { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost }
      PRIORITY Priority } [...]

Parameters

ParameterDescription
FullStoreNameThe database, specified as one of the following:
  • SELF

  • The prefix of the database file name

For example, if the database path is directory/subdirectory/data.ds0, then data is the database name that should be used.

This is the database file name specified in the DataStore attribute of the DSN description with optional host ID in the form:

DataStoreName [ON Host]

Host can be either an IP address or a literal host name assigned to one or more IP addresses, as described in "Configuring host IP addresses" in Oracle TimesTen In-Memory Database Replication Guide. Host names containing special characters must be surrounded by double quotes. For example: "MyHost-500".

RETURN RECEIPT [BY REQUEST]Enables the return receipt service, so that applications that commit a transaction to an active master database are blocked until the transaction is received by the standby master database.

Specifying RETURN RECEIPT applies the service to all transactions. If you specify RETURN REQUEST BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions. For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

RETURN TWOSAFE [BY REQUEST]Enables the return twosafe service, so that applications that commit a transaction to an active master database are blocked until the transaction is committed on the standby master database.

Specifying RETURN TWOSAFE applies the service to all transactions. If you specify RETURN TWOSAFE BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions.

For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

DISABLE RETURN {SUBSCRIBER | ALL} NumFailuresSet the return service failure policy so that return service blocking is disabled after the number of timeouts specified by NumFailures.

Specifying SUBSCRIBER is the same as specifying ALL. Both settings refer to the standby master database.

This failure policy can be specified for either the RETURN RECEIPT or RETURN TWOSAFE service.

See "Managing return service timeout errors and replication state changes" in Oracle TimesTen In-Memory Database Replication Guide for details.

RESUME RETURN MillisecondsIf DISABLE RETURN has disabled return service blocking, this attribute sets the policy for when to re-enable the return service.
NO RETURNSpecifies that no return service is to be used. This is the default.

For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

RETURN WAIT TIME SecondsSpecifies the number of seconds to wait for return service acknowledgement. A value of 0 means that there is no waiting. The default value is 10 seconds.

The application can override this timeout setting by using the returnWait parameter in the ttRepSyncSet built-in procedure.

SUBSCRIBER FullStoreName [,...]]A database that receives updates from a master database. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
STORE FullStoreName [StoreAttribute [...]]Defines the attributes for the specified database. Attributes include PORT, TIMEOUT and FAILTHRESHOLD. FullStoreName is the database file name specified in the DataStore attribute of the DSN description.
{INCLUDE | EXCLUDE}

{TABLE [[Owner.]TableName[,...]]|

CACHE GROUP

[[Owner.]CacheGroupName

[,...]]|

SEQUENCE

[[Owner.]SequenceName

[,...]]}

[,...]

An active standby pair replicates an entire database by default.

INCLUDE includes only the listed tables, sequences or cache groups to replication. Use one INCLUDE clause for each object type (table, sequence or cache group).

EXCLUDE removes tables, sequences or cache groups from the replication scheme. Use one EXCLUDE clause for each object type (table, sequence or cache group).

DURABLE COMMIT {ON | OFF}Overrides the DurableCommits general connection attribute setting. DURABLE COMMIT ON enables durable commits regardless of whether the replication agent is running or stopped. It also enables durable commits when the ttRepStateSave built-in procedure has marked the standby database as failed.
FAILTHRESHOLD ValueThe number of log files that can accumulate for a subscriber database. If this value is exceeded, the subscriber is set to the Failed state.The value 0 means "No Limit." This is the default.

See "Setting the log failure threshold" in Oracle TimesTen In-Memory Database Replication Guide for more information.

LOCAL COMMIT ACTION

{NO ACTION | COMMIT}

Specifies the default action to be taken for a return twosafe transaction in the event of a timeout.

Note: This attribute is valid only when the RETURN TWOSAFE or RETURN TWOSAFE BY REQUEST attribute is set in the SUBSCRIBER clause.

NO ACTION: On timeout, the commit function returns to the application, leaving the transaction in the same state it was in when it entered the commit call, with the exception that the application is not able to update any replicated tables. The application can reissue the commit or rollback the call. This is the default.

COMMIT: On timeout, the commit function attempts to perform a COMMIT to end the transaction locally. No more operations are possible on the same transaction.

This setting can be overridden for specific transactions by calling the localAction parameter in the ttRepSyncSet procedure.

MASTER FullStoreNameThe database on which applications update the specified element. The MASTER database sends updates to its SUBSCRIBER databases. The FullStoreName must be the database specified in the DataStore attribute of the DSN description.
PORT PortNumberThe TCP/IP port number on which the replication agent for the database listens for connections. If not specified, the replication agent automatically allocates a port number.

In an active standby pair, the standby master database listens for updates from the active master database. Read-only subscribers listen for updates from the standby master database.

ROUTE MASTER FullStoreName SUBSCRIBER</code> FullStoreNameDenotes the NetworkOperation clause. If specified, enables you to control the network interface that a master store uses for every outbound connection to each of its subscriber stores. In the context of the ROUTE clause, you can define the following:
  • A route for the active database to the standby database and for the standby database to the active database for when failover occurs.

  • A route for a read-only subscriber to the active and standby databases.

When using active standby pairs, ROUTE should be specified at least twice for an active standby pair with no read only subscribers. Then, ROUTE should be specified twice more for each read only subscriber on the active standby pair.

For FullStoreName, ON "host" must be specified.

MASTERIP MasterHost | SUBSCRIBERIP SubscriberHostMasterHost and SubscriberHost are the IP addresses for the network interface on the master and subscriber stores. Specify in dot notation or canonical format or in colon notation for IPV6.

Clause can be specified more than once.

PRIORITY PriorityVariable expressed as an integer from 1 to 99. Denotes the priority of the IP address. Lower integral values have higher priority. An error is returned if multiple addresses with the same priority are specified. Controls the order in which multiple IP addresses are used to establish peer connections.

Required syntax of NetworkOperation clause. Follows MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost clause.

TIMEOUT SecondsThe maximum number of seconds the replication agent waits for a response from the database. Default: 120 seconds.

In an active standby pair, the active master database sends messages to the standby master database. The standby master database sends messages to the read-only subscribers.


Description

  • CREATE ACTIVE STANDBY PAIR is immediately followed by the names of the two master databases. The master databases are later designated as ACTIVE and STANDBY using the ttRepStateSet built-in procedure. See "Setting up an active standby pair with no cache groups" in Oracle TimesTen In-Memory Database Replication Guide.

  • The SUBSCRIBER clause lists one or more read-only subscriber databases. You can designate up to 127 subscriber databases.

  • Replication between the active master database and the standby master database can be RETURN TWOSAFE, RETURN RECEIPT, or asynchronous. RETURN TWOSAFE ensures no transaction loss.

  • Use the INCLUDE and EXCLUDE clauses to exclude the listed tables, sequences and cache groups from replication, or to include only the listed tables, sequences and cache groups, excluding all others.

  • If the active standby pair has the RETURN TWOSAFE attribute and replicates a cache group, a transaction may fail if:

    • The transaction that is being replicated contains an ALTER TABLE statement or an ALTER CACHE GROUP statement

    • The transaction contains an INSERT, UPDATE or DELETE statement on a replicated table, replicated cache group or an asynchronous writethrough cache group

  • Using an active standby pair to replicate read-only cache groups and asynchronous writethrough (AWT) cache groups is supported.

  • You cannot use an active standby pair to replicate synchronous writethrough (SWT) cache groups. If you are using an active standby pair to replicated a database with SWT cache groups, you must either drop or exclude the SWT cache groups.

  • You cannot execute the CREATE ACTIVE STANDBY PAIR statement when Oracle Clusterware is used with TimesTen.

Examples

This example creates an active standby pair whose master databases are rep1 and rep2. There is one subscriber, rep3. The type of replication is RETURN RECEIPT. The statement also sets PORT and TIMEOUT attributes for the master databases.

CREATE ACTIVE STANDBY PAIR rep1, rep2 RETURN RECEIPT
  SUBSCRIBER rep3
  STORE rep1 PORT 21000 TIMEOUT 30
  STORE rep2 PORT 22000 TIMEOUT 30;

Specify NetworkOperation clause to control network interface:

CREATE ACTIVE STANDBY PAIR rep1,rep2
ROUTE MASTER rep1 ON "machine1" SUBSCRIBER rep2 ON "machine2"
MASTERIP "1.1.1.1" PRIORITY 1 SUBSCRIBERIP "2.2.2.2" PRIORITY 1;
ROUTE MASTER rep2 ON "machine2" SUBSCRIBER rep1 ON "machine1"
MASTERIP "2.2.2.2" PRIORITY 1 SUBSCRIBERIP "1.1.1.1" PRIORITY 1;

See also


ALTER ACTIVE STANDBY PAIR
DROP ACTIVE STANDBY PAIR

CREATE CACHE GROUP

The CREATE CACHE GROUP statement:

  • Creates the table defined by the cache group

  • Loads all new information associated with the cache group in the appropriate system tables.

A cache group is a set of tables related through foreign keys that cache data from tables in an Oracle database. There is one root table that does not reference any of the other tables. All other cache tables in the cache group reference exactly one other table in the cache group. In other words, the foreign key relationships form a tree.

A cache table is a set of rows satisfying the conditions:

  • The rows constitute a subset of the rows of a vertical partition of an Oracle table.

  • The rows are stored in a TimesTen table with the same name as the Oracle table.

If a database has more than one cache group, the cache groups must correspond to different Oracle (and TimesTen) tables.

Cache group instance refers to a row in the root table and all the child table rows related directly or indirectly to the root table rows.

User managed and system managed cache groups

A cache group can be either system managed or user managed.

A system managed cache group is fully managed by TimesTen and has fixed properties. System managed cache group types include:

  • Read-only cache groups are updated in the Oracle database, and the updates are propagated from Oracle to the cache.

  • Asynchronous writethrough (AWT) cache groups are updated in the cache and the updates are propagated to the Oracle database. Transactions continue executing on the cache without waiting for a commit on Oracle.

  • Synchronous writethrough (SWT) cache groups are updated in the cache and the updates are propagated to the Oracle database. Transactions are committed on the cache after notification that a commit has occurred on Oracle.

Because TimesTen manages system managed cache groups, including loading and unloading the cache group, certain statements and clauses cannot be used in the definition of these cache groups, including:

  • WHERE clauses in AWT and SWT cache group definitions

  • READONLY, PROPAGATE and NOT PROPAGATE in cache table definitions

  • AUTOREFRESH in AWT and SWT cache group definitions

The FLUSH CACHE GROUP and REFRESH CACHE GROUP operations are not allowed for AWT and SWT cache groups.

You must stop the replication agent before creating an AWT cache group.

A user managed cache group must be managed by the application or user. PROPAGATE in a user managed cache group is synchronous. The table-level READONLY keyword can only be used for user managed cache groups.

In addition, both TimesTen and Oracle must be able to parse all WHERE clauses.

Explicitly loaded cache groups and dynamic cache groups

Cache groups can be explicitly or dynamically loaded.

In cache groups that are explicitly loaded, new cache instances are loaded manually into the TimesTen cache tables from the Oracle tables using a LOAD CACHE GROUP or REFRESH CACHE GROUP statement or automatically using an autorefresh operation.

In a dynamic cache group, new cache instances can be loaded manually into the TimesTen cache tables by using a LOAD CACHE GROUP or on demand using a dynamic load operation. In a dynamic load operation, data is automatically loaded into the TimesTen cache tables from the cached Oracle tables when a SELECT, UPDATE, DELETE or INSERT statement is issued on one of the cache tables, where the data is not present in the cache table but does exist in the cached Oracle table. A manual refresh or automatic refresh operation on a dynamic cache group can result in the updating or deleting of existing cache instances, but not in the loading of new cache instances.

Any cache group type (read-only, asynchronous writethrough, synchronous writethrough, user managed) can be defined as an explicitly loaded cache group.

Any cache group type can be defined as a dynamic cache group except a user managed cache group that has both the AUTOREFRESH cache group attribute and the PROPAGATE cache table attribute.

Data in a dynamic cache group is aged out because LRU aging is defined by default. Use the ttAgingLRUConfig built-in procedure to override the space usage thresholds for LRU aging. You can also define time-based aging on a dynamic cache group to override LRU aging.

For more information on explicitly loaded and dynamic cache groups, see Oracle In-Memory Database Cache User's Guide. For more information about the dynamic load operation, see "Dynamically loading a cache instance" in Oracle In-Memory Database Cache User's Guide.

Local and global cache groups

You can create either local or global cache groups.

In a local cache group, data in the cache tables are not shared across TimesTen databases even if the databases are members of the same cache grid. Therefore, the databases can have overlapping data or the same data. Any cache group type can be defined as a local cache group. A local cache group can be either dynamically or explicitly loaded.

In a global cache group, data in the cache tables are shared among TimesTen databases within a cache grid. Updates to the same data by different grid members are coordinated by the grid. Only an AWT cache group can be defined as a global cache group.

For more information on local and global cache groups, see "Defining Cache Groups" in the Oracle In-Memory Database Cache User's Guide. In addition, see "Example of data sharing among the grid members" in Oracle In-Memory Database Cache User's Guide.

Required privilege

CREATE CACHE GROUP or CREATE ANY CACHE GROUP and

CREATE TABLE (if all tables in the cache group are owned by the current user) or CREATE ANY TABLE (if at least one of the tables in the cache group is not owned by the current user).

SQL syntax

There are CREATE CACHE GROUP statements for each type of cache group:

There is one CREATE CACHE GROUP statement to create a global cache group:

CREATE READONLY CACHE GROUP

For read-only cache groups, the syntax is:

CREATE [DYNAMIC] READONLY CACHE GROUP [Owner.]GroupName
 [AUTOREFRESH
  [MODE {INCREMENTAL | FULL}]
  [INTERVAL IntervalValue {MINUTE[S] | SECOND[S] | MILLISECOND[S] }]
  [STATE {ON|OFF|PAUSED}]
 ]
 FROM
  {[Owner.]TableName (
    {ColumnDefinition[,...]}
    [,PRIMARY KEY(ColumnName[,...])]
    [,FOREIGN KEY(ColumnName [,...])
            REFERENCES RefTableName (ColumnName [,...])
                    [ON DELETE CASCADE]
 [UNIQUE HASH ON (HashColumnName[,...]) PAGES=PrimaryPages]
 [AGING USE ColumnName
        LIFETIME Num1 {SECOND[S] | MINUTE[S] |HOUR[S] | DAY[S]}
        [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
 [ON|OFF]
 ]
 [WHERE ExternalSearchCondition]
} [,...];

CREATE ASYNCHRONOUS WRITETHROUGH CACHE GROUP

For asynchronous writethrough cache groups, the syntax is:

CREATE [DYNAMIC] [ASYNCHRONOUS] WRITETHROUGH CACHE GROUP   [Owner.]GroupName
  FROM
   {[Owner.]TableName (
     {ColumnDefinition[,...]}
    [,PRIMARY KEY(ColumnName[,...])]
     [FOREIGN KEY(ColumnName [,...])
          REFERENCES RefTableName (ColumnName [,...])]
                         [ ON DELETE CASCADE ]
 UNIQUE HASH ON (HashColumnName[,...]) PAGES=PrimaryPages]
 [AGING {LRU|
     USE ColumnName
          LIFETIME Num1 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}
         [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
     }[ON|OFF]
 ]
} [,...];

CREATE SYNCHRONOUS WRITETHROUGH CACHE GROUP

For synchronous writethrough cache groups, the syntax is:

CREATE [DYNAMIC] SYNCHRONOUS WRITETHROUGH
CACHE GROUP [Owner.]GroupName
 FROM 
   {[Owner.]TableName (
     {ColumnDefinition[,...]}
    [,PRIMARY KEY(ColumnName[,...])]
     [FOREIGN KEY(ColumnName [,...])
            REFERENCES RefTableName (ColumnName [,...])}]
                             [ ON DELETE CASCADE ]
 [UNIQUE HASH ON (HashColumnName[,...]) PAGES=PrimaryPages]
 [AGING {LRU|
     USE ColumnName
         LIFETIME Num1 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}
         [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
     }[ON|OFF]
 ]
} [,...];

CREATE USERMANAGED CACHE GROUP

For user managed cache groups, the syntax is:

CREATE [DYNAMIC][USERMANAGED] CACHE GROUP [Owner.]GroupName
 [AUTOREFRESH
   [MODE {INCREMENTAL | FULL}]
   [INTERVAL IntervalValue {MINUTE[S] | SECOND[S] | MILLISECOND[S] }]
   [STATE {ON|OFF|PAUSED}]
 ]
  FROM 
   {[Owner.]TableName (
    {ColumnDefinition[,...]}
    [,PRIMARY KEY(ColumnName[,...])]
    [FOREIGN KEY(ColumnName[,...])
          REFERENCES RefTableName (ColumnName [,...])]
                  [ON DELETE CASCADE]
    [, {READONLY | PROPAGATE | NOT PROPAGATE}]
 [UNIQUE HASH ON (HashColumnName[,...]) PAGES=PrimaryPages]
 [AGING {LRU|
         USE ColumnName
             LIFETIME Num1 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}
             [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
        }[ON|OFF]
 ]
 [WHERE ExternalSearchCondition]
} [,...];

CREATE WRITETHROUGH GLOBAL CACHE GROUP

The following syntax demonstrates how to create a global cache group to cache data within a cache grid. Specify the DYNAMIC attribute to enable dynamic load from the Oracle database for the cache group.

CREATE [DYNAMIC] [ASYNCHRONOUS] WRITETHROUGH GLOBAL CACHE GROUP  [Owner.]GroupName
  FROM
   {[Owner.]TableName (
     {ColumnDefinition[,...]}
    [,PRIMARY KEY(ColumnName[,...])]
     [FOREIGN KEY(ColumnName [,...])
          REFERENCES RefTableName (ColumnName [,...])]
                         [ ON DELETE CASCADE ]
 UNIQUE HASH ON (HashColumnName[,...]) PAGES=PrimaryPages]
 [AGING {LRU|
     USE ColumnName
          LIFETIME Num1 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}
         [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
     }[ON|OFF]
 ]
} [,...];

Parameters

Following are the parameters for the cache group definition before the FROM keyword:

ParameterDescription
[Owner.]GroupNameOwner and name assigned to the new cache group.
[DYNAMIC]If specified, a dynamic cache group is created.
AUTOREFRESHThe AUTOREFRESH parameter automatically propagates changes from the Oracle database to the cache group. For details, see "AUTOREFRESH in cache groups".
MODE [INCREMENTAL | FULL]Determines which rows in the cache are updated during an autorefresh. If the INCREMENTAL clause is specified, TimesTen refreshes only rows that have been changed on Oracle since the last propagation. If the FULL clause is specified, TimesTen updates all rows in the cache with each autorefresh. The default autorefresh mode is INCREMENTAL.
INTERVAL IntervalValueIndicates the interval at which autorefresh should occur in units of minutes, seconds or milliseconds. IntervalValue is an integer value that specifies how often autorefresh should be scheduled, in MINUTES, SECONDS or MILLISECONDS. The default IntervalValue value is 5 minutes. If the specified interval is not long enough for an autorefresh to complete, a runtime warning is generated and the next autorefresh waits until the current one finishes. An informational message is generated in the support log if the wait queue reaches 10.
STATE [ON | OFF | PAUSED]Specifies whether autorefresh should be ON or OFF or PAUSED when the cache group is created. You can alter this setting later by using the ALTER CACHE GROUP statement. By default, the AUTOREFRESH state is PAUSED.
FROMDesignates one or more table definitions for the cache group.

Everything after the FROM keyword comprises the definitions of the Oracle tables cached in the cache group. The syntax for each table definition is similar to that of a CREATE TABLE statement. However, primary key constraints are required for the cache group table.

Table definitions have the following parameters:

ParameterDescription
[Owner.]TableNameOwner and name to be assigned to the new table. If you do not specify the owner name, your login becomes the owner name for the new table.
ColumnDefinitionName of an individual column in a table, its data type and whether or not it is nullable. Each table must have at least one column. See "Column Definition".
PRIMARY KEY (ColumnName[,...])Specifies that the table has a primary key. Primary key constraints are required for a cache group. ColumnName is the name of the column that forms the primary key for the table to be created. Up to 16 columns can be specified for the primary key. Cannot be specified with UNIQUE in one specification.
FOREIGN KEY (ColumnName[,...])Specifies that the table has a foreign key. ColumnName is the name of the column that forms the foreign key for the table to be created. See "FOREIGN KEY".
REFERENCES RefTableName (ColumnName[,...])Specifies the table which the foreign key is associated with. RefTableName is the name of the referenced table and ColumnName is the name of the column referenced in the table.
[ON DELETE CASCADE]Enables the ON DELETE CASCADE referential action. If specified, when rows containing referenced key values are deleted from a parent table, rows in child tables with dependent foreign key values are also deleted.
READONLYSpecifies that changes cannot be made on the cached table.
PROPAGATE|NOT PROPAGATESpecifies whether changes to the cached table are automatically propagate to the corresponding Oracle table at commit time.
UNIQUE HASH ON (HashColumnName)Specifies that a hash index is created on this table. HashColumnName identifies the column that is to participate in the hash key of this table. The columns specified in the hash index must be identical to the columns in the primary key.
PAGES=PrimaryPagesSpecifies the expected number of pages in the table. The PrimaryPages number determines the number of hash buckets created for the hash index. The minimum is 1. If your estimate is too small, performance is degraded. See "CREATE TABLE" for more information.
WHERE ExternalSearchConditionThe WHERE clause evaluated by Oracle for the cache group table. This WHERE clause is added to every LOAD and REFRESH operation on the cache group. It may not directly reference other tables. It is parsed by both TimesTen and Oracle. See "Using a WHERE clause" in Oracle In-Memory Database Cache User's Guide.
AGING LRU [ON | OFF]If specified, defines the LRU aging policy on the root table. The LRU aging policy applies to all tables in the cache group. The LRU aging policy defines the type of aging (least recently used (LRU)), the aging state (ON or OFF) and the LRU aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

In dynamic cache groups, LRU aging is set ON by default. You can specify time-based aging instead. Aging is disabled by default on an explicitly loaded global cache group.

LRU aging cannot be specified on a cache group with the autorefresh attribute, unless the cache group is dynamic.

LRU attributes are defined by calling the ttAgingLRUConfig procedure. LRU attributes are not defined at the SQL level.

For more information about LRU aging, see "Implementing aging on a cache group" in Oracle In-Memory Database Cache User's Guide.

AGING USE ColumnName...[ON|OFF]If specified, defines the time-based aging policy on the root table. The time-based aging policy applies to all tables in the cache group. The time-based aging policy defines the type of aging (time-based), the aging state (ON or OFF) and the time-based aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

Time-based aging attributes are defined at the SQL level and are specified by the LIFETIME and CYCLE clauses.

Specify ColumnName as the name of the column used for time-based aging. Define the column as NOT NULL and of data type TIMESTAMP or DATE. The value of this column is subtracted from SYSDATE, truncated using the specified unit (second, minute, hour, day) and then compared to the LIFETIME value. If the result is greater than the LIFETIME value, then the row is a candidate for aging.

The values of the column used for aging are updated by your applications. If the value of this column is unknown for some rows, and you do not want the rows to be aged, define the column with a large default value (the column cannot be NULL).

Aging is disabled by default on an explicitly loaded global cache group.

For more information about time-based aging, see "Implementing aging on a cache group" in Oracle In-Memory Database Cache User's Guide.

LIFETIME Num1 {SECOND[S]|MINUTE[S]|HOUR[S]DAY[S]}LIFETIME is a time-based aging attribute and is a required clause.

Specify the LIFETIME clause after the AGING USE ColumnName clause.

The LIFETIME clause specifies the minimum amount of time data is kept in cache.

Specify Num1 as a positive integer constant to indicate the unit of time expressed in seconds, minutes, hours or days that rows should be kept in cache. Rows that exceed the LIFETIME value are aged out (deleted from the table).

The concept of time resolution is supported. If DAYS is specified as the time resolution, then all rows whose timestamp belongs to the same day are aged out at the same time. If HOURS is specified as the time resolution, then all rows with timestamp values within that hour are aged at the same time. A LIFETIME of 3 days is different than a LIFETIME of 72 hours (3*24) or a LIFETIME of 432 minutes (3*24*60).

[CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S]|DAY[S]}]CYCLE is a time-based aging attribute and is optional. Specify the CYCLE clause after the LIFETIME clause.

The CYCLE clause indicates how often the system should examine rows to see if data exceeds the specified LIFETIME value and should be aged out (deleted).

Specify Num2 as a positive integer constant.

If you do not specify the CYCLE clause, then the default value is 5 minutes. If you specify 0 for Num2, then the aging thread wakes up every second.

If the aging state is OFF, then aging is not done automatically and the CYCLE clause is ignored.


Description

  • Two cache groups cannot have the same owner name and group name. If you do not specify the owner name, your login becomes the owner name for the new cache group.

  • Neither a cache table name nor a cache group name can contain #.

  • Dynamic parameters are not allowed in the WHERE clause.

  • Oracle temporary tables cannot be cached.

  • Each table must correspond to a table in the Oracle database.

  • You cannot use lowercase delimited identifiers to name your cache tables. Table names in TimesTen are case-insensitive and are stored as uppercase. The name of the cache table must be the same as the Oracle table name. Uppercase table names on TimesTen will not match mixed case table names on Oracle. As a workaround, create a synonym for your table in Oracle and use that synonym as the table name for the cache group. This workaround is not available for read-only cache groups or cache groups with the AUTOREFRESH parameter set.

  • Each column in the cache table must match each column in the Oracle table, both in name and in data type. See "Mappings between Oracle and TimesTen data types" in Oracle In-Memory Database Cache User's Guide. In addition, each column name must be fully qualified with an owner and table name when referenced in a WHERE clause.

  • The WHERE clause can only directly refer to the cache group table. Tables that are not in the cache group can only be referenced with a subquery.

  • Generally, you do not have to fully qualify the column names in the WHERE clause of the CREATE CACHE GROUP, LOAD CACHE GROUP, UNLOAD CACHE GROUP, REFRESH CACHE GROUP or FLUSH CACHE GROUP statements. However, since TimesTen automatically generates queries that join multiple tables in the same cache group, a column needs to be fully qualified if there is more than one table in the cache group that contains columns with the same name.

  • By default, a range index is created to enforce the primary key for a cache group table. Use the UNIQUE HASH clause to specify a hash index for the primary key.

    • If your application performs range queries over a cache group table's primary key, then choose a range index for that cache group table by omitting the UNIQUE HASH clause.

    • If, however, your application performs only exact match lookups on the primary key, then a hash index may offer better response time and throughput. In such a case, specify the UNIQUE HASH clause. See "CREATE TABLE" for more information on the UNIQUE HASH clause.

    • Use ALTER TABLE to change the representation of the primary key index for a table.

  • For cache group tables with the PROPAGATE attribute and for tables of SWT and AWT cache groups, foreign keys specified with ON DELETE CASCADE must be a proper subset of foreign keys with ON DELETE CASCADE in the Oracle tables.

  • You cannot execute the CREATE CACHE GROUP statement when performed under the serializable isolation level. An error message is returned when attempted.

AUTOREFRESH in cache groups

The AUTOREFRESH parameter automatically propagates changes from the Oracle database to TimesTen cache groups. For explicitly loaded cache groups, deletes, updates and inserts are automatically propagated from the Oracle database to the cache group. For dynamic cache groups, only deletes and updates are propagated. Inserts to the specified Oracle tables are not propagated to dynamic cache groups. They are dynamically loaded into IMDB Cache when referenced by the application. They can also be explicitly loaded by the application.

To use autorefresh with a cache group, you must specify AUTOREFRESH when you create the cache group. You can change the MODE, STATE and INTERVAL AUTOREFRESH settings after a cache group has been created by using the ALTER CACHE GROUP command. Once a cache group has been specified as either AUTOREFRESH or PROPAGATE, you cannot change these attributes.

TimesTen supports FULL or INCREMENTAL AUTOREFRESH. In FULL mode, the entire cache is periodically unloaded and then reloaded. In INCREMENTAL mode, TimesTen installs triggers in the Oracle database to track changes and periodically updates only the rows that have changed in the specified Oracle tables. The first incremental refresh is always a full refresh, unless the autorefresh state is PAUSED. The default mode is INCREMENTAL.

FULL AUTOREFRESH is more efficient when most of the Oracle table rows have been changed. INCREMENTAL AUTOREFRESH is more efficient when there are fewer changes.

TimesTen schedules an autorefresh operation when the transaction that contains a statement with AUTOREFRESH specified is committed. The statement types that cause autorefresh to be scheduled are:

  • A CREATE CACHE GROUP statement in which AUTOREFRESH is specified, and the AUTOREFRESH state is specified as ON.

  • An ALTER CACHE GROUP statement in which the AUTOREFRESH state has been changed to ON.

  • A LOAD CACHE GROUP statement on an empty cache group whose autorefresh state is PAUSED.

The specified interval determines how often autorefresh occurs.

The current STATE of AUTOREFRESH can be ON, OFF or PAUSED. By default, the autorefresh state is PAUSED.

The NOT PROPAGATE attribute cannot be used with the AUTOREFRESH attribute.

Aging in cache groups

  • You can implement sliding windows with time-based aging. See "Configuring a sliding window" in Oracle In-Memory Database Cache User's Guide.

  • After you have defined an aging policy for the table, you cannot change the policy from LRU to time-based or from time-based to LRU. You must first drop aging and then alter the table to add a new aging policy.

  • The aging policy must be defined to change the aging state.

  • LRU and time-based aging can be combined in one system. If you use only LRU aging, the aging thread wakes up based on the cycle specified for the whole database. If you use only time-based aging, the aging thread wakes up based on an optimal frequency. This frequency is determined by the values specified in the CYCLE clause for all tables. If you use both LRU and time-based aging, then the thread wakes up based on a combined consideration of both types.

  • Call the ttAgingScheduleNow procedure to schedule the aging process right away regardless if the aging state is ON or OFF.

  • The following rules determine if a row is accessed or referenced for LRU aging:

    • Any rows used to build the result set of a SELECT statement.

    • Any rows used to build the result set of an INSERT...SELECT statement.

    • Any rows that are about to be updated or deleted.

  • Compiled commands are marked invalid and need recompilation when you either drop LRU aging from or add LRU aging to tables that are referenced in the commands.

  • For LRU aging, if a child row is not a candidate for aging, then neither this child row nor its parent row are deleted. ON DELETE CASCADE settings are ignored.

  • For time-based aging, if a parent row is a candidate for aging, then all child rows are deleted. ON DELETE CASCADE (whether specified or not) is ignored.

  • Specify either the LRU aging or time-based aging policy on the root table. The policy applies to all tables in the cache group.

  • For the time-based aging policy, you cannot add or modify the aging column. This is because you cannot add or modify a NOT NULL column.

  • Restrictions on defining aging for a cache group:

    • LRU aging is not supported on a cache group defined with the autorefresh attribute, unless it is a dynamic cache group.

    • Aging is disabled by default on an explicitly loaded global cache group.

    • The aging policy cannot be added, altered, or dropped for read-only cache groups or cache groups with the AUTOREFRESH attribute while the cache agent is active. Stop the cache agent first.

    • You cannot drop the column that is used for time-based aging.

Cache grid

To cache data in a cache grid, you must create an asynchronous writethrough global cache group. Before you can create this cache group, the TimesTen database must be associated with a cache grid. For more information on creating and using a cache grid and creating and using global cache groups, see "Configuring a cache grid" and "Global cache groups" in Oracle In-Memory Database Cache User's Guide.

Examples

Create a read-only cache group:

CREATE READONLY CACHE GROUP customerorders
AUTOREFRESH INTERVAL 10 MINUTES
FROM
customer (custid INT NOT NULL,
       name CHAR(100) NOT NULL,
       addr CHAR(100),
       zip INT,
       region CHAR(10),
       PRIMARY KEY(custid)),
ordertab (orderid INT NOT NULL,
       custid INT NOT NULL,
       PRIMARY KEY (orderid),
       FOREIGN KEY (custid) REFERENCES customer(custid));

Create an asynchronous writethrough cache group:

CREATE ASYNCHRONOUS WRITETHROUGH CACHE GROUP cstomers
FROM
customer (custid INT NOT NULL,
       name CHAR(100) NOT NULL,
       addr CHAR(100),
       zip INT,
       PRIMARY KEY(custid));

Create a synchronous writethrough cache group:

CREATE SYNCHRONOUS WRITETHROUGH CACHE GROUP customers
FROM
customer (custid INT NOT NULL,
       name CHAR(100) NOT NULL,
       addr CHAR(100),
       zip INT,
       PRIMARY KEY(custid));

Create a user managed cache group:

CREATE USERMANAGED CACHE GROUP updateanywherecustomers
AUTOREFRESH
       MODE INCREMENTAL
       INTERVAL 30 SECONDS
       STATE ON
FROM
customer (custid INT NOT NULL,
       name CHAR(100) NOT NULL,
       addr CHAR(100),
       zip INT,
       PRIMARY KEY(custid),
       PROPAGATE);

Create a cache group with time-based aging. Specify agetimestamp as the column for aging. Specify LIFETIME 2 hours, CYCLE 30 minutes. Aging state is not specified, so the default setting (ON) is used.

CREATE READONLY CACHE GROUP agingcachegroup
AUTOREFRESH
       MODE INCREMENTAL
       INTERVAL 5 MINUTES
       STATE PAUSED
FROM
customer (customerid NUMBER NOT NULL,
       agetimestamp TIMESTAMP NOT NULL,
       PRIMARY KEY (customerid))
       AGING USE agetimestamp LIFETIME 2 HOURS CYCLE 30 MINUTES;

Command> DESCRIBE customer;
Table USER.CUSTOMER:
  Columns:
   *CUSTOMERID                      NUMBER NOT NULL
    AGETIMESTAMP                    TIMESTAMP (6) NOT NULL
  AGING USE AgeTimestamp LIFETIME 2 HOURS CYCLE 30 MINUTES ON
1 table found.
(primary key columns are indicated with *)

Use a synonym for a mixed case delimited identifier table name in the Oracle database so the mixed case table name can be cached in TimesTen. First attempt to cache the mixed case Oracle table name. You see the error "Could not find 'NameofTable' in Oracle":

Command> AUTOCOMMIT 0;
Command> PASSTHROUGH 3;
Command> CREATE TABLE "MixedCase" (col1 NUMBER PRIMARY KEY NOT NULL);
Command> INSERT INTO "MixedCase" VALUES (1);
1 row inserted.
Command> COMMIT;
Command> CREATE CACHE GROUP MixedCase1 from "MixedCase" 
        (col1 NUMBER PRIMARY KEY NOT NULL);
 5140: Could not find SAMPLEUSER.MIXEDCASE in Oracle.  May not have privileges.
The command failed.

Now, using the PassThrough attribute, create the synonym "MIXEDCASE" in the Oracle database and use that synonym as the table name.

Command> AUTOCOMMIT 0;
Command> PASSTHROUGH 3;
Command> CREATE SYNONYM "MIXEDCASE" FOR "MixedCase";
Command> COMMIT;
Command> CREATE CACHE GROUP MixedCase2 FROM "MIXEDCASE" 
         (col1 NUMBER PRIMARY KEY NOT NULL);
Warning  5147: Cache group contains synonyms
Command> COMMIT;

Attempt to use a synonym name with a read-only cache group or a cache group with the AUTOREFRESH attribute. You see an error:

Command> AUTOCOMMIT 0;
Command> PASSTHROUGH 3;
Command> CREATE SYNONYM "MIXEDCASE_AUTO" FOR "MixedCase";
Command> COMMIT;
Command> CREATE READONLY CACHE GROUP MixedCase3 AUTOREFRESH MODE
         INCREMENTAL INTERVAL 10 MINUTES FROM "MIXEDCASE_AUTO" 
         (Col1 NUMBER PRIMARY KEY NOT NULL);
 5142: Autorefresh is not allowed on cache groups with Oracle synonyms
The command failed.

See also


ALTER CACHE GROUP
ALTER TABLE
DROP CACHE GROUP
FLUSH CACHE GROUP
LOAD CACHE GROUP
UNLOAD CACHE GROUP

CREATE FUNCTION

The CREATE FUNCTION statement creates a standalone stored function.

Required privilege

CREATE PROCEDURE (if owner) or CREATE ANY PROCEDURE (if not owner).

SQL syntax

CREATE [OR REPLACE] FUNCTION [Owner.]FunctionName 
     [(arguments [IN|OUT|IN OUT][NOCOPY] DataType [DEFAULT expr][,...])]
     RETURN DataType [InvokerRightsClause] [DETERMINISTIC]
     {IS|AS} PlsqlFunctionBody

The syntax for the InvokerRightsClause:

AUTHID {CURRENT_USER|DEFINER}

You can specify InvokerRightsClause or DETERMINISTIC in any order.

Parameters

ParameterDescription
OR REPLACESpecify OR REPLACE to re-create the function if it already exists. Use this clause to change the definition of an existing function without dropping and re-creating it. When you re-create a function, TimesTen recompiles it.
FunctionNameName of function.
argumentsName of argument or parameter. You can specify 0 or more parameters for the function. If you specify a parameter, you must specify a data type for the parameter. The data type must be a PL/SQL data type.

For more information on PL/SQL data types, see Chapter 3, "PL/SQL Data Types" in the Oracle Database PL/SQL Language Reference.

IN| OUT |IN OUTParameter modes.

IN is a read-only parameter. You can pass the parameter's value into the function but the function cannot pass the parameter's value out of the function and back to the calling PL/SQL block.The value of the parameter cannot be changed.

OUT is a write-only parameter. Use an OUT parameter to pass a value back from the function to the calling PL/SQL block. You can assign a value to the parameter.

IN OUT is a read/write parameter. You can pass values into the function and return a value back to the calling program (either the original, unchanged value or a new value set within the function.

IN is the default.

NOCOPYSpecify NOCOPY to instruct TimesTen to pass the parameter as fast as possible. You can enhance performance when passing a large value such as a record, an index-by-table, or a varray to an OUT or IN OUT parameter. IN parameters are always passed NOCOPY.

For more information on NOCOPY, see Oracle Database SQL Language Reference.

DEFAULT exprUse this clause to specify a default value for the parameter. You can specify := in place of the keyword DEFAULT.
RETURN DataTypeRequired clause. A function must return a value. You must specify the data type of the return value of the function.

Do not specify a length, precision, or scale for the data type.

The data type is a PL/SQL data type.

For more information on PL/SQL data types, see Chapter 3, "PL/SQL Data Types" in the Oracle Database PL/SQL Language Reference.

InvokerRightsClauseLets you specify whether the SQL statements in PL/SQL functions or procedures execute with definer's or invoker's rights. The AUTHID setting affects the name resolution and privilege checking of SQL statements that a PL/SQL procedure or function issues at runtime, as follows:
  • Specify DEFINER so that SQL name resolution and privilege checking operate as though the owner of the procedure or function (the definer, in whose schema it resides) is running it. DEFINER is the default.

  • Specify CURRENT_USER so that SQL name resolution and privilege checking operate as though the current user (the invoker) is running it.

For more information, see the "Definer's rights and invoker's rights" section in the Oracle TimesTen In-Memory Database PL/SQL Developer's Guide or the Oracle Database PL/SQL Language Reference.

DETERMINISTICSpecify DETERMINISTIC to indicate that the function should return the same result value whenever it is called with the same values for its parameters.

For more information on the DETERMNISTIC clause, see Oracle Database SQL Language Reference.

IS|ASSpecify either IS or AS to declare the body of the function.
plsql_function_specSpecifies the function body.

Restrictions

TimesTen does not support:

  • parallel_enable_clause. You can specify the clause, but it has no effect.

  • call_spec clause

  • AS EXTERNAL

In a replication environment, the CREATE FUNCTION statement is not replicated. For more information, see "Creating a new PL/SQL object in an existing active standby pair" and "Adding a PL/SQL object to an existing replication scheme" in the Oracle TimesTen In-Memory Database Replication Guide.

When you create or replace a function, the privileges granted on the function remain the same. If you drop and re-create the object, the object privileges that were granted on the original object are revoked.

Examples

Create function get_sal with one input parameter. Return salary as type NUMBER.

Command> CREATE OR REPLACE FUNCTION get_sal
       >   (p_id employees.employee_id%TYPE) RETURN NUMBER IS
       >   v_sal employees.salary%TYPE := 0;
       > BEGIN
       >   SELECT salary INTO v_sal FROM employees
       >     WHERE employee_id = p_id;
       >   RETURN v_sal;
       > END get_sal;
       > /
 
Function created.

See also

Oracle Database PL/SQL Language Reference and Oracle Database SQL Language Reference


CREATE INDEX

The CREATE INDEX statement creates either a range or bitmap index on one or more columns of a table or materialized view.


Note:

Consider using a hash index if your application uses exact match search. Hash indexes provide performance gains over range indexes. Create a hash index using CREATE TABLE.

Required privilege

No privilege is required for table or materialized view owner.

INDEX for another user's table or materialized view.

SQL syntax

CREATE [UNIQUE|BITMAP] INDEX [Owner.]IndexName ON
[Owner.]TableName ({ColumnName [ASC | DESC]}
[,... ] )

Parameters

ParameterDescription
UNIQUEProhibits duplicates in the index. If UNIQUE is specified, each possible combination of index key column values can occur in only one row of the table. If UNIQUE is omitted, duplicate values are allowed. When you create a unique index, all existing rows must have unique values in the indexed columns. If you specify UNIQUE, TimesTen creates a range index.

A range index:

  • Speeds up range searches (but can also be used for efficient equality searches)

  • Is optimized for in-memory data management

  • Provides efficient sorting by column value

BITMAPSpecify CREATE BITMAP INDEX to create an index where the information about rows with each unique value is encoded in a bitmap. Each bit in the bitmap corresponds to a row in the table.

Use a bitmap index for columns that do not have many unique values.

[Owner.] IndexNameName to be assigned to the new index. A table cannot have two indexes with the same name. If the owner is specified, it must be the same as the owner of the table.
[Owner.] TableNameDesignates the table or materialized view for which an index is to be created.
ColumnNameName of a column to be used as an index key. You can specify up to 16 columns in order from major index key to minor index key.
[ASC|DESC]Specifies the order of the index to be either ascending (the default) or descending. In TimesTen, this parameter is currently ignored.

Description

  • TimesTen creates a non-unique range index by default. Specify UNIQUE to create a unique range index. Specify BITMAP to create a bitmap index.

  • Specify a bitmap index on each column to increase the performance of complex queries that specify multiple predicates on multiple columns connected by the AND or OR operator. At runtime, TimesTen finds bitmaps of rows that satisfy each predicate and bitmaps from different predicates are combined using bitwise logical operation and then the resultant bitmaps are converted to qualified rows.

  • Bitmap indexes are used to satisfy these predicates:

    • Equality predicates. For example: 'x1 = 1'

    • Range predicates. For example: 'y1 > 10' and'z1 BETWEEN 1 and 10'

    • AND predicates. For example: 'x1 > 10 AND y1 > 10'

    • OR predicates. For example: 'x1 > 10 OR y1 > 10'

    • Complex predicates with AND or OR. For example: '(x1 > 10 AND y1 > 10) OR (z1 > 10)'

    • NOT EQUAL predicate with AND. For example: 'x1 = 1 and y1 != 1'

  • Bitmap indexes:

    • COUNT (*) optimization counts rowids from bitmaps.

    • Are used to optimize queries that group by a prefix of columns of the bitmap index.

    • Are used to optimize distinct queries and order by queries.

    • Are used in a MERGE join.

  • The CREATE INDEX statement enters the definition of the index in the system catalog and initializes the necessary data structures. Any rows in the table are then added to the index. In TimesTen, performance is the same regardless of whether the table is created, indexed and populated or created, then populated and indexed.

  • If UNIQUE is specified, all existing rows must have unique values in the indexed column(s).

  • The new index is maintained automatically until the index is deleted by a DROP INDEX statement or until the table associated with it is dropped.

  • Any prepared statements that reference the table with the new index are automatically prepared again the next time they are executed. Then the statements can take advantage, if possible, of the new index.

  • NULL compares higher than all other values for sorting.

  • An index on a temporary table cannot be created by a connection if any other connection has a non-empty instance of the table.

  • If you are using linguistic comparisons, you can create a linguistic index. A linguistic index uses sort key values and storage is required for these values. Only one unique value for NLS_SORT is allowed for an index. For more information on linguistic indexes and linguistic comparisons, see "Using linguistic indexes" in Oracle TimesTen In-Memory Database Operations Guide.

  • If you create indexes that are redundant, TimesTen generates warnings or errors. Call ttRedundantIndexCheck to see the list of redundant indexes for your tables.

  • In a replicated environment for an active standby pair, if DDL_REPLICATION_LEVEL=2 when you execute the CREATE INDEX on the active database, the index will be replicated to all databases in the replication scheme. The table on which the index is created must be empty. See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

  • Indexes can be created on over any columns in the table. This includes compressed columns, even columns that exist in separate compression column groups.

Examples

Create a table and then create a bitmap index on the table. Use the ttIsql SHOWPLAN command to verify that the bitmap index is used in the query:

Command> CREATE TABLE tab1 (id NUMBER);
Command> INSERT INTO tab1 VALUES (10);
1 row inserted.
Command> INSERT INTO tab1 VALUES (20);
1 row inserted.
Command> CREATE BITMAP INDEX bitmap_id ON tab1 (id);
Command> COMMIT;
Command> SET AUTOCOMMIT OFF;
Command> SHOWPLAN 1;
Command> SELECT * FROM tab1 WHERE id = 10;
 
Query Optimizer Plan:
 
  STEP:                1
  LEVEL:               1
  OPERATION:           RowLkBitmapScan
  TBLNAME:             TAB1
  IXNAME:              BITMAP_ID
  INDEXED CONDITION:   TAB1.ID = 10
  NOT INDEXED:         <NULL>
 
< 10 >
1 row found.

The regions table in the HR schema creates a unique index on region_id. Issue the ttIsql INDEXES command on table regions. You see the unique range index regions.

Command> INDEXES REGIONS;

Indexes on table SAMPLEUSER.REGIONS:
  REGIONS: unique range index on columns:
    REGION_ID
    (referenced by foreign key index COUNTR_REG_FK on table SAMPLEUSER.COUNTRIES)
  1 index found.

1 index found on 1 table.

Attempt to create a unique index i on table regions indexing on column region_id. You see a warning message:

Command> CREATE UNIQUE INDEX i ON regions (region_id);
Warning  2232: New index I is identical to existing index REGIONS; 
consider dropping index I

Call ttRedundantIndexCheck to see warning message for this index:

Command> CALL ttRedundantIndexCheck ('regions');
< Index SAMPLEUSER.REGIONS.I is identical to index SAMPLEUSER.REGIONS.REGIONS;
consider dropping index SAMPLEUSER.REGIONS.I >
1 row found.

Create table redundancy and define columns co11 and col2. Create two user indexes on col1 and col2. You see an error message when you attempt to create the second index r2. Index r1 is created. Index r2 is not created.

Command> CREATE TABLE redundancy (col1 CHAR (30), col2 VARCHAR2 (30));
Command> CREATE INDEX r1 ON redundancy (col1, col2);
Command> CREATE INDEX r2 ON redundancy (col1, col2);
 2231: New index R2 would be identical to existing index R1
The command failed.

Issue the ttIsql command INDEXES on table redundancy to show that only index r1 is created:

Command> INDEXES redundancy;

Indexes on table SAMPLEUSER.REDUNDANCY:
  R1: non-unique range index on columns:
    COL1
    COL2
  1 index found.

1 index found on 1 table.

This unique index ensures that all part numbers are unique.

CREATE UNIQUE INDEX purchasing.partnumindex
ON purchasing.parts (partnumber);

Create a linguistic index named german_index on table employees1. If you want to have more than one linguistic sort, create a second linguistic index.

Command> CREATE TABLE employees1 (id CHARACTER (21),
id2 character (21));
Command> CREATE INDEX german_index ON employees1
  (NLSSORT(id, 'NLS_SORT=GERMAN'));
Command> CREATE INDEX german_index2 ON employees1
  NLSSORT(id2, 'nls_sort=german_ci'));
Command> indexes employees1;
Indexes on table SAMPLEUSER.EMPLOYEES1:
  GERMAN_INDEX: non-unique range index on columns:
    NLSSORT(ID,'NLS_SORT=GERMAN')
  GERMAN_INDEX2: non-unique range index on columns:
    NLSSORT(ID2,'nls_sort=german_ci')
  2 indexes found.
1 table found.

See also

DROP INDEX


CREATE MATERIALIZED VIEW

The CREATE MATERIALIZED VIEW statement creates a view of the table specified in the SelectQuery clause. The original tables used to create a view are referred to as detail tables. The view can be refreshed synchronously or asynchronously with regard to changes in the detail tables. If you create an asynchronous materialized view, you must first create a materialized view log on the detail table. See "CREATE MATERIALIZED VIEW LOG".

Required privilege

  • User executing the statement must have CREATE MATERIALIZED VIEW (if owner) or CREATE ANY MATERIALIZED VIEW (if not owner).

  • Owner of the materialized view must have SELECT on the detail tables.

  • Owner of the materialized view must have CREATE TABLE.

SQL syntax

CREATE MATERIALIZED VIEW [Owner.]ViewName
      [REFRESH 
        { FAST | COMPLETE } |
              [NEXT SYSDATE[+NUMTODSINTERVAL(IntegerLiteral,IntervalUnit)]] 
        |  NEXT SYSDATE[+NUMTODSINTERVAL(IntegerLiteral,IntervalUnit) ]
      ]
      AS SelectQuery
      [PRIMARY KEY (ColumnName [,...])] 
      [UNIQUE HASH ON (HashColumnName [,...]) PAGES = PrimaryPages]

Parameters

ParameterDescription
[Owner.]ViewNameName assigned to the new view.
REFRESHSpecifies an asynchronous materialized view.
FAST | COMPLETERefresh methods. FAST specifies incremental refresh. COMPLETE specifies full refresh.
NEXT SYSDATEIf NEXT SYSDATE is specified without NUMTODSINTERVAL, the materialized view is refreshed incrementally every time a detail table is modified. The refresh occurs in a separate transaction immediately after the transaction that modifies the detail table has been committed. You cannot specify a full refresh (COMPLETE) every time a detail table is modified.

If NEXT SYSDATE is omitted, then the materialized view will not be refreshed automatically. It must be refreshed manually.

If NEXT SYSDATE is provided without FAST or COMPLETE specified, COMPLETE is the default refresh method.

[+NUMTODSINTERVAL(IntegerLiteral,
IntervalUnit)]
If specified, the materialized view is refreshed at the specified interval. IntegerLiteral must be an integer. IntervalUnit must be one of the following values: 'DAY', 'HOUR', 'MINUTE', 'SECOND'.

If [NEXT SYSDATE[+NUMTODSINTERVAL(IntegerLiteral),IntervalUnit] is not specified, the materialized view is not refreshed automatically. You can manually refresh the view by using the REFRESH MATERIALIZED VIEW statement.

SelectQuerySelect column from the detail tables to be used in the view.
ColumnNameName of the column(s) that forms the primary key for the view to be created. Up to 16 columns can be specified for the primary key. Each result column name of a viewed table must be unique. The column name definition cannot contain the table or owner component.
UNIQUE HASH ONHash index for the table. Only unique hash indexes are created. This parameter is used for equality predicates. UNIQUE HASH ON requires that a primary key be defined.
HashColumnNameColumn defined in the view that is to participate in the hash key of this table. The columns specified in the hash index must be identical to the columns in the primary key.
PrimaryPagesSpecifies the expected number of pages in the table. This number determines the number of hash buckets created for the hash index. The minimum is 1. If your estimate is too small, performance is degraded. See "CREATE TABLE" section for more information.

Description

Restrictions for all materialized views are as follows:

  • You cannot create a materialized view on a detail table that includes a LOB column.

For synchronous materialized views or asynchronous materialized views that use complete refresh, the following is true for the SELECT statement:

  • * Outer joins are allowed, but the SELECT list must project at least one non-nullable column from each of the inner tables specified in the OUTER JOIN.

  • OUTER JOIN syntax for a SELECT in a materialized view definition is identical to that in a top-level SELECT.

  • The restrictions noted in the description of SELECT statements apply. The (+) symbol must be used to specify outer joins of a materialized view.

Restrictions on synchronous materialized view and detail tables:

  • A materialized view is read-only and cannot be updated directly. A materialized view is updated only when changes are made to the associated detail tables. Therefore a materialized view cannot be the target of a DELETE, UPDATE or INSERT statement.

  • Materialized views defined on replicated tables may result in replication failures or inconsistencies if the materialized view is specified so that overflow or underflow conditions occur when the materialized view is updated.

  • Detail tables can be replicated, but materialized views themselves cannot be replicated. If detail tables are replicated, TimesTen automatically updates the corresponding views.

  • A materialized view and its detail tables cannot be part of a cache group.

  • Referential constraints cannot be defined on materialized views.

  • If REFRESH is specified, at least one of the refresh options of refresh method (FAST or COMPLETE) or the refresh interval (NEXT SYSDATE) must be specified. If you omit REFRESH, the materialized view is updated synchronously with updates from the detail tables.

  • If you create an asynchronous materialized view with REFRESH FAST, it is recommended that you update the statistics on the materialized view log, materialized view and the base table on which the materialized view is created to increase the performance for the base table and updates on the materialized view.

  • By default, a range index is created to enforce the primary key for a materialized view. Use the UNIQUE HASH clause to specify a hash index for the primary key.

    • If your application performs range queries over a materialized view's primary key, then choose a range index for that view by omitting the UNIQUE HASH clause.

    • If your application performs only exact match lookups on the primary key, then a hash index may offer better response time and throughput. In such a case, specify the UNIQUE HASH clause. See "CREATE TABLE" for more information about the UNIQUE HASH clause.

  • Use ALTER TABLE to change the representation of the primary key index or resize a hash index.

  • You cannot add or drop columns in the materialized view with the ALTER TABLE statement. To change the structure of the materialized view, drop and re-create the view.

  • You can create indexes on the materialized view with the CREATE INDEX SQL statement.

  • Use the DROP [MATERIALIZED] VIEW statement to drop a materialized view.

There are several restrictions on the query that is used to define the materialized view:

  • A SELECT * query in a materialized view definition is expanded when the view is created. Columns added to the detail table after a materialized view is created do not affect the materialized view.

  • Temporary tables cannot be used in a materialized view definition. Nonmaterialized views and derived tables cannot be used to define a materialized view.

  • All columns in the GROUP BY list must be included in the select list.

  • Aggregate view must include a COUNT(*) in the select list.

  • SUM and COUNT are allowed, but not expressions involving them, including AVG.

  • The following cannot be used in a SELECT statement that is creating a materialized view:

    • DISTINCT

    • FIRST

    • HAVING

    • ORDER BY

    • UNION

    • UNION ALL

    • MINUS

    • INTERSECT

    • JOIN

    • User functions: USER, CURRENT_USER, SESSION_USER

    • Subqueries

    • NEXTVAL and CURRVAL

    • Derived tables and joined tables

  • Each expression in the select list must have a unique name. The name of a simple column expression is that column's name unless a column alias is defined. ROWID is considered an expression and needs an alias.

  • No SELECT FOR UPDATE or SELECT FOR INSERT statements can be used on a view.

  • Each inner table can only be outer joined with at most one table.

  • Self joins are allowed. A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition.

There are no additional restrictions on asynchronous materialized views with full (COMPLETE) refresh.

In addition to the restrictions in a SELECT statement that is creating a materialized view, the following restrictions apply when creating asynchronous materialized views with incremental (FAST) refresh:

  • Aggregate functions are not supported

  • Outer joins are not supported.

  • The SELECT list must include the ROWID or the primary key columns for all the detail tables.

  • The materialized view log must be created for each detail table in the asynchronous material view with incremental refresh before creating the asynchronous materialized view.

  • The materialized view log must include all the columns used in the asynchronous materialized views.

  • TimesTen creates a unique index for a asynchronous materialized views that are refreshed incrementally. The index is created on the primary key or ROWID of the detail tables included in the SELECT list.

Invalid materialized views

The owner of a materialized view must have the SELECT privilege on its detail tables. The SELECT privilege is implied by the SELECT ANY TABLE and ADMIN system privileges. When the SELECT privilege or a higher-level system privilege on the detail tables is revoked from the owner of the materialized view, the materialized view becomes invalid.

You can select from an invalid asynchronous materialized view. Refreshing an invalid asynchronous materialized view fails with an error.

Selecting from an invalid synchronous materialized view fails with an error. Updates to the detail tables of an invalid synchronous materialized view do not update the materialized view.

You can identify invalid materialized views by using the ttIsql describe command and by inspecting the STATUS column of the SYS.DBA_OBJECTS, SYS.ALL_OBJECTS or SYS.USER_OBJECTS system tables. See Oracle TimesTen In-Memory Database System Tables and Views Reference .

If the revoked privilege is restored, you can make an invalid materialized view valid again by:

  • Dropping and then re-creating the materialized view

  • Refreshing an invalid asynchronous materialized view if it was originally specified with complete refreshes

For more information, see "Object privileges for materialized views" in Oracle TimesTen In-Memory Database Operations Guide.

Examples

Create a materialized view of columns from the customer and bookorder tables.

CREATE MATERIALIZED VIEW custorder AS
  SELECT custno, custname, ordno, book
    FROM customer, bookorder
    WHERE customer.custno=bookorder.custno;

Create a materialized view of columns x1 and y1 from the t1 table.

CREATE MATERIALIZED VIEW v1 AS SELECT x1, y1 FROM t1
  PRIMARY KEY (x1) UNIQUE HASH (x1) PAGES=100;

Create a materialized view from an outer join of columns x1 and y1 from the t1 and t2 tables.

CREATE MATERIALIZED VIEW v2 AS SELECT x1, y1 FROM t1, t2
  WHERE x1=x2(+);

Create an asynchronous materialized view called empmatview with incremental refresh. The materialized view will be refreshed immediately after updates to employees have been committed. The columns in empmatview are employee_id and email. You must create a materialized view log before you create an asynchronous materialized view.

CREATE MATERALIZED VIEW empmatview 
  REFRESH FAST NEXT SYSDATE 
  AS SELECT employee_id, email FROM employees;
107 rows materialized.

Create an asynchronous materialized view called empmatview1 with complete refresh. A full refresh of the materialized view occurs every 10 days. The columns in empmatview are employee_id and email. You must create a materialized view log before you create an asynchronous materialized view.

CREATE MATERIALIZED VIEW empmatview1
    REFRESH COMPLETE NEXT SYSDATE+NUMTODSINTERVAL(10,'day')
    AS SELECT employee_id, email FROM employees;
107 rows materialized.

The following example creates a materialized view empmatview2 based on selected columns employee_id and email from table employees. After the materialized view is created, create an index on the materialized view column mvemp_id of the materialized view empmatview2.

CREATE MATERIALIZED VIEW empmatview2
   AS SELECT employee_id mvemp_id, email mvemail 
         FROM employees;
107 rows materialized. 

CREATE INDEX empmvindex ON empmatview2 (mvemp_id);

See also


CREATE MATERIALIZED VIEW LOG
CREATE TABLE
CREATE VIEW
DROP [MATERIALIZED] VIEW
REFRESH MATERIALIZED VIEW

CREATE MATERIALIZED VIEW LOG

The CREATE MATERIALIZED VIEW LOG statement creates a log in which changes to the detail table are recorded. The log is required for an asynchronous materialized view that is refreshed incrementally. The log must be created before the materialized view is created. The log is a table in the user's schema called MVLOG$_detailTableID, where detailTableID is a system-generated ID.

This statement also creates other objects for internal use:

  • A global temporary table called MVLGT$_detailTableID

  • A sequence called MVSEQ$_detailTableID

The objects are dropped when the DROP MATERIALIZED VIEW LOG statement is executed.

Required privileges

SELECT on the detail table and

CREATE TABLE or CREATE ANY TABLE (if not owner).

SQL syntax

CREATE MATERIALIZED VIEW LOG ON [Owner.]TableName
  [ WITH 
       { PRIMARY KEY[, ROWID] | 
         ROWID[, PRIMARY KEY } [(columnName[,...])] 
       | (columnName[,...])
  ]

Parameters

ParameterDescription
[Owner.]TableNameName of the detail table for the materialized view
[(columnName[,...])List of columns for which changes will be recorded in the log. You cannot include the primary key columns in the column list when you specify the PRIMARY KEY option.

Description

  • Use the WITH clause to indicate the keys and columns for which changes will be recorded in the materialized view log. If you specify the WITH clause, the following applies:

    • Specify either the PRIMARY KEY or ROWID when using the WITH clause. However, if the WITH clause is specified without either option, it defaults implicitly to use PRIMARY KEY. In addition, the materialized view log defaults to use PRIMARY KEY if the WITH clause is omitted altogether.

    • Specify PRIMARY KEY to record changes in the primary key columns.

    • Specify the ROWID option to record the rowid of all changed rows. The ROWID option is useful when the table does not have a primary key or when you do not want to use the primary key when you create the materialized view.

    • You can specify both PRIMARY KEY and ROWID. The materialized view log may be used by more than one asynchronous materialized view using the specified table as the detail table. However, you can only specify one PRIMARY KEY clause, one ROWID clause and one column list for a materialized view log.

  • Only one materialized view log is created for a table, even if the table is the detail table for more than one materialized view with FAST refreshes. Make sure to include all the columns that are used in different asynchronous materialized views with FAST refresh.

  • A materialized view log cannot be created using a materialized view as the table or for tables in cache groups.

  • A materialized view log cannot be altered to add or drop columns.

Examples

Create a materialized view log on the employees table. Include employee_id (the primary key) and email in the log.

CREATE MATERIALIZED VIEW LOG ON employees WITH PRIMARY KEY (email);

You can create the same materialized view log on the employees table without specifying PRIMARY KEY, which is the default and so is implied, as follows:

CREATE MATERIALIZED  VIEW LOG ON employees WITH (email);

To create a materialized view log on the employees table with only the primary key, execute the following:

CREATE MATERIALIZED VIEW LOG ON employees;

Create a materialized view log on the employees table. Include employee_id (the primary key) and row id in the log.

Command> CREATE MATERIALIZED VIEW LOG ON employees WITH primary key, rowid;

Create a materialized view log on the employees table. Include row id in the log.

Command> CREATE MATERIALIZED VIEW LOG ON employees WITH rowid;

Create a materialized view log on the employees table. Include row id, primary key (employee_id) and email in the log.

Command> CREATE MATERIALIZED VIEW LOG ON employees WITH rowid, primary key (email);

Create a materialized view log on the employees table. Include primary key, by default), and two other columns of email and last_name in the log.

Command> CREATE MATERIALIZED VIEW LOG ON employees WITH (email, last_name);

See also


CREATE MATERIALIZED VIEW
DROP MATERIALIZED VIEW LOG

CREATE PACKAGE

The CREATE PACKAGE statement creates the specification for a standalone package, which is an encapsulated collection of related procedures, functions, and other program objects stored together in your database. The package specification declares these objects. The package body defines these objects.

Required privilege

CREATE PROCEDURE (if owner) or CREATE ANY PROCEDURE (if not owner).

SQL syntax

CREATE [OR REPLACE] PACKAGE [Owner.]PackageName 
      [InvokerRightsClause] {IS|AS}
      PlsqlPackageSpec

The syntax for the InvokerRightsClause:

AUTHID {CURRENT_USER | DEFINER}

Parameters

ParameterDescription
OR REPLACESpecify OR REPLACE to re-create the package specification if it already exists. Use this clause to change the specification of an existing package without dropping and recreating the package. When you change a package specification, TimesTen recompiles it.
PackageNameName of the package.
InvokerRightsClauseLets you specify whether the SQL statements in PL/SQL functions or procedures execute with definer's or invoker's rights. The AUTHID setting affects the name resolution and privilege checking of SQL statements that a PL/SQL procedure or function issues at runtime, as follows:
  • Specify DEFINER so that SQL name resolution and privilege checking operate as though the owner of the procedure or function (the definer, in whose schema it resides) is running it. DEFINER is the default.

  • Specify CURRENT_USER so that SQL name resolution and privilege checking operate as though the current user (the invoker) is running it.

For more information, see the "Definer's rights and invoker's rights" section in the Oracle TimesTen In-Memory Database PL/SQL Developer's Guide or the Oracle Database PL/SQL Language Reference.

IS|ASSpecify either IS or AS to declare the body of the function.
PlsqlPackageSpecSpecifies the package specification. Can include type definitions, cursor declarations, variable declarations, constant declarations, exception declarations and PL/SQL subprogram declarations.

Description

In a replicated environment, the CREATE PACKAGE statement is not replicated. For more information, see "Creating a new PL/SQL object in an existing active standby pair" and "Adding a PL/SQL object to an existing replication scheme" in the Oracle TimesTen In-Memory Database Replication Guide.

When you create or replace a package, the privileges granted on the package remain the same. If you drop and re-create the object, the object privileges that were granted on the original object are revoked.

See also

Oracle Database PL/SQL Language Reference and Oracle Database SQL Language Reference


CREATE PACKAGE BODY

The CREATE PACKAGE BODY statement creates the body of a standalone package. A package is an encapsulated collection of related procedures, functions, and other program objects stored together in your database. A package specification declares these objects. A package body defines these objects.

Required privilege

CREATE PROCEDURE (if owner) or CREATE ANY PROCEDURE (if not owner).

SQL syntax

CREATE [OR REPLACE] PACKAGE BODY [Owner.]PackageBody 
      {IS|AS} plsql_package_body

Parameters

ParameterDescription
OR REPLACESpecify OR REPLACE to re-create the package body if it already exists. Use this clause to change the body of an existing package without dropping and recreating it. When you change a package body, TimesTen recompiles it.
PackageBodyName of the package body.
IS|ASSpecify either IS or AS to declare the body of the function.
plsql_package_bodySpecifies the package body which consists of PL/SQL subprograms.

Description

In a replicated environment, the CREATE PACKAGE BODY statement is not replicated. For more information, see "Creating a new PL/SQL object in an existing active standby pair" and "Adding a PL/SQL object to an existing replication scheme" in the Oracle TimesTen In-Memory Database Replication Guide.

When you create or replace a package body, the privileges granted on the package body remain the same. If you drop and re-create the object, the object privileges that were granted on the original object are revoked.

See also


Oracle Database PL/SQL Language Reference and Oracle Database SQL Language Reference

CREATE PROCEDURE

The CREATE PROCEDURE statement creates a standalone stored procedure.

Required privilege

CREATE PROCEDURE (if owner) or CREATE ANY PROCEDURE (if not owner).

SQL syntax

CREATE [OR REPLACE] PROCEDURE [Owner.]ProcedureName 
     [(arguments [IN|OUT|IN OUT][NOCOPY] DataType [DEFAULT expr][,...])]
     [InvokerRightsClause] [DETERMINISTIC]
     {IS|AS} plsql_procedure_body

The syntax for the InvokerRightsClause:

AUTHID {CURRENT_USER|DEFINER}

You can specify InvokerRightsClause or DETERMINISTIC in any order.

Parameters

ParameterDescription
OR REPLACESpecify OR REPLACE to re-create the procedure if it already exists. Use this clause to change the definition of an existing procedure without dropping and recreating it. When you re-create a procedure, TimesTen recompiles it.
ProcedureNameName of procedure.
argumentsName of argument/parameter. You can specify 0 or more parameters for the procedure. If you specify a parameter, you must specify a data type for the parameter. The data type must be a PL/SQL data type.

For more information on PL/SQL data types, see Chapter 3, "PL/SQL Data Types" in the Oracle Database PL/SQL Language Reference.

[IN| OUT |IN OUT]Parameter modes.

IN is a read-only parameter. You can pass the parameter's value into the procedure but the procedure cannot pass the parameter's value out of the procedure and back to the calling PL/SQL block.The value of the parameter cannot be changed.

OUT is a write-only parameter. Use an OUT parameter to pass a value back from the procedure to the calling PL/SQL block. You can assign a value to the parameter.

IN OUT is a read/write parameter. You can pass values into the procedure and return a value back to the calling program (either the original, unchanged value or a new value set within the procedure.

IN is the default.

NOCOPYSpecify NOCOPY to instruct TimesTen to pass the parameter as fast as possible. Can enhance performance when passing a large value such as a record, an index-by-table, or a varray to an OUT or IN OUT parameter. IN parameters are always passed NOCOPY.

For more information on NOCOPY, see Oracle Database SQL Language Reference

DEFAULT exprUse this clause to specify a DEFAULT value for the parameter. You can specify := in place of the keyword DEFAULT.
InvokerRightsClauseLets you specify whether the SQL statements in PL/SQL functions or procedures execute with definer's or invoker's rights. The AUTHID setting affects the name resolution and privilege checking of SQL statements that a PL/SQL procedure or function issues at runtime, as follows:
  • Specify DEFINER so that SQL name resolution and privilege checking operate as though the owner of the procedure or function (the definer, in whose schema it resides) is running it. DEFINER is the default.

  • Specify CURRENT_USER so that SQL name resolution and privilege checking operate as though the current user (the invoker) is running it.

For more information, see the "Definer's rights and invoker's rights" section in the Oracle TimesTen In-Memory Database PL/SQL Developer's Guide or the Oracle Database PL/SQL Language Reference.

DETERMINISTICSpecify DETERMINISTIC to indicate that the procedure should return the same result value whenever it is called with the same values for its parameters.

For more information on the DETERMNISTIC clause, see Oracle Database SQL Language Reference.

IS|ASSpecify either IS or AS to declare the body of the procedure.
plsql_procedure_bodySpecifies the procedure body.

Restrictions

TimesTen does not support:

  • call_spec clause

  • AS EXTERNAL clause

In a replicated environment, the CREATE PROCEDURE statement is not replicated. For more information, see "Creating a new PL/SQL object in an existing active standby pair" and "Adding a PL/SQL object to an existing replication scheme" in the Oracle TimesTen In-Memory Database Replication Guide.

Description

  • The namespace for PL/SQL procedures is distinct from the TimesTen built-in procedures. You can create a PL/SQL procedure with the same name as a TimesTen built-in procedure.

  • When you create or replace a procedure, the privileges granted on the procedure remain the same. If you drop and re-create the object, the object privileges that were granted on the original object are revoked.

Examples

Create a procedure query_emp to retrieve information about an employee. Pass the employee_id 171 to the procedure and retrieve the last_name and salary into two OUT parameters.

Command> CREATE OR REPLACE PROCEDURE query_emp
       >           (p_id IN employees.employee_id%TYPE,
       >            p_name  OUT employees.last_name%TYPE,
       >            p_salary OUT employees.salary%TYPE) IS
       >         BEGIN
       >           SELECT last_name, salary INTO p_name, p_salary
       >           FROM employees
       >           WHERE employee_id = p_id;
       >         END query_emp;
       >         /
 
Procedure created.

See also


Oracle Database PL/SQL Language Reference and Oracle Database SQL Language Reference

CREATE REPLICATION

TimesTen SQL configuration for replication provides a programmable way to configure replication. The configuration can be embedded in C, C++ or Java code. Replication can be configured locally or from remote systems using client/server.

In addition, you need to use the ttRepAdmin utility to maintain operations not covered by the supported SQL statements. Use ttRepAdmin to change replication state, duplicate databases, list the replication configuration and view replication status.

The CREATE REPLICATION statement:

  • Defines a replication scheme at a participating database.

  • Installs the specified configuration in the executing database's replication system tables.

  • Typically consists of one or more replication element specifications and zero or more STORE specifications.

Required privilege

ADMIN

Definitions

A replication element is an entity that TimesTen synchronizes between databases. A replication element can be a whole table or a database. A database can include most types of tables and cache groups. It can include only specified tables and cache groups, or include all tables except specified tables and cache groups. It cannot include temporary tables or views, whether materialized or nonmaterialized.

A replication scheme is a set of replication elements, as well as the databases that maintain copies of these elements.

When replicating cache groups:

  • When replicating cache groups between databases, both cache groups must be identical, with the exception of the settings for AUTOREFRESH and PROPAGATE.

  • When replicating a cache group with AUTOREFRESH, the cache group on the subscriber must set the autorefresh STATE to OFF. In a bidirectional replication scheme, one of the cache groups must set the autorefresh STATE to OFF.

  • If a master cache group specifies PROPAGATE, the subscriber cache group must set the autorefresh STATE to OFF.

For more detailed information on SQL configuration for replication, see Oracle TimesTen In-Memory Database Replication Guide.

SQL syntax

CREATE REPLICATION [Owner.]ReplicationSchemeName
{ ELEMENT ElementName
  { DATASTORE | { TABLE [Owner.]TableName [CheckConflicts]} | 
       SEQUENCE [Owner.]SequenceName}
     { MASTER | PROPAGATOR } FullStoreName
     [TRANSMIT { NONDURABLE | DURABLE }]
     { SUBSCRIBER FullStoreName [,...]
        [ReturnServiceAttribute] } [,...] }
     [...]
     [{INCLUDE | EXCLUDE}
          {TABLE [[Owner.]TableName[,...]] |
           CACHE GROUP [[Owner.]CacheGroupName[,...]] | 
           SEQUENCE [[Owner.]SequenceName[,...]} [,...]] 
[ STORE FullStoreName [StoreAttribute [... ]]] [...]
[ NetworkOperation[...]]

Syntax for CheckConflicts is described in "CHECK CONFLICTS".

Syntax for ReturnServiceAttribute:

{ RETURN RECEIPT [BY REQUEST] |
  RETURN TWOSAFE [BY REQUEST] |
  NO RETURN }

Syntax for StoreAttribute:

  [ DISABLE RETURN {SUBSCRIBER | ALL} NumFailures ]
  [ RETURN SERVICES {ON | OFF} WHEN [REPLICATION] STOPPED ]
  [ DURABLE COMMIT {ON | OFF}]
  [ RESUME RETURN MilliSeconds ]
  [ LOCAL COMMIT ACTION {NO ACTION | COMMIT} ]
  [ RETURN WAIT TIME Seconds ]
  [ COMPRESS TRAFFIC {ON | OFF}
  [ PORT PortNumber ]
  [ TIMEOUT Seconds ]
  [ FAILTHRESHOLD Value ]
  [ CONFLICT REPORTING SUSPEND AT Value ]
  [ CONFLICT REPORTING RESUME AT Value ]
  [ TABLE DEFINITION CHECKING {RELAXED|EXACT}]

Syntax for NetworkOperation:

ROUTE MASTER FullStoreName SUBSCRIBER FullStoreName
  { { MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost }
      PRIORITY Priority } [...]

Parameters

ParameterDescription
[Owner.]ReplicationSchemeNameName assigned to the new replication scheme. Replication schemes should have names that are unique from all other database objects.
CheckConflictsCheck for replication conflicts when simultaneously writing to bidirectionally replicated databases. See "CHECK CONFLICTS".
COMPRESS TRAFFIC {ON | OFF}Compress replicated traffic to reduce the amount of network bandwidth. ON specifies that all replicated traffic for the database defined by STORE be compressed. OFF (the default) specifies no compression. See "Compressing replicated traffic" in Oracle TimesTen In-Memory Database Replication Guide for details.
CONFLICT REPORTING SUSPEND AT ValueSuspends conflict resolution reporting.

Value is a non-negative integer. The default is 0 and means never suspend. Conflict reporting is suspended when the rate of conflict exceeds Value. If you set Value to 0, conflict reporting suspension is turned off.

Use this clause for table-level replication.

CONFLICT REPORTING RESUME AT ValueResumes conflict resolution reporting.

Value is a non-negative integer. Conflict reporting is resumed when the rate of conflict falls below Value. The default is 1.

Use this clause for table level replication.

DATASTOREDefine entire database as element. This type of element can only be defined for a master database that is not configured with an element of type TABLE in the same or a different replication scheme. See "Defining replication elements" in Oracle TimesTen In-Memory Database Replication Guide.
{INCLUDE|EXCLUDE}

{[TABLE[Owner.]TableName [,...]]|

CACHE GROUP

[[Owner.]CacheGroupName [,...]]|

SEQUENCE

[[Owner.]SequenceName[,...]]} [,...]

INCLUDE includes in the DATASTORE element only the tables, sequences or cache groups listed. Use one INCLUDE clause for each object type (table, sequence or cache group).

EXCLUDE includes in the DATASTORE element all tables, sequences or cache groups except for those listed. Use one EXCLUDE clause for each object type (table, sequence or cache group).

DISABLE RETURN {SUBSCRIBER|ALL} NumFailuresSet the return service failure policy so that return service blocking is disabled after the number of timeouts specified by NumFailures. Selecting SUBSCRIBER applies this policy only to the subscriber that fails to acknowledge replicated updates within the set timeout period. ALL applies this policy to all subscribers should any of the subscribers fail to respond. This failure policy can be specified for either the RETURN RECEIPT or RETURN TWOSAFE service.

If DISABLE RETURN is specified but RESUME RETURN is not specified, the return services remain off until the replication agent for the database has been restarted.

See "Managing return service timeout errors and replication state changes" in Oracle TimesTen In-Memory Database Replication Guide for details.

DURABLE COMMIT {ON|OFF}Overrides the DurableCommits general connection attribute setting. DURABLE COMMIT ON enables durable commits regardless of whether the replication agent is running or stopped.
ELEMENT ElementNameThe entity that TimesTen synchronizes between databases. TimesTen supports the entire database (DATASTORE) and whole tables (TABLE) as replication elements.

ElementName is the name given to the replication element. The ElementName for a TABLE element can be up to 30 characters in length. The ElementName for a DATASTORE element must be unique with respect to other DATASTORE element names within the first 20 chars. Each ElementName must be unique within a replication scheme. Also, you cannot define two element descriptions for the same element.

See "Defining replication elements" in Oracle TimesTen In-Memory Database Replication Guide for details.

FAILTHRESHOLD ValueThe number of log files that can accumulate for a subscriber database. If this value is exceeded, the subscriber is set to the Failed state.The value 0 means "No Limit." This is the default.

See "Setting the log failure threshold" in Oracle TimesTen In-Memory Database Replication Guide.

FullStoreNameThe database, specified as one of the following:
  • SELF

  • The prefix of the database file name

For example, if the database path is directory/subdirectory/data.ds0, then data is the database name that should be used.

This is the database file name specified in the DataStore attribute of the DSN description with optional host ID in the form:

DataStoreName [ON Host]

Host can be either an IP address or a literal host name assigned to one or more IP addresses, as described in "Configuring host IP addresses" in Oracle TimesTen In-Memory Database Replication Guide. Host names containing special characters must be surrounded by double quotes. For example: "MyHost-500". Host names can be up to 30 characters long.

LOCAL COMMIT ACTION{NO ACTION|COMMIT}Specifies the default action to be taken for a return twosafe transaction in the event of a timeout.

Note: This attribute is only valid when the RETURN TWOSAFE or RETURN TWOSAFE BY REQUEST attribute is set in the SUBSCRIBER clause.

NO ACTION: On timeout, the commit function returns to the application, leaving the transaction in the same state it was in when it entered the commit call, with the exception that the application is not able to update any replicated tables. The application can reissue the commit or rollback the call. This is the default.

COMMIT: On timeout, the commit function attempts to perform a COMMIT to end the transaction locally. No more operations are possible on the same transaction.

This setting can be overridden for specific transactions by calling the localAction parameter in the ttRepSyncSet procedure.

MASTER FullStoreNameThe database on which applications update the specified element. The MASTER database sends updates to its SUBSCRIBER databases. The FullStoreName must be the database specified in the DataStore attribute of the DSN description.
NO RETURNSpecifies that no return service is to be used. This is the default.

For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

PORT PortNumberThe TCP/IP port number on which the replication agent for the database listens for connections. If not specified, the replication agent automatically allocates a port number.
PROPAGATOR FullStoreNameThe database that receives replicated updates and passes them on to other databases. The FullStoreName must be the database specified in the DataStore attribute of the DSN description.
RESUME RETURN MilliSecondsIf return service blocking has been disabled by DISABLE RETURN, this attribute sets the policy on when to re-enable return service blocking. Return service blocking is re-enabled as soon as the failed subscriber acknowledges the replicated update in a period of time that is less than the specified MilliSeconds.

If DISABLE RETURN is specified but RESUME RETURN is not specified, the return services remain off until the replication agent for the database has been restarted.

RETURN RECEIPT [BY REQUEST]Enables the return receipt service, so that applications that commit a transaction to a master database are blocked until the transaction is received by all subscribers.

RETURN RECEIPT applies the service to all transactions. If you specify RETURN REQUEST BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions. For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide

RETURN SERVICES {ON|OFF} WHEN [REPLICATION] STOPPEDSet the return service failure policy so that return service blocking is either unchanged or disabled when the replication agent is in the Stop or Pause state.

OFF is the default when using the return receipt service. ON is the default when using the return twosafe service

See "Managing return service timeout errors and replication state changes" in Oracle TimesTen In-Memory Database Replication Guide for details.

RETURN TWOSAFE [BY REQUEST]Enables the return twosafe service, so that applications that commit a transaction to a master database are blocked until the transaction is committed on all subscribers.

Note: This service can only be used in a bidirectional replication scheme where the elements are defined as DATASTORE.

Specifying RETURN TWOSAFE applies the service to all transactions. If you specify RETURN TWOSAFE BY REQUEST, you can use the ttRepSyncSet procedure to enable the return receipt service for selected transactions. For details on the use of the return services, see "Using a return service" in Oracle TimesTen In-Memory Database Replication Guide.

RETURN WAIT TIME SecondsSpecifies the number of seconds to wait for return service acknowledgement. The default value is 10 seconds. A value of '0' means that there is no timeout. Your application can override this timeout setting by calling the returnWait parameter in the ttRepSyncSet procedure.
SEQUENCE [Owner.]SequenceNameDefine the sequence specified by [Owner.]SequenceName as element. See "Defining replication elements" in Oracle TimesTen In-Memory Database Replication Guide for details.
STORE FullStoreNameDefines the attributes for a given database. Attributes include PORT, TIMEOUT and FAILTHRESHOLD. The FullStoreName must be the database specified in the DataStore attribute of the DSN description.
SUBSCRIBER FullStoreNameA database that receives updates from the MASTER databases. The FullStoreName must be the database specified in the DataStore attribute of the DSN description.
TABLE [Owner.]TableNameDefine the table specified by [Owner.]TableName as element. See "Defining replication elements" in Oracle TimesTen In-Memory Database Replication Guide for details.
TIMEOUT SecondsThe maximum number of seconds the replication agent waits for a response from the database. Default: 120 seconds.
TRANSMIT {DURABLE | NONDURABLE}Specifies whether to flush the master log to disk before sending a batch of committed transactions to the subscribers.

TRANSMIT NONDURABLE specifies that records in the master log are not to be flushed to disk before they are sent to subscribers. This setting can only be used if the specified element is a DATASTORE. This is the default for RETURN TWOSAFE transactions.

TRANSMIT DURABLE specifies that records are to be flushed to disk before they are sent to subscribers. This is the default for asynchronous and RETURN RECEIPT transactions.

Note: TRANSMIT DURABLE has no effect on RETURN TWOSAFE transactions.

Note: TRANSMIT DURABLE cannot be set for active standby pairs.

See "Setting transmit durability on database elements" and "Replicating the entire master database with TRANSMIT NONDURABLE" in Oracle TimesTen In-Memory Database Replication Guide for more information.

TABLE DEFINITION CHECKING {EXACT|RELAXED}Specifies type of table definition checking that occurs on the subscriber:
  • EXACT - The tables must be identical on master and subscriber.

  • RELAXED - The tables must have the same key definition, number of columns and column data types.

The default is EXACT.

ROUTE MASTER FullStoreName SUBSCRIBER FullStoreNameDenotes the NetworkOperation clause. If specified, enables you to control the network interface that a master store uses for every outbound connection to each of its subscriber stores.

Can be specified more than once.

For FullStoreName, ON "host" must be specified.

MASTERIP MasterHost | SUBSCRIBERIP SubscriberHostMasterHost and SubscriberHost are the IP addresses for the network interface on the master and subscriber stores. Specify in dot notation or canonical format or in colon notation for IPV6.

Clause can be specified more than once.

PRIORITY PriorityVariable expressed as an integer from 1 to 99. Denotes the priority of the IP address. Lower integral values have higher priority. An error is returned if multiple addresses with the same priority are specified. Controls the order in which multiple IP addresses are used to establish peer connections.

Required syntax of NetworkOperation clause. Follows MASTERIP MasterHost | SUBSCRIBERIP SubscriberHost clause.



CHECK CONFLICTS

Syntax

The syntax for CHECK CONFLICTS is:

{NO CHECK |
CHECK CONFLICTS BY ROW TIMESTAMP
      COLUMN ColumnName
      [ UPDATE BY { SYSTEM | USER } ]
      [ ON EXCEPTION { ROLLBACK [ WORK ] | NO ACTION } ]
      [ {REPORT TO 'FileName'
             [ FORMAT { XML | STANDARD } ] | NO REPORT
      } ]
}

Note:

A CHECK CONFLICT clause can only be used for elements of type TABLE.

Parameters

The CHECK CONFLICTS clause of the CREATE REPLICATION or ALTER REPLICATION statement has the following parameters:

ParameterDescription
CHECK CONFLICTS BY ROW TIMESTAMPIndicates that all update and uniqueness conflicts are to be detected. Conflicts are resolved in the manner specified by the ON EXCEPTION parameter.

It also detects delete conflicts with UPDATE operations.

COLUMN ColumnNameIndicates the column in the replicated table to be used for timestamp comparison. The table is specified in the ELEMENT description by TableName.

ColumnName is a nullable column of type BINARY(8) used to store a timestamp that indicates when the row was last updated. TimesTen rejects attempts to update a row with a lower timestamp value than the stored value. The specified ColumnName must exist in the replicated table on both the master and subscriber databases.

NO CHECKSpecify to suppress conflict resolution for a given element.
UPDATE BY {SYSTEM | USER}Specifies whether the timestamp values are maintained by TimesTen (SYSTEM) or the application (USER). The replicated table in the master and subscriber databases must use the same UPDATE BY specification. See "Enabling system timestamp column maintenance" and "Enabling user timestamp column maintenance" in Oracle TimesTen In-Memory Database Replication Guide for more information. The default is UPDATE BY SYSTEM.
ON EXCEPTION {ROLLBACK[WORK |NO ACTION}Specifies how to resolve a detected conflict. ROW TIMESTAMP conflict detection has the resolution options:
  • ROLLBACK [WORK]: Abort the transaction that contains the conflicting action.

  • NO ACTION: Complete the transaction without performing the conflicting action (UPDATE, INSERT or DELETE).

Default is ON EXCEPTION ROLLBACK [WORK].

REPORT TO 'FileName'Specifies the file to log updates that fail the timestamp comparison. FileName is a SQL character string that cannot exceed 1,000 characters. (SQL character string literals are single-quoted strings that may contain any sequence of characters, including spaces.) The same file can be used to log failed updates for multiple tables.
[FORMAT {XML|STANDARD}]Optionally specifies the conflict report format for an element. The default format is STANDARD.
NO REPORTSpecify to suppress logging of failed timestamp comparisons.

Description

  • The names of all databases on the same host must be unique for each replication scheme for each TimesTen instance.

  • Replication elements can only be updated (by normal application transactions) through the MASTER database. PROPAGATOR and SUBSCRIBER databases are read-only.

  • If you define a replication scheme that permits multiple databases to update the same table, see "Resolving Replication Conflicts" in Oracle TimesTen In-Memory Database Replication Guide for recommendations on how to avoid conflicts when updating rows.

  • SELF is intended for replication schemes where all participating databases are local. Do not use SELF for a distributed replication scheme in a production environment, where spelling out the hostname for each database in a script enables it to be used at each participating database.

  • Each attribute for a given STORE may be specified only once, or not at all.

  • Specifying the PORT of a database for one replication scheme specifies it for all replication schemes. All other connection attributes are specific to the replication scheme specified in the command.

  • For replication schemes, DataStoreName is always the prefix of the TimesTen database checkpoint file names. These are the files with the.ds0 and.ds1 suffixes that are saved on disk by checkpoint operations.

  • If a row with a default NOT INLINE VARCHAR value is replicated, the receiver creates a copy of this value for each row instead of pointing to the default value if and only if the default value of the receiving node is different from the sending node.

  • To use timestamp comparison on replicated tables, you must specify a nullable column of type BINARY(8) to hold the timestamp value. Define the timestamp column when you create the table. You cannot add the timestamp column with the ALTER TABLE statement. In addition, the timestamp column cannot be part of a primary key or index.

  • If you specify the XML report format, two XML documents are generated:

    • FileName.xml: This file contains the DTD for the report and the root node for the report. It includes the document definition and the include directive.

    • FileName.include: This file is included in FileName.xml and contains all the actual conflicts.

    • The FileName.include file can be truncated. Do not truncate the FileName.xml file.

    • For a complete description of the XML format, including examples of each conflict, see "Reporting conflicts to an XML file" in Oracle TimesTen In-Memory Database Replication Guide.

  • If you specify a report format for an element and then drop the element, the corresponding report files are not deleted.

  • Use the CONFLICT REPORTING SUSPEND AT clause to specify a high water mark threshold at which the reporting of conflict resolution is suspended. When the number of conflicts per second exceeds the specified high water mark threshold, conflict resolution reporting (if configured and reported by the report file) and SNMP are suspended and an SNMP trap is emitted to indicate that it has been suspended.

  • Use the CONFLICT REPORTING RESUME AT clause to specify a low water mark threshold where the reporting of conflict resolution is resumed. When the rate of conflict falls below the low water mark threshold, conflict resolution reporting is resumed. A SNMP trap is emitted to indicate the resumption of conflict resolution. This trap provides the number of unreported conflicts during the time when conflict resolution was suspended.

  • The state of whether conflict reporting is suspended or not by a replication agent does not persist across the local replication agent and the peer agent stop and restart.

  • Do not use the CREATE REPLICATION statement to replicate dynamic read-only cache groups asynchronously. Use the CREATE ACTIVE STANDBY PAIR statement.

Examples

Replicate the contents of repl.tab from masterds to two subscribers, subscriber1ds and subscriber2ds.

CREATE REPLICATION repl.twosubscribers
       ELEMENT e TABLE repl.tab
         MASTER masterds ON "server1"
         SUBSCRIBER subscriber1ds ON "server2",
                    subscriber2ds ON "server3";

Replicate the entire masterds database to the subscriber, subscriber1ds. The FAILTHRESHOLD specifies that a maximum of 10 log files can accumulate on masterds before it decides that subscriber1ds has failed.

CREATE REPLICATION repl.wholestore
  ELEMENT e DATASTORE
     MASTER masterds ON "server1"
     SUBSCRIBER subscriber1ds ON "server2"
  STORE masterds FAILTHRESHOLD 10;

Bidirectionally replicate the entire westds and eastds databases and enable the RETURN TWOSAFE service.

CREATE REPLICATION repl.biwholestore
  ELEMENT e1 DATASTORE
     MASTER westds ON "westcoast"
     SUBSCRIBER eastds ON "eastcoast"
        RETURN TWOSAFE
  ELEMENT e2 DATASTORE
     MASTER eastds ON "eastcoast"
     SUBSCRIBER westds ON "westcoast"
        RETURN TWOSAFE;

Enable the return receipt service for select transaction updates to the subscriber1ds subscriber.

CREATE REPLICATION repl.twosubscribers
  ELEMENT e TABLE repl.tab
     MASTER masterds ON "server1"
     SUBSCRIBER subscriber1ds ON "server2"
        RETURN RECEIPT BY REQUEST
     SUBSCRIBER subscriber2ds ON "server3";

Replicate the contents of the customerswest table from the west database to the ROUNDUP database and the customerseast table from the east database. Enable the return receipt service for all transactions.

CREATE REPLICATION r
       ELEMENT west TABLE customerswest
         MASTER west ON "serverwest"
         SUBSCRIBER roundup ON "serverroundup"
            RETURN RECEIPT
       ELEMENT east TABLE customerseast
         MASTER east ON "servereast"
         SUBSCRIBER roundup ON "serverroundup"
            RETURN RECEIPT;

Replicate the contents of the repl.tab table from the centralds database to the propds database, which propagates the changes to the backup1ds and backup2ds databases.

CREATE REPLICATION repl.propagator
       ELEMENT a TABLE repl.tab
         MASTER centralds ON "finance"
         SUBSCRIBER proprds ON "nethandler"
       ELEMENT b TABLE repl.tab
         PROPAGATOR proprds ON "nethandler"
         SUBSCRIBER backup1ds ON "backupsystem1"
                    bakcup2ds ON "backupsystem2";

Bidirectionally replicate the contents of the repl.accounts table between the eastds and westds databases. Each database is both a master and a subscriber for the repl.accounts table.

Because the repl.accounts table can be updated on either the eastds or westds database, it includes a timestamp column (tstamp). The CHECK CONFLICTS clause establishes automatic timestamp comparison to detect any update conflicts between the two databases. In the event of a comparison failure, the entire transaction that includes an update with the older timestamp is rolled back (discarded).

CREATE REPLICATION repl.r1
ELEMENT elem_accounts_1 TABLE repl.accounts
   CHECK CONFLICTS BY ROW TIMESTAMP
      COLUMN tstamp
      UPDATE BY SYSTEM
      ON EXCEPTION ROLLBACK
   MASTER westds ON "westcoast"
   SUBSCRIBER eastds ON "eastcoast"
ELEMENT elem_accounts_2 TABLE repl.accounts
   CHECK CONFLICTS BY ROW TIMESTAMP
      COLUMN tstamp
      UPDATE BY SYSTEM
      ON EXCEPTION ROLLBACK
   MASTER eastds ON "eastcoast"
   SUBSCRIBER westds ON "westcoast";

Replicate the contents of the repl.accounts table from the activeds database to the backupds database, using the return twosafe service, and using TCP/IP port 40000 on activeds and TCP/IP port 40001 on backupds. The transactions on activeds need to be committed whenever possible, so configure replication so that the transaction is committed even after a replication timeout using LOCAL COMMIT ACTION, and so that the return twosafe service is disabled when replication is stopped. To avoid significant delays in the application if the connection to the backupds database is interrupted, configure the return service to be disabled after five transactions have timed out, but also configure the return service to be re-enabled when the backupds database's replication agent responds in under 100 milliseconds. Finally, the bandwidth between databases is limited, so configure replication to compress the data when it is replicated from the activeds database.

CREATE REPLICATION repl.r
ELEMENT elem_accounts_1 TABLE repl.accounts
   MASTER activeds ON "active"
   SUBSCRIBER backupds ON "backup"
      RETURN TWOSAFE
ELEMENT elem_accounts_2 TABLE repl.accounts
   MASTER activeds ON "active"
   SUBSCRIBER backupds ON "backup"
      RETURN TWOSAFE
STORE activeds ON "active"
   PORT 40000
   LOCAL COMMIT ACTION COMMIT
   RETURN SERVICES OFF WHEN REPLICATION STOPPED
   DISABLE RETURN SUBSCRIBER 5
   RESUME RETURN 100
   COMPRESS TRAFFIC ON
STORE backupds ON "backup"
   PORT 40001;

Illustrate conflict reporting suspend and conflict reporting resume clauses for table level replication. Use these clauses for table level replication not database replication. Issue repschemes command to show that replication scheme is created.

Command> CREATE TABLE repl.accounts (tstamp BINARY (8) NOT NULL 
PRIMARY KEY, tstamp1 BINARY (8));
Command> CREATE REPLICATION repl.r2
> ELEMENT elem_accounts_1 TABLE repl.accounts
> CHECK CONFLICTS BY ROW TIMESTAMP
> COLUMN tstamp1
> UPDATE BY SYSTEM
> ON EXCEPTION ROLLBACK WORK
> MASTER westds ON "west1"
> SUBSCRIBER eastds ON "east1"
> ELEMENT elem_accounts_2 TABLE repl.accounts
> CHECK CONFLICTS BY ROW TIMESTAMP 
> COLUMN tstamp1
> UPDATE BY SYSTEM 
> ON EXCEPTION ROLLBACK WORK 
> MASTER eastds ON "east1"
> SUBSCRIBER westds ON "west1"
> STORE westds
> CONFLICT REPORTING SUSPEND AT 20
> CONFLICT REPORTING RESUME AT 10;
Command> REPSCHEMES;

Replication Scheme REPL.R2:

  Element: ELEM_ACCOUNTS_1
  Type: Table REPL.ACCOUNTS
  Conflict Check Column: TSTAMP1
  Conflict Exception Action: Rollback Work
  Conflict Timestamp Update: System
  Conflict Report File: (none)
  Master Store: WESTDS on WEST1 Transmit Durable
  Subscriber Store: EASTDS on EAST1

  Element: ELEM_ACCOUNTS_2
  Type: Table REPL.ACCOUNTS
  Conflict Check Column: TSTAMP1
  Conflict Exception Action: Rollback Work
  Conflict Timestamp Update: System
  Conflict Report File: (none)
  Master Store: EASTDS on EAST1 Transmit Durable
  Subscriber Store: WESTDS on WEST1

  Store: EASTDS on EAST1
    Port: (auto)
    Log Fail Threshold: (none)
    Retry Timeout: 120 seconds
    Compress Traffic: Disabled

  Store: WESTDS on WEST1
    Port: (auto)
    Log Fail Threshold: (none)
    Retry Timeout: 120 seconds
    Compress Traffic: Disabled
    Conflict Reporting Suspend: 20
    Conflict Reporting Resume: 10

1 replication scheme found.

Example of NetworkOperation clause with 2 MASTERIP and SUBSCRIBERIP clauses:

CREATE REPLICATION r ELEMENT e DATASTORE
MASTER rep1 SUBSCRIBER rep2 RETURN RECEIPT
MASTERIP "1.1.1.1" PRIORITY 1 SUBSCRIBERIP "2.2.2.2"
    PRIORITY 1
MASTERIP "3.3.3.3" PRIORITY 2 SUBSCRIBERIP "4.4.4.4"
    PRIORITY 2;

Example of NetworkOperation clause. Use the default sending interface but a specific receiving network:

CREATE REPLICATION r
ELEMENT e DATASTORE
MASTER rep1 SUBSCRIBER rep2
ROUTE MASTER rep1 ON "machine1" SUBSCRIBER rep2 ON "machine2"
SUBSCRIBERIP "rep2nic2" PRIORITY 1;

Example of using the NetworkOperation clause with multiple subscribers:

CREATE REPLICATION r ELEMENT e DATASTORE
MASTER rep1 SUBSCRIBER rep2,rep3
ROUTE MASTER rep1 ON "machine1" SUBSCRIBER rep2 ON "machine2"
MASTERIP "1.1.1.1" PRIORITY 1 SUBSCRIBERIP "2.2.2.2"
    PRIORITY 1
ROUTE MASTER Rep1 ON "machine1" SUBSCRIBER Rep3 ON "machine2"
MASTERIP "3.3.3.3" PRIORITY 2 SUBSCRIBERIP "4.4.4.4";

See also


ALTER ACTIVE STANDBY PAIR
ALTER REPLICATION
CREATE ACTIVE STANDBY PAIR
DROP ACTIVE STANDBY PAIR
DROP REPLICATION

CREATE SEQUENCE

The CREATE SEQUENCE statement creates a new sequence number generator that can subsequently be used by multiple users to generate unique integers. Use the CREATE SEQUENCE statement to define the initial value of the sequence, define the increment value, the maximum or minimum value and determine if the sequence continues to generate numbers after the minimum or maximum is reached.

Required privilege

CREATE SEQUENCE (if owner) or CREATE ANY SEQUENCE (if not owner).

SQL syntax

CREATE SEQUENCE [Owner.]SequenceName
       [INCREMENT BY IncrementValue]
       [MINVALUE MinimumValue]
       [MAXVALUE MaximumValue]
       [CYCLE]
       [CACHE CacheValue]
       [START WITH StartValue]

Parameters

ParameterDescription
SEQUENCE [Owner.]SequenceNameName of the sequence number generator.
INCREMENT BY IncrementValueThe incremental value between consecutive numbers. This value can be either a positive or negative integer. It cannot be 0. If the value is positive, it is an ascending sequence. If the value is negative, it is descending. The default value is 1. In a descending sequence, the range starts from MAXVALUE to MINVALUE, and vice versa for ascending sequence.
MINVALUE MinimumValueSpecifies the minimum value for the sequence. The default minimum value is 1.
MAXVALUE MaximumValueThe largest possible value for an ascending sequence, or the starting value for a descending sequence. The default maximum value is (263) -1, which is the maximum of BIGINT.
CYCLEIndicates that the sequence number generator continues to generate numbers after it reaches the maximum or minimum value. By default, sequences do not cycle. Once the number reaches the maximum value in the ascending sequence, the sequence wraps around and generates numbers from its minimum value. For a descending sequence, when the minimum value is reached, the sequence number wraps around, beginning from the maximum value. If CYCLE is not specified, the sequence number generator stops generating numbers when the maximum/minimum is reached and TimesTen returns an error.
CACHE CacheValueCACHE indicates the range of numbers that are cached each time. When a restart occurs, unused cached numbers are lost. If you specify a CacheValue of 1, then each use of the sequence results in an update to the database. Larger cache values result in fewer changes to the database and less overhead. The default is 20.
START WITH StartValueSpecifies the first sequence number to be generated. Use this clause to start an ascending sequence at a value that is greater than the minimum value or to start a descending sequence at a value less than the maximum. The StartValue must be greater or equal MinimumValue and StartValue must be less than or equal to MaximumValue.

Description

  • All parameters in the CREATE SEQUENCE statement must be integer values.

  • If you do not specify a value in the parameters, TimesTen defaults to an ascending sequence that starts with 1, increments by 1, has the default maximum value and does not cycle.

  • There is no ALTER SEQUENCE statement in TimesTen. To alter a sequence, use the DROP SEQUENCE statement and then create a new sequence with the same name. For example, to change the MINVALUE, drop the sequence and re-create it with the same name and with the desired MINVALUE.

  • Do not create a sequence with the same name as a view or materialized view.

  • Sequences with the CYCLE attribute cannot be replicated.

Incrementing SEQUENCE values with CURRVAL and NEXTVAL

To refer to the SEQUENCE values in a SQL statement, use CURRVAL and NEXTVAL.

  • CURRVAL returns the value of the last call to NEXTVAL if there is one in the current session, otherwise it returns an error.

  • NEXTVAL increments the current sequence value by the specified increment and returns the value for each row accessed.

The current value of a sequence is a connection-specific value. If there are two concurrent connections to the same database, each connection has its own CURRVAL of the same sequence set to its last NEXTVAL reference. When the maximum value is reached, SEQUENCE either wraps or issues an error statement, depending on the value of the CYCLE option of the CREATE SEQUENCE. In the case of recovery, sequences are not rolled back. It is possible that the range of values of a sequence can have gaps; however, each sequence value is still unique.

If you execute a single SQL statement with multiple NEXTVAL references, TimesTen only increments the sequence once, returning the same value for all occurrences of NEXTVAL. If a SQL statement contains both NEXTVAL and CURRVAL, NEXTVAL is executed first. CURRVAL and NEXTVAL have the same value in that SQL statement.


Note:

NEXTVAL cannot be used in a query on a standby node of an active standby pair.

NEXTVAL and CURRVAL can be used in:

  • The SelectList of a SELECT statement, but not the SelectList of a subquery.

  • The SelectList of an INSERT...SELECT statement.

  • The SET clause of an UPDATE statement.

Examples

Create a sequence.

CREATE SEQUENCE mysequence INCREMENT BY 1 MINVALUE 2 
       MAXVALUE 1000;

This example assumes that tab1 has 1 row in the table and that CYCLE is used:

CREATE SEQUENCE s1 MINVALUE 2 MAXVALUE 4 CYCLE;
SELECT s1.NEXTVAL FROM tab1;
/* Returns the value of 2; */
SELECT s1.NEXTVAL FROM tab1;
/* Returns the value of 3; */
SELECT s1.NEXTVAL FROM tab1;
/* Returns the value of 4; */

After the maximum value is reached, the cycle starts from the minimum value for an ascending sequence.

SELECT s1.NEXTVAL FROM tab1;
/* Returns the value of 2; */

To create a sequence and generate a sequence number:

CREATE SEQUENCE seq INCREMENT BY 1;
INSERT INTO student VALUES (seq.NEXTVAL, 'Sally');

To use a sequence in an UPDATE SET clause:

UPDATE student SET studentno = seq.NEXTVAL WHERE name = 'Sally';

To use a sequence in a query:

SELECT seq.CURRVAL FROM student;

See also

DROP SEQUENCE


CREATE SYNONYM

The CREATE SYNONYM statement creates a public or private synonym for a database object. A synonym is an alias for a database object. The object can be a table, view, synonym, sequence, PL/SQL stored procedure, PL/SQL function, PL/SQL package, materialized view or cache group.

A private synonym is owned by a specific user and exists in that user's schema. A private synonym is accessible to users other than the owner only if those users have appropriate privileges on the underlying object and specify the schema along with the synonym name.

A public synonym is accessible to all users as long as the user has appropriate privileges on the underlying object.

CREATE SYNONYM is a DDL statement.

Synonyms can be used in these SQL statements:

  • DML statements: SELECT, DELETE, INSERT, UPDATE, MERGE

  • Some DDL statements: GRANT, REVOKE, CREATE TABLE ... AS SELECT, CREATE VIEW ... AS SELECT, CREATE INDEX, DROP INDEX

  • Some cache group statements: LOAD CACHE GROUP, UNLOAD CACHE GROUP, REFRESH CACHE GROUP, FLUSH CACHE GROUP

Required privilege

CREATE SYNONYM (if owner) or CREATE ANY SYNONYM (if not owner) to create a private synonym.

CREATE PUBLIC SYNONYM to create a public synonym.

SQL syntax

CREATE [OR REPLACE] [PUBLIC] SYNONYM [owner1.]synonym FOR [owner2.]object

Parameters

ParameterDescription
[OR REPLACE]Specify OR REPLACE to re-create the synonym if it already exists. Use this clause to change the definition of an existing synonym without first dropping it.
[PUBLIC]Specify PUBLIC to create a public synonym. Public synonyms are accessible to all users, but each user must have appropriate privileges on the underlying object in order to use the synonym.

When resolving references to an object, TimesTen uses a public synonym only if the object is not prefaced by a schema name.

[owner1.]synonymSpecify the owner of the synonym. You cannot specify an owner for the synonym if you have specified PUBLIC. If you omit both PUBLIC and owner1, TimesTen creates the synonym in your own schema.

Specify the name for the synonym, which is limited to 30 bytes.

[owner2.]objectSpecify the owner in which the object resides. Specify the object name for which you are creating a synonym. If you do not qualify object with owner2, the object is in your own schema. The owner2 and object do not need to exist when the synonym is created.

Description

  • The schema object does not need to exist when its synonym is created.

  • Do not create a public synonym with the same name as a TimesTen built-in procedure.

  • In order to use the synonym, appropriate privileges must be granted to a user for the object aliased by the synonym before using the synonym.

  • A private synonym cannot have the same name as tables, views, sequences, PLSQL packages, functions, procedures, and cache groups that are in the same schema as the private synonym.

  • A public synonym may have the same name as a private synonym or an object name.

  • If the PassThrough attribute is set so that a query needs to executed in the Oracle database, the query is sent to the Oracle database without any changes. If the query uses a synonym for a table in a cache group, then a synonym with the same name must be defined for the corresponding Oracle table for the query to be successful.

  • When an object name is used in the DML and DDL statements in which a synonym can be used, the object name is resolved as follows:

    1. Search for a match within the current schema. If no match is found, then:

    2. Search for a match with a public synonym name. If no match is found, then:

    3. Search for a match in the SYS schema. If no match is found, then:

    4. The object does not exist.

    TimesTen creates a public synonym for some objects in the SYS schema. The name of the public synonym is the same as the object name. Thus steps 2 and 3 in the object name resolution can be switched without changing the results of the search.

  • In a replicated environment for an active standby pair, if DDL_REPLICATION_LEVEL=2 when you execute the CREATE SYNONYM on the active database, the synonym will be replicated to all databases in the replication scheme. See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

Examples

As user ttuser, create a synonym for the jobs table. Verify that you can retrieve the information using the synonym. Display the contents of the SYS.USER_SYNONYMS system view.

Command> CREATE SYNONYM synjobs FOR jobs;
Synonym created.

Command> SELECT FIRST 2 * FROM jobs;
< AC_ACCOUNT, Public Accountant, 4200, 9000 >
< AC_MGR, Accounting Manager, 8200, 16000 >
2 rows found.
Command> SELECT FIRST 2 * FROM synjobs;
< AC_ACCOUNT, Public Accountant, 4200, 9000 >
< AC_MGR, Accounting Manager, 8200, 16000 >
2 rows found.

Command> SELECT * FROM sys.user_synonyms;
< SYNJOBS, TTUSER, JOBS, <NULL> >
1 row found.

Create a public synonym for the employees table.

Command> CREATE PUBLIC SYNONYM pubemp FOR employees;
Synonym created.

Verify that pubemp is listed as a public synonym in the SYS.ALL_SYNONYMS system view.

Command> SELECT * FROM sys.all_synonyms;
< PUBLIC, TABLES, SYS, TABLES, <NULL> >
...
< TTUSER, SYNJOBS, TTUSER, JOBS, <NULL> >
< PUBLIC, PUBEMP, TTUSER, EMPLOYEES, <NULL> >
57 rows found.

Create a synonym for the tab table in the terry schema. Describe the synonym.

Command> CREATE SYNONYM syntab FOR terry.tab;
Synonym created.
Command> DESCRIBE syntab;
 
Synonym TTUSER.SYNTAB:
  For Table TERRY.TAB
  Columns:
    COL1                            VARCHAR2 (10) INLINE
    COL2                            VARCHAR2 (10) INLINE

1 Synonyms found.

Redefine the synjobs synonym to be an alias for the employees table by using the OR REPLACE clause. Describe synjobs.

Command> CREATE OR REPLACE synjobs FOR employees;
Synonym created.
 
Command> DESCRIBE synjobs;
 
Synonym TTUSER.SYNJOBS:
  For Table TTUSER.EMPLOYEES
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE NOT NULL
    EMAIL                           VARCHAR2 (25) INLINE UNIQUE NOT NULL
    PHONE_NUMBER                    VARCHAR2 (20) INLINE
    HIRE_DATE                       DATE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    SALARY                          NUMBER (8,2)
    COMMISSION_PCT                  NUMBER (2,2)
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)
 
1 Synonyms found.

See also

DROP SYNONYM


CREATE TABLE

The CREATE TABLE statement defines a table.

Required privilege

CREATE TABLE (if owner) or CREATE ANY TABLE (if not owner).

The owner of the created table must have the REFERENCES privilege on tables referenced by the REFERENCE clause.

ADMIN privilege if replicating a new table across an active standby pair when DDL_REPLICATION_LEVEL=2 and DDL_REPLICATION_ACTION=INCLUDE. These attributes cause the CREATE TABLE to implicitly execute an ALTER ACTIVE STANDBY PAIR... INCLUDE TABLE statement. See "ALTER SESSION" for more details.

SQL syntax

The syntax for a persistent table is:

CREATE TABLE [Owner.]TableName
(
    {{ColumnDefinition} [,...]
     [PRIMARY KEY (ColumnName [,...]) |
     [[CONSTRAINT ForeignKeyName]
        FOREIGN KEY ([ColumnName] [,...])
        REFERENCES RefTableName
            [(ColumnName [,...])] [ON DELETE CASCADE]] [...]
    }
)
[TableCompression]
[UNIQUE HASH ON (HashColumnName [,...])
    PAGES = PrimaryPages]
[AGING {LRU|
         USE ColumnName
             LIFETIME Num1 {SECOND[S] | MINUTE[S] | HOUR[S] |DAY[S]}
               [CYCLE Num2 {SECOND[S] | MINUTE[S] |HOUR[S] |DAY[S]}]
       }[ON|OFF]
]
[AS SelectQuery]

The syntax for a global temporary table is:

CREATE GLOBAL TEMPORARY TABLE [Owner.]TableName
(
    {{ColumnDefinition} [,...]
     [PRIMARY KEY (ColumnName [,...]) |
     [[CONSTRAINT ForeignKeyName]
        FOREIGN KEY ([ColumnName] [,...])
        REFERENCES RefTableName
             [(ColumnName [,...])] [ON DELETE CASCADE]] [...]
      }
)
[UNIQUE HASH ON (HashColumnName [,...])
    PAGES = PrimaryPages]
[ON COMMIT { DELETE | PRESERVE } ROWS 
]

Parameters

ParameterDescription
[Owner.]TableNameName to be assigned to the new table. Two tables cannot have the same owner name and table name.

If you do not specify the owner name, your login name becomes the owner name for the new table. Owners of tables in TimesTen are determined by the user ID settings or login names. Oracle table owner names must always match TimesTen table owner names.

For rules on creating names, see "Basic names".

GLOBAL TEMPORARYSpecifies that the table being created is a global temporary table. A temporary table is similar to a persistent table but it is effectively materialized only when referenced in a connection.

A global temporary table definition is persistent and is visible to all connections, but the table instance is local to each connection. It is created when a command referencing the table is compiled for a connection and dropped when the connection is disconnected. All instances of the same temporary table have the same name but they are identified by an additional connection ID together with the table name. Global temporary tables are allocated in temp space.

The contents of a global temporary table cannot be shared between connections. Each connection sees only its own content of the table and compiled commands that reference temporary tables are not shared among connections.

When DDL_REPLICATION_LEVEL=2, the creation of a global temporary table is replicated in an active standby pair, but the global temporary table is not included in the replication scheme.

Temporary tables are automatically excluded from active standby pairs or when the DATASTORE element has been specified.

A cache group table cannot be defined as a temporary table.

Changes to temporary tables cannot be tracked with XLA.

Operations on temporary tables do generate log records. The amount of log they generate is less than for permanent tables.

Truncate table is not supported with global temporary tables.

Local temporary tables are not supported.

No object privileges are needed to access global temporary tables.

Do not specify the AS SelectQuery clause with global temporary tables.

ColumnDefinitionAn individual column in a table. Each table must have at least one column. See "Column Definition".

If you specify the AS SelectQuery clause, ColumnDefinition is optional.

ColumnNameNames of the columns that form the primary key for the table to be created. Up to 16 columns can be specified for the primary key. For a foreign key, the ColumnName is optional. If not specified for a foreign key, the reference is to the parent table's primary key.

If you specify the AS SelectQuery clause, you do not have to specify the ColumnName. Do not specify the data type with the AS SelectQuery clause.

PRIMARY KEYPRIMARY KEY may only be specified once in a table definition. It provides a way of identifying one or more columns that, together, form the primary key of the table. The contents of the primary key have to be unique and NOT NULL. You cannot specify a column as both UNIQUE and a single column PRIMARY KEY.
CONSTRAINT ForeignKeyNameSpecifies an optional user-defined name for a foreign key. If not provided by the user, the system provides a default name.
FOREIGN KEYThis specifies a foreign key constraint between the new table and the referenced table identified by RefTableName. There are two lists of columns specified in the foreign key constraint.

Columns in the first list are columns of the new table and are called the referencing columns. Columns in the second list are columns of the referenced table and are called referenced columns. These two lists must match in data type, including length, precision and scale. The referenced table must already have a primary key or unique index on the referenced column.

The column name list of referenced columns is optional. If omitted, the primary index of RefTableName is used.

The declaration of a foreign key creates a range index on the referencing columns. The user cannot drop the referenced table or its referenced index until the referencing table is dropped.

The foreign key constraint asserts that each row in the new table must match a row in the referenced table such that the contents of the referencing columns are equal to the contents of the referenced columns. Any INSERT, DELETE or UPDATE statements that violate the constraint return TimesTen error 3001.

TimesTen supports SQL-92 "NO ACTION" update and delete rules and ON DELETE CASCADE. Foreign key constraints are not deferrable.

A foreign key can be defined on a global temporary table, but it can only reference a global temporary table. If a parent table is defined with COMMIT DELETE, the child table must also have the COMMIT DELETE attribute.

A foreign key cannot reference an active parent table. An active parent table is one that has some instance materialized for a connection.

If you specify the AS SelectQuery clause, you cannot define a foreign key on the table you are creating.

[ON DELETE CASCADE]Enables the ON DELETE CASCADE referential action. If specified, when rows containing referenced key values are deleted from a parent table, rows in child tables with dependent foreign key values are also deleted.
TableCompressionDefines compression at the column level, which stores data more efficiently. Eliminates redundant storage of duplicate values within columns and improves the performance of SQL queries that perform full table scans. See "In-memory columnar compression of tables" for details.
UNIQUEUNIQUE provides a way of identifying a column where each row must contain a unique value.
UNIQUE HASH ONHash index for the table. Only unique hash indexes are created. This parameter is used for equality predicates. UNIQUE HASH ON requires that a primary key be defined.
HashColumnNameColumn defined in the table that is to participate in the hash key of this table. The columns specified in the hash index must be identical to the columns in the primary key.

If you specify the AS SelectQuery clause, you must define HashColumnName on the table you are creating.

PrimaryPagesSpecifies the expected number of pages in the table. This number affects the number of buckets that are allocated for the table's hash index. The minimum is 1. If your estimate is too small, performance is degraded.
[ON COMMIT {DELETE|PRESERVE} ROWS]The optional statement specifies whether to delete or preserve rows when a transaction that touches a global temporary table is committed. If not specified, the rows of the temporary table are deleted.
[AGING LRU [ON|OFF]]If specified, defines the LRU aging policy for the table. The LRU aging policy defines the type of aging (least recently used (LRU)), the aging state (ON or OFF) and the LRU aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

LRU attributes are defined by calling the ttAgingLRUConfig procedure. LRU attributes are not defined at the SQL level.

For more information about LRU aging, see "Implementing aging in your tables" in Oracle TimesTen In-Memory Database Operations Guide.

[AGING USE ColumnName...[ON|OFF]]If specified, defines the time-based aging policy for the table. The time-based aging policy defines the type of aging (time-based), the aging state (ON or OFF) and the time-based aging attributes.

Set the aging state to either ON or OFF. ON indicates that the aging state is enabled and aging is done automatically. OFF indicates that the aging state is disabled and aging is not done automatically. In both cases, the aging policy is defined. The default is ON.

Time-based aging attributes are defined at the SQL level and are specified by the LIFETIME and CYCLE clauses.

Specify ColumnName as the name of the column used for time-based aging. Define the column as NOT NULL and of data type TIMESTAMP or DATE. The value of this column is subtracted from SYSDATE, truncated using the specified unit (second, minute, hour, day) and then compared to the LIFETIME value. If the result is greater than the LIFETIME value, then the row is a candidate for aging.

The values of the column that you use for aging are updated by your applications. If the value of this column is unknown for some rows, and you do not want the rows to be aged, define the column with a large default value (the column cannot be NULL).

You can define your aging column with a data type of TT_TIMESTAMP or TT_DATE. If you choose data type TT_DATE, then you must specify the LIFETIME unit as days.

If you specify the AS SelectQuery clause, you must define the ColumnName on the table you are creating.

For more information about time-based aging, see "Implementing aging in your tables" in Oracle TimesTen In-Memory Database Operations Guide.

LIFETIME Num1 {SECOND[S]| MINUTE[S]|HOUR[S]| DAY[S]}LIFETIME is a time-based aging attribute and is a required clause.

Specify the LIFETIME clause after the AGING USE ColumnName clause.

The LIFETIME clause specifies the minimum amount of time data is kept in cache.

Specify Num1 as a positive integer constant to indicate the unit of time expressed in seconds, minutes, hours or days that rows should be kept in cache. Rows that exceed the LIFETIME value are aged out (deleted from the table). If you define your aging column with data type TT_DATE, then you must specify DAYS as the LIFETIME unit.

The concept of time resolution is supported. If DAYS is specified as the time resolution, then all rows whose timestamp belongs to the same day are aged out at the same time. If HOURS is specified as the time resolution, then all rows with timestamp values within that hour are aged at the same time. A LIFETIME of 3 days is different than a LIFETIME of 72 hours (3*24) or a LIFETIME of 432 minutes (3*24*60).

[CYCLE Num2 {SECOND[S] |MINUTE[S]|HOUR[S]| DAY[S]}]CYCLE is a time-based aging attribute and is optional. Specify the CYCLE clause after the LIFETIME clause.

The CYCLE clause indicates how often the system should examine rows to see if data exceeds the specified LIFETIME value and should be aged out (deleted).

Specify Num2 as a positive integer constant.

If you do not specify the CYCLE clause, then the default value is 5 minutes. If you specify 0 for Num2, then the aging thread wakes up every second.

If the aging state is OFF, then aging is not done automatically and the CYCLE clause is ignored.

AS SelectQueryIf specified, creates a new table from the contents of the result set of the SelectQuery. The rows returned by SelectQuery are inserted into the table.

Data types and data type lengths are derived from SelectQuery.

SelectQuery is a valid SELECT statement that may or may not contain a subquery.



Column Definition

SQL syntax

For all data types other than LOBs, the syntax is as follows:

ColumnName ColumnDataType
 [DEFAULT DefaultVal]
 [[NOT] INLINE]
 [PRIMARY KEY | UNIQUE | 
 NULL [UNIQUE] | 
 NOT NULL [PRIMARY KEY | UNIQUE] 
]

For LOB data types, you cannot create a primary key or unique constraint on LOB columns. In addition, LOB data types are stored out of line, so the INLINE attribute cannot be specified.

For all LOB data types, the syntax is:

ColumnName ColumnDataType
 [DEFAULT DefaultVal] [[NOT] NULL] |
 [[NOT] NULL] [DEFAULT DefaultVal]

Parameters

The column definition has the following parameters:

ParameterDescription
ColumnNameName to be assigned to one of the columns in the new table. No two columns in the table can be given the same name. A table can have a maximum of 1000 columns.

If you specify the AS SelectQuery clause, ColumnName is optional. The number of column names must match the number of columns in SelectQuery.

ColumnDataTypeType of data the column can contain. Some data types require that you indicate a length. See Chapter 1, "Data Types" for the data types that can be specified.

If you specify the AS SelectQuery clause, do not specify ColumnDataType.

DEFAULT DefaultValIndicates that if a value is not specified for the column in an INSERT statement, the default value DefaultVal is inserted into the column. The default value specified must have a compatible type with the column's data type. A default value can be as long as the data type of the associated column allows. You cannot assign a default value for the ROWID data type or for columns in read-only cache groups. In addition, you cannot use a function within the DEFAULT clause.

Legal data types for DefaultVal can be one of:

If the default value is one of the users, the column's data type must be either CHAR or VARCHAR2 and the column's width must be at least 30 characters.

If you specify the AS SelectQuery clause, optionally, you can specify the DEFAULT clause on the table you are creating.

INLINE|NOT INLINEBy default, variable-length columns whose declared column length is greater than 128 bytes are stored out of line. Variable-length columns whose declared column length is less than or equal to 128 bytes are stored inline. The default behavior can be overridden during table creation through the use of the INLINE and NOT INLINE keywords.

If you specify the AS SelectQuery clause, optionally, you can specify the INLINE | NOT INLINE clause on the table you are creating.

NULLIndicates that the column can contain NULL values.

If you specify the AS SelectQuery clause, optionally, you can specify NULL on the table you are creating.

NOT NULLIndicates that the column cannot contain NULL values. If NOT NULL is specified, any statement that attempts to place a NULL value in the column is rejected.

If you specify the AS SelectQuery clause, optionally, you can specify NOT NULL on the table you are creating.

UNIQUEA unique constraint placed on the column. No two rows in the table may have the same value for this column. TimesTen creates a unique range index to enforce uniqueness. This means that a column with a unique constraint can use more memory and time during execution than a column without the constraint. Cannot be used with PRIMARY KEY.

If you specify the AS SelectQuery clause, optionally, you can specify UNIQUE on the table you are creating.

PRIMARY KEYA unique NOT NULL constraint placed on the column. No two rows in the table may have the same value for this column. Cannot be used with UNIQUE.

If you specify the AS SelectQuery clause, optionally, you can specify PRIMARY KEY on the table you are creating.


Description

  • All columns participating in the primary key are NOT NULL.

  • A PRIMARY KEY that is specified in the ColumnDefinition can only be specified for one column.

  • PRIMARY KEY cannot be specified in both the ColumnDefinition parameters and CREATE TABLE parameters.

  • For both primary key and foreign key constraints, duplicate column names are not allowed in the constraint column list.

  • If ON DELETE CASCADE is specified on a foreign key constraint for a child table, a user can delete rows from a parent table for which the user has the DELETE privilege without requiring explicit DELETE privilege on the child table.

  • To change the ON DELETE CASCADE triggered action, drop then redefine the foreign key constraint.

  • You cannot create a table that has a foreign key referencing a cached table.

  • UNIQUE column constraint and default column values are not supported with materialized views.

  • Use the ALTER TABLE statement to change the representation of the primary key index for a table.

  • If you specify the AS SelectQuery clause:

    • Data types and data type lengths are derived from the SelectQuery. Do not specify data types on the columns of the table you are creating.

    • TimesTen defines on columns in the new table NOT NULL constraints that were explicitly created on the corresponding columns of the selected table if SelectQuery selects the column rather than an expression containing the column.

    • NOT NULL constraints that were implicitly created by TimesTen on columns of the selected table (for example, primary keys) are carried over to the new table. You can override the NOT NULL constraint on the selected table by defining the new column as NULL. For example: CREATE TABLE newtable (newcol NULL) AS SELECT (col) FROM tab;

    • NOT INLINE/INLINE attributes are carried over to the new table.

    • Unique keys, foreign keys, indexes and column default values are not carried over to the new table.

    • If all expressions in SelectQuery are columns, rather than expressions, then you can omit the columns from the table you are creating. In this case, the name of the columns are the same as the columns in SelectQuery. If the SelectQuery contains an expression rather than a simple column reference, either specify a column alias or name the column in the CREATE TABLE statement.

    • Do not specify foreign keys on the table you are creating.

    • Do not specify the SELECT FOR UPDATE clause in SelectQuery.

    • The ORDER BY clause is not supported when you use the AS SelectQuery clause.

    • SelectQuery cannot contain set operators UNION, MINUS, INTERSECT.

    • In a replicated environment for an active standby pair, if DDL_REPLICATION_LEVEL=2 when you execute the CREATE TABLE on the active database, the table, including global temporary tables, will be replicated to all databases in the replication scheme. Tables are only replicated to TimesTen instances when DDL_REPLICATION_LEVEL=2.

      To include a new table into an active standby pair when the table is created, set DDL_REPLICATION_LEVEL=2 and DDL_REPLICATION_ACTION to INCLUDE before executing the CREATE TABLE statement on the active database. If DDL_REPLICATION_ACTION is set to EXCLUDE, the new table is not included in the active standby pair. You must execute the ALTER ACTIVE STANDBY PAIR INCLUDE TABLE statement to include the table after creation on all databases. In this case, the table must be empty and present on all databases before executing the ALTER ACTIVE STANDBY PAIR INCLUDE TABLE statement as the table contents will be truncated when this statement is executed.

      See "ALTER SESSION" for more information.

  • By default, a range index is created to enforce the primary key. Use the UNIQUE HASH clause to specify a hash index for the primary key.

    • If your application performs range queries using a table's primary key, then choose a range index for that table by omitting the UNIQUE HASH clause.

    • If your application performs only exact match lookups on the primary key, then a hash index may offer better response time and throughput. In such a case, specify the UNIQUE HASH clause.

  • TimesTen supports one hash index per table. A hash index is defined on the primary key of a table.

  • A unique hash index can be specified only for the primary key.

  • A hash index is created with a fixed number of buckets that remains constant for the life of the table or until the hash index is resized using an ALTER TABLE statement to change hash index size. Fewer buckets in the hash index result in more hash collisions. More buckets reduce collisions but can waste memory. Hash key comparison is a fast operation, so a small number of hash collisions does not cause a performance problem for TimesTen.

    The bucket count is derived as the ratio of the maximum table cardinality, divided by the value of the PAGES parameter. To ensure that the hash index is sized correctly, an application must indicate the expected size of the table. This is done with the PAGES parameter. The PAGES parameter should be the expected number of rows in the table, divided by 256. (Since 256 is the number of rows TimesTen stores on each page, the value provided is the expected number of pages in the table.) The application may specify a larger value for PAGES, and therefore fewer rows per bucket on average, if memory use is not an overriding concern.

  • At most 16 columns are allowed in a hash key.

  • ON DELETE CASCADE is supported on detail tables of a materialized view. If you have a materialized view defined over a child table, a deletion from the parent table causes cascaded deletes in the child table. This, in turn, triggers changes in the materialized view.

  • The total number of rows reported by the DELETE statement does not include rows deleted from child tables as a result of the ON DELETE CASCADE action.

  • For ON DELETE CASCADE: Since different paths may lead from a parent table to a child table, the following rule is enforced:

    • Either all paths from a parent table to a child table are "delete" paths or all paths from a parent table to a child table are "do not delete" paths. Specify ON DELETE CASCADE on all child tables on the "delete" path.

    • This rule does not apply to paths from one parent to different children or from different parents to the same child.

  • For ON DELETE CASCADE, a second rule is also enforced:

    • If a table is reached by a "delete" path, then all its children are also reached by a "delete" path.

  • For ON DELETE CASCADE with replication, the following restrictions apply:

    • The foreign keys specified with ON DELETE CASCADE must match between the Master and subscriber for replicated tables. Checking is done at runtime. If there is an error, the receiver thread stops working.

    • All tables in the delete cascade tree have to be replicated if any table in the tree is replicated. This restriction is checked when the replication scheme is created or when a foreign key with ON DELETE CASCADE is added to one of the replication tables. If an error is found, the operation is aborted. You may be required to drop the replication scheme first before trying to change the foreign key constraint.

    • You must stop the replication agent before adding or dropping a foreign key on a replicated table.

  • The data in a global temporary is private to the current connection and does not need to be secured between users. Thus global temporary tables do not require object privileges.

  • After you have defined an aging policy for the table, you cannot change the policy from LRU to time-based or from time-based to LRU. You must first drop aging and then alter the table to add a new aging policy.

  • The aging policy must be defined to change the aging state.

  • For the time-based aging policy, you cannot add or modify the aging column. This is because you cannot add or modify a NOT NULL column.

  • LRU and time-based aging can be combined in one system. If you use only LRU aging, the aging thread wakes up based on the cycle specified for the whole database. If you use only time-based aging, the aging thread wakes up based on an optimal frequency. This frequency is determined by the values specified in the CYCLE clause for all tables. If you use both LRU and time-based aging, then the thread wakes up based on a combined consideration of both types.

  • The following rules determine if a row is accessed or referenced for LRU aging:

    • Any rows used to build the result set of a SELECT statement.

    • Any rows used to build the result set of an INSERT ... SELECT statement.

    • Any rows that are about to be updated or deleted.

  • Compiled commands are marked invalid and need recompilation when you either drop LRU aging from or add LRU aging to tables that are referenced in the commands.

  • Call the ttAgingScheduleNow procedure to schedule the aging process immediately regardless of the aging state.

  • Aging restrictions:

    • LRU aging and time-based aging are not supported on detail tables of materialized views.

    • LRU aging and time-based aging are not supported on global temporary tables.

    • You cannot drop the column that is used for time-based aging.

    • The aging policy and aging state must be the same in all sites of replication.

    • Tables that are related by foreign keys must have the same aging policy.

    • For LRU aging, if a child row is not a candidate for aging, neither this child row nor its parent row are deleted. ON DELETE CASCADE settings are ignored.

    • For time-based aging, if a parent row is a candidate for aging, then all child rows are deleted. ON DELETE CASCADE (whether specified or not) is ignored.


In-memory columnar compression of tables

You can compress tables at the column level, which stores data more efficiently. This eliminates redundant storage of duplicate values within columns and improves the performance of SQL queries that perform full table scans.

You can define one or more columns in a table to be compressed, which is called a compressed column group. You can define one or more compressed column groups in each table.

A dictionary table is created for each compressed column group that contains a column with all the distinct values of the compressed column group. The compressed column group now contains a pointer to the row in the dictionary table for the appropriate value. The width of this pointer can be 1, 2, or 4 bytes long depending on the maximum number of entries you defined for the dictionary table. So if the column being compressed was wider than the pointer width, you have reduced the amount of space used by the table.

Figure 6-1 shows the compressed column group in the table pointing to the appropriate row in the dictionary table.

Figure 6-1 Table Compression

Description of Figure 6-1 follows
Description of "Figure 6-1 Table Compression"

The dictionary table has a column of pointers to each of the distinct values. When the user configures the maximum number of distinct entries for the compressed column group, the size of the compressed column group is set as follows:

  • 1 byte for a maximum number of entries of 255 (28-1). When the maximum number is between 1 and 255, the dictionary size is set to 255 (28-1) values and the compressed column group pointer column is 1 byte.

  • 2 bytes for a maximum number of entries of 65,535 (216-1). When the maximum number is between 256 and 65,535, the dictionary size is set to 65,535 (216-1) values and the compressed column group pointer column is 2 bytes.

  • 4 bytes for a maximum number of entries of 4,294,967,295 (232-1). When the maximum number is between 65,536 and 4,294,967,295, the dictionary size is set to 4,294,967,295 (232-1) values and the compressed column group pointer column is 4 bytes. This is the default.

Syntax

The syntax for TableCompression is:

[COMPRESS (CompressColumns [,...])] OPTIMIZED FOR READ

The CompressColumns syntax is as follows:

{ColumnDefinition | (ColumnDefinition [,...])} BY DICTIONARY 
   [MAXVALUES = CompressMax]

Parameters

TableCompression syntax has the following parameters:

ParameterDescription
COMPRESS (CompressColumns [,...])Defines a compressed column group for a table that is enabled for compression. This can include one or more columns in the table. However, a column can be included in only one compressed column group.

Only INLINE columns are supported when you specify multiple columns in a compressed column group. You can only specify out-of-line columns in a compression group on its own.

Each compressed column group is limited to a maximum of 16 columns.

OPTIMIZED FOR READWhen specified on the CREATE TABLE statement, enables the table for compressed column groups. You can add compressed column groups at table creation with the CREATE TABLE statement or later with the ALTER TABLE statement.
BY DICTIONARYDefines a compression dictionary for each compressed column group.
MAXVALUES = CompressMaxCompressMax is the total number of distinct values in the table and sets the size for the compressed column group pointer column to 1, 2, or 4 bytes and sets the size for the maximum number of entries in the dictionary table.

For the dictionary table, NULL is counted as one unique value.

CompressMax takes an integer between 1 and 232-1.

The maximum size defaults to size of 232-1 if the MAXVALUES clause is omitted, which uses 4 bytes for the pointer column. An error is thrown if the value is greater than 232-1.


Description

  • Compressed column groups can be added at the time of table creation or added later using ALTER TABLE. You can drop the entire compressed column group with the ALTER TABLE statement.

  • You can create a primary or unique key, where part or or all of the columns included in the key are compressed. For compressed columns included in a primary or unique key, you can include columns that exist within a compressed column group, but you do not have to include all of the columns within the compressed column group. In addition, you can include columns from different compressed column groups.

  • For compressed tables, all SQL operations lock the table. Table and index scans that access the columns of any compressed column group are somewhat slower due to dictionary lookup. However, since all the operations on the table acquire table locks, you do not need to acquire and release lower level locks. INSERT, DELETE and UPDATE operations on these tables will not scale.

  • Indexes can be created on any columns in the table. This includes compressed columns and includes columns that exist in separate compression column groups.

  • LOB columns cannot be compressed.

  • Compression is not supported on columns in replicated tables, cache group tables, grid tables, or on global temporary tables. You cannot create a table with the CREATE TABLE AS SELECT statement when defining in-memory columnar compression for that table in that statement.

  • You cannot create materialized views and materialized view logs on tables enabled for compression.

Examples

A range index is created on partnumber because it is the primary key.

Command> CREATE TABLE price
> (partnumber INTEGER NOT NULL PRIMARY KEY,
> vendornumber INTEGER NOT NULL,
> vendpartnum CHAR(20) NOT NULL,
> unitprice DECIMAL(10,2),
> deliverydays SMALLINT,
> discountqty SMALLINT);
Command> INDEXES price;
Indexes on table SAMPLEUSER.PRICE:
 PRICE: unique range index on columns:
    PARTNUMBER
  1 index found.
1 index found on 1 table.

A hash index is created on column clubname, the primary key.

CREATE TABLE recreation.clubs
(clubname CHAR(15) NOT NULL PRIMARY KEY,
 clubphone SMALLINT,
 activity CHAR(18))
UNIQUE HASH ON (clubname) PAGES = 30;

A range index is created on the two columns membername and club because together they form the primary key.

Command> CREATE TABLE recreation.members
> (membername CHAR(20) NOT NULL,
>  club CHAR(15) NOT NULL,
>  memberphone SMALLINT,
>  PRIMARY KEY (membername, club));
Command> INDEXES recreation.members;
Indexes on table RECREATION.MEMBERS:
  MEMBERS: unique range index on columns:
    MEMBERNAME
    CLUB
  1 index found on 1 table.

No hash index is created on the table recreation.events.

CREATE TABLE recreation.events
(sponsorclub CHAR(15),
 event CHAR(30),
 coordinator CHAR(20),
 results VARBINARY(10000));

A hash index is created on the column vendornumber.

CREATE TABLE purchasing.vendors
(vendornumber INTEGER NOT NULL PRIMARY KEY,
 vendorname CHAR(30) NOT NULL,
 contactname CHAR(30),
 phonenumber CHAR(15),
 vendorstreet CHAR(30) NOT NULL,
 vendorcity CHAR(20) NOT NULL,
 vendorstate CHAR(2) NOT NULL,
 vendorzipcode CHAR(10) NOT NULL,
 vendorremarks VARCHAR(60))
UNIQUE HASH ON (vendornumber) PAGES = 101;

A hash index is created on the columns membername and club because together they form the primary key.

CREATE TABLE recreation.members
    (membername CHAR(20) NOT NULL,
        club CHAR(15) NOT NULL,
        memberphone SMALLINT,
        PRIMARY KEY (membername, club))
    UNIQUE HASH ON (membername, club) PAGES = 100;

A hash index is created on the columns firstname and lastname because together they form the primary key in the table authors. A foreign key is created on the columns authorfirstname and authorlastname in the table books that references the primary key in the table authors.

CREATE TABLE authors
    (firstname VARCHAR(255) NOT NULL,
        lastname VARCHAR(255) NOT NULL,
        description VARCHAR(2000),
        PRIMARY KEY (firstname, lastname))
    UNIQUE HASH ON (firstname, lastname) PAGES=20;
CREATE TABLE books
    (title VARCHAR(100),
    authorfirstname VARCHAR(255),
    authorlastname VARCHAR(255),
    price DECIMAL(5,2),
    FOREIGN KEY (authorfirstname, authorlastname) 
    REFERENCES authors(firstname, lastname));

The following statement overrides the default character of VARCHAR columns and creates a table where one VARCHAR (10) column is NOT INLINE and one VARCHAR (144) is INLINE:

CREATE TABLE t1
    (c1 VARCHAR(10) NOT INLINE NOT NULL,
    c2 VARCHAR(144) INLINE NOT NULL);

The following statement creates a table with a UNIQUE column for book titles:

CREATE TABLE books
    (title VARCHAR(100) UNIQUE,
        authorfirstname VARCHAR(255),
        authorlastname VARCHAR(255),
        price DECIMAL(5,2),
        FOREIGN KEY (authorfirstname, authorlastname)
        REFERENCES authors(firstname, lastname));

The following statement creates a table with a default value of 1 on column x1 and a default value of SYSDATE on column d:

CREATE TABLE t1
    (x1 INT DEFAULT 1, d TIMESTAMP DEFAULT SYSDATE);

This example creates the rangex table and defines col1 as the primary key. A range index is created by default.

Command> CREATE TABLE rangex (col1 TT_INTEGER PRIMARY KEY);
Command> INDEXES rangex;
Indexes on table SAMPLEUSER.RANGEX:
  RANGEX: unique range index on columns:
    COL1
  1 index found
1 index found on 1 table.

The following statement illustrates the use of the ON DELETE CASCADE clause for parent/child tables of the HR schema. Tables with foreign keys have been altered to enable ON DELETE CASCADE.

ALTER TABLE countries
ADD CONSTRAINT countr_reg_fk
         FOREIGN KEY (region_id)
           REFERENCES regions(region_id) ON DELETE CASCADE;
ALTER TABLE locations
     ADD CONSTRAINT loc_c_id_fk
          FOREIGN KEY (country_id)
                    REFERENCES countries(country_id) ON DELETE CASCADE;
ALTER TABLE departments
     ADD CONSTRAINT dept_loc_fk
         FOREIGN KEY (location_id)
           REFERENCES locations (location_id) ON DELETE CASCADE;
ALTER TABLE employees
     ADD CONSTRAINT     emp_dept_fk
         FOREIGN KEY (department_id)
           REFERENCES departments ON DELETE CASCADE;
ALTER TABLE employees
     ADD CONSTRAINT     emp_job_fk
         FOREIGN KEY (job_id)
           REFERENCES jobs (job_id);
ALTER TABLE job_history
     ADD CONSTRAINT     jhist_job_fk
         FOREIGN KEY (job_id)
           REFERENCES jobs;
ALTER TABLE job_history
     ADD CONSTRAINT     jhist_emp_fk
         FOREIGN KEY (employee_id)
           REFERENCES employees ON DELETE CASCADE;
ALTER TABLE job_history
     ADD CONSTRAINT     jhist_dept_fk
         FOREIGN KEY (department_id)
           REFERENCES departments ON DELETE CASCADE;
     ;

This example shows how time resolution works with aging.

If lifetime is 3 days (resolution is in days):

  • If (SYSDATE - ColumnValue) <= 3, do not age.

  • If (SYSDATE - ColumnValue) > 3, then the row is a candidate for aging.

  • If (SYSDATE - ColumnValue) = 3 days, 22 hours. The row is not aged out if you specified a lifetime of 3 days. The row would be aged out if you had specified a lifetime of 72 hours.

This example creates a table with LRU aging. Aging state is ON by default.

CREATE TABLE agingdemo
       (agingid NUMBER NOT NULL PRIMARY KEY,
        name  VARCHAR2 (20)
       )
       AGING LRU;
Command> DESCRIBE agingdemo;
Table USER.AGINGDEMO:
  Columns:
     *AGINGID NUMBER NOT NULL
     NAME VARCHAR2 (20) INLINE
     AGING LRU ON
1 table found.
(primary key columns are indicated with *)

This example creates a table with time-based aging. Lifetime is 3 days. Cycle is not specified, so the default is 5 minutes. Aging state is OFF.

CREATE TABLE agingdemo2
       (agingid NUMBER NOT NULL PRIMARY KEY,
        name  VARCHAR2 (20),
        agingcolumn TIMESTAMP NOT NULL
        )
        AGING USE agingcolumn LIFETIME 3 DAYS OFF;
Command> DESCRIBE agingdemo2;
Table USER.AGINGDEMO2:
  Columns:
     *AGINGID NUMBER NOT NULL
     NAME VARCHAR2 (20) INLINE
     AGINGCOLUMN TIMESTAMP (6) NOT NULL
  Aging use AGINGCOLUMN lifetime 3 days cycle 5 minutes off
1 table found.
(primary key columns are indicated with *)

This example generates an error message. It illustrates that after you create an aging policy, you cannot change it. You must drop aging and redefine aging.

CREATE TABLE agingdemo2
        (agingid NUMBER NOT NULL PRIMARY KEY,
        name  VARCHAR2 (20),
        agingcolumn TIMESTAMP NOT NULL
        )
        AGING USE agingcolumn LIFETIME 3 DAYS OFF;
ALTER TABLE agingdemo2
        ADD AGING LRU;
 2980: Cannot add aging policy to a table with an existing aging policy. Have to
drop the old aging first
The command failed.
DROP aging on the table and redefine with LRU aging.
ALTER TABLE agingdemo2
        DROP AGING;
ALTER TABLE agingdemo2
        ADD AGING LRU;
Command> DESCRIBE agingdemo2;
Table USER.AGINGDEMO2:
  Columns:
   *AGINGID                         NUMBER NOT NULL
    NAME                            VARCHAR2 (20) INLINE
    AGINGCOLUMN                     TIMESTAMP (6) NOT NULL
  Aging lru on
1 table found.
(primary key columns are indicated with *)

Attempt to create a table with time-based aging. Define aging column with data type TT_DATE and LIFETIME 3 hours. An error is generated because the LIFETIME unit must be expressed as DAYS.

Command> CREATE TABLE aging1 (col1 TT_INTEGER PRIMARY KEY, 
         col2 TT_DATE NOT NULL) AGING USE col2 LIFETIME 3 HOURS;
 2977: Only DAY lifetime unit is allowed with a TT_DATE column
The command failed.

Use AS SelectQuery clause to create the table emp. Select last_name from the employees table where employee_id between 100 and 105. You see 6 rows inserted into emp. First issue the SELECT statement to see rows that should be returned.

Command> SELECT last_name FROM employees 
 WHERE employee_id BETWEEN 100 AND 105;
< King >
< Kochhar >
< De Haan >
< Hunold >
< Ernst >
< Austin >
6 rows found.
Command> CREATE TABLE emp AS SELECT employee_id FROM employees
>WHERE employee_id BETWEEN 100 AND 105;
6 rows inserted.
Command> SELECT * FROM emp;
< King >
< Kochhar >
< De Haan >
< Hunold >
< Ernst >
< Austin >
6 rows found.

Use AS SelectQuery to create table totalsal. Sum salary and insert result into totalsalary. Define alias s for SelectQuery expression.

Command> CREATE TABLE totalsal AS SELECT SUM (salary) s FROM employees;
1 row inserted.
Command> SELECT * FROM totalsal;
< 691400 >
1 row found.

Use AS SelectQuery to create table defined with column commission_pct. Set default to .3. First describe table employees to show that column commission_pct is of type NUMBER (2,2). For table c_pct, column commission_pct inherits type NUMBER (2,2) from column commission_pct of employees table.

Command> DESCRIBE employees;
Table SAMPLEUSER.EMPLOYEES:
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE NOT NULL
    EMAIL                           VARCHAR2 (25) INLINE UNIQUE NOT NULL
    PHONE_NUMBER                    VARCHAR2 (20) INLINE
    HIRE_DATE                       DATE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    SALARY                          NUMBER (8,2)
    COMMISSION_PCT                  NUMBER (2,2)
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)

1 table found.
(primary key columns are indicated with *)
Command> CREATE TABLE c_pct (commission_pct DEFAULT .3) AS SELECT
         commission_pct FROM employees;
107 rows inserted.
Command> DESCRIBE c_pct;

Table SAMPLEUSER.C_PCT:
  Columns:
    COMMISSION_PCT                 NUMBER (2,2) DEFAULT .3

1 table found.
(primary key columns are indicated with *)

The following example creates the employees table where the job_id is compressed:

Command> CREATE TABLE EMPLOYEES
 (EMPLOYEE_ID NUMBER (6) PRIMARY KEY, 
 FIRST_NAME VARCHAR2(20), 
 LAST_NAME VARCHAR2(25) NOT NULL, 
 EMAIL VARCHAR2(25) NOT NULL, 
 PHONE_NUMBER VARCHAR2(20),
 HIRE_DATE DATE NOT NULL, 
 JOB_ID VARCHAR2(10) NOT NULL, 
 SALARY NUMBER (8,2), 
 COMMISSION_PCT NUMBER (2,2), 
 MANAGER_ID NUMBER(6), 
 DEPARTMENT_ID NUMBER(4)) 
 COMPRESS (JOB_ID BY DICTIONARY) OPTIMIZED FOR READ;

Command> DESCRIBE EMPLOYEES;
 
Table MYSCHEMA.EMPLOYEES:
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE NOT NULL
    EMAIL                           VARCHAR2 (25) INLINE NOT NULL
    PHONE_NUMBER                    VARCHAR2 (20) INLINE
    HIRE_DATE                       DATE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    SALARY                          NUMBER (8,2)
    COMMISSION_PCT                  NUMBER (2,2)
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)
  COMPRESS ( JOB_ID BY DICTIONARY ) OPTIMIZED FOR READ
 
1 table found.
(primary key columns are indicated with *)

The following example shows that there are three dictionary table sizes. The value you specify for the maximum number of entries is rounded up to the next size. For example, specifying 400 as the maximum number of job IDs creates a dictionary table that can have at most 65535 entries. The default size of 232-1 is not shown in the DESCRIBE output.

Command> CREATE TABLE employees 
 (employee_id NUMBER(6) PRIMARY KEY, 
  first_name VARCHAR2(20), 
  last_name VARCHAR2(25), 
  email VARCHAR2(25) NOT NULL, 
  job_id VARCHAR2(10) NOT NULL, 
  manager_id NUMBER(6), 
  department_id NUMBER(4)) 
 COMPRESS (last_name BY DICTIONARY MAXVALUES=70000, 
           job_id BY DICTIONARY MAXVALUES=400, 
           department_id BY DICTIONARY MAXVALUES=100) 
 OPTIMIZED FOR READ;

Command> DESCRIBE employees;                                                   
Table MYSCHEMA.EMPLOYEES:
  Columns:
   *EMPLOYEE_ID                     NUMBER (6) NOT NULL
    FIRST_NAME                      VARCHAR2 (20) INLINE
    LAST_NAME                       VARCHAR2 (25) INLINE
    EMAILS                          VARCHAR2 (25) INLINE NOT NULL
    JOB_ID                          VARCHAR2 (10) INLINE NOT NULL
    MANAGER_ID                      NUMBER (6)
    DEPARTMENT_ID                   NUMBER (4)
  COMPRESS ( LAST_NAME BY DICTIONARY,
             JOB_ID BY DICTIONARY MAXVALUES=65535,
             DEPARTMENT_ID BY DICTIONARY MAXVALUES=255 ) OPTIMIZED FOR READ
 
1 table found.
(primary key columns are indicated with *)

See also


ALTER TABLE
DROP TABLE
TRUNCATE TABLE
UPDATE

CREATE USER

The CREATE USER statement creates a user of a TimesTen database.

Required privilege

ADMIN

SQL syntax

CREATE USER user IDENTIFIED BY {password | "password"}
CREATE USER user IDENTIFIED EXTERNALLY

Parameters

ParameterDescription
userName of the user that is being added to the database.
IDENTIFIEDIdentification clause.
BY {password |"password"}Internal users must be given a TimesTen password. To perform database operations using an internal user name, the user must supply this password.
EXTERNALLYIdentifies the operating system user to the TimesTen database. To perform database operations as an external user, the process needs a TimesTen external user name that matches the user name authenticated by the operating system or network. A password is not required by TimesTen because the user has been authenticated by the operating system at login time.

Description

  • Database users can be internal or external.

    • Internal users are defined for a TimesTen database.

    • External users are defined by an external authority such as the operating system. External users cannot be assigned a TimesTen password.

  • Passwords are case-sensitive.

  • When a user is created, the user has the privileges granted to PUBLIC and no additional privileges.

  • You cannot create a user across a client/server connection. You must use a direct connection when creating a user.

  • In TimesTen, user brad is the same as user "brad". In both cases, the name of the user is created as BRAD.

  • User names are TT_CHAR data type.

  • When replication is configured, this statement is replicated.

Examples

To create the internal user terry with the password "secret", use:

CREATE USER terry IDENTIFIED BY "secret";
User created.

Verify that user terry has been created:

Command> SELECT * FROM sys.all_users WHERE username='TERRY';
< TERRY, 11, 2009-05-12 10:28:04.610353 >
1 row found.

To identify the external user pat to the TimesTen database, use:

CREATE USER pat IDENTIFIED EXTERNALLY;
User created.

See also


ALTER USER
DROP USER
GRANT
REVOKE

CREATE VIEW

The CREATE VIEW statement creates a view of the tables specified in the SelectQuery clause. A view is a logical table that is based on one or more detail tables. The view itself contains no data. It is sometimes called a nonmaterialized view to distinguish it from a materialized view, which does contain data that has already been calculated from detail tables.

Required privilege

The user executing the statement must have the CREATE VIEW privilege (if owner) or CREATE ANY VIEW (if not the owner) for another user's view.

The owner of the view must have the SELECT privilege on the detail tables.

SQL syntax

CREATE VIEW [Owner.]ViewName AS SelectQuery

Parameters

ParameterDescription
[Owner.]ViewNameName assigned to the new view.
SelectQuerySelects column from the detail tables to be used in the view. Can also create indexes on the view.

Restrictions on the SELECT query

There are several restrictions on the query that is used to define the view.

  • A SELECT * query in a view definition is expanded when the view is created. Any columns added after a view is created do not affect the view.

  • The following cannot be used in a SELECT statement that is used to create a view:

    • FIRST

    • ORDER BY, if used, is ignored by the CREATE VIEW statement. The result will not be sorted.

    • Arguments

  • Each expression in the select list must have a unique name. A name of a simple column expression would be that column's name unless a column alias is defined. ROWID is considered an expression and needs an alias.

  • No SELECT FOR UPDATE or SELECT FOR INSERT statements can be used to create a view.

  • Certain TimesTen query restrictions are not checked when a non-materialized view is created. Views that violate those restrictions may be allowed to be created, but an error is returned when the view is referenced later in an executed statement.

  • When a view is referenced in the FROM clause of a SELECT statement, its name is replaced by its definition as a derived table at parsing time. If it is not possible to merge all clauses of a view to the same clause in the original select query to form a legal query without the derived table, the content of this derived table is materialized. For example, if both the view and the referencing select specify aggregates, the view is materialized before its result can be joined with other tables of the select.

  • Use the DROP [MATERIALIZED] VIEW statement to drop a view.

  • A view cannot be altered with an ALTER TABLE statement.

  • Referencing a view can fail because of dropped or altered detail tables.

Examples

Create a nonmaterialized view from the employees table.

Command> CREATE VIEW v1 AS SELECT employee_id, email FROM employees;
Command> SELECT FIRST 5 * FROM v1;
< 100, SKING >
< 101, NKOCHHAR >
< 102, LDEHAAN >
< 103, AHUNOLD >
< 104, BERNST >
5 rows found.

Create a nonmaterialized view tview with column max1 from an aggregate query on the table t1.

CREATE VIEW tview (max1) AS SELECT MAX(x1) FROM t1;

See also


CREATE MATERIALIZED VIEW
CREATE TABLE
DROP [MATERIALIZED] VIEW

DELETE

The DELETE statement deletes rows from a table.

Required privilege

No privilege is required for the table owner.

DELETE on the table for another user's table.

SQL syntax

DELETE [FIRST NumRows] FROM [Owner.]TableName [CorrelationName] 
[WHERE SearchCondition]
[RETURNING|RETURN Expression[,...]INTO DataItem[,...]]

Parameters

ParameterDescription
FIRST NumRowsSpecifies the number of rows to delete. FIRST NumRows is not supported in subquery statements. NumRows must be either a positive INTEGER or a dynamic parameter placeholder. The syntax for a dynamic parameter placeholder is either ? or :DynamicParameter. The value of the dynamic parameter is supplied when the statement is executed.
[Owner.]TableName [CorrelationName]Designates a table from which any rows satisfying the search condition are to be deleted.

[Owner.]TableName identifies a table to be deleted.

CorrelationName specifies an alias for the immediately preceding table. Use the correlation name to reference the table elsewhere in the DELETE statement. The scope of the CorrelationName is the SQL statement in which it is used. It must conform to the syntax rules for a basic name. See "Basic names".

SearchConditionSpecifies which rows are to be deleted. If no rows satisfy the search condition, the table is not changed. If the WHERE clause is omitted, all rows are deleted. The search condition can contain a subquery.
ExpressionValid expression syntax. See Chapter 3, "Expressions".
DataItemHost variable or PL/SQL variable that stores the retrieved Expression value.

Description

  • If all the rows of a table are deleted, the table is empty but continues to exist until you issue a DROP TABLE statement.

  • The DELETE operation fails if it violates any foreign key constraint. See "CREATE TABLE" for a description of the foreign key constraint.

  • The total number of rows reported by the DELETE statement does not include rows deleted from child tables as a result of the ON DELETE CASCADE action.

  • If ON DELETE CASCADE is specified on a foreign key constraint for a child table, a user can delete rows from a parent table for which the user has the DELETE privilege without requiring explicit DELETE privilege on the child table.

  • Restrictions on the RETURNING clause:

    • Each Expression must be a simple expression. Aggregate functions are not supported.

    • You cannot return a sequence number into an OUT parameter.

    • ROWNUM and subqueries cannot be used in the RETURNING clause.

    • Parameters in the RETURNING clause cannot be duplicated anywhere in the DELETE statement.

    • Using the RETURNING clause to return multiple rows requires PL/SQL BULK COLLECT functionality. See Oracle TimesTen In-Memory Database PL/SQL Developer's Guide.

    • In PL/SQL, you cannot use a RETURNING clause with a WHERE CURRENT operation.

Examples

Rows for orders whose quantity is less than 50 are deleted.

DELETE FROM purchasing.orderitems
WHERE quantity < 50;

The following query deletes all the duplicate orders assuming that id is not a primary key:

DELETE FROM orders a
WHERE EXISTS (SELECT 1 FROM orders b
WHERE a.id = b.id and a.rowid < b.rowid);

The following sequence of statements causes a foreign key violation.

CREATE TABLE master (name CHAR(30), id CHAR(4) NOT NULL PRIMARY KEY);
CREATE TABLE details
  (masterid CHAR(4),description VARCHAR(200), 
   FOREIGN KEY (masterid) REFERENCES master(id));
INSERT INTO master('Elephant', '0001');
INSERT INTO details('0001', 'A VERY BIG ANIMAL');
DELETE FROM master WHERE id = '0001';

If you attempt to delete a "busy" table, an error results. In this example, t1 is a "busy" table that is a parent table with foreign key constraints based on it.

CREATE TABLE t1 (a INT NOT NULL, b INT NOT NULL,
       PRIMARY KEY (a));
CREATE TABLE t2 (c INT NOT NULL, 
       FOREIGN KEY (c) REFERENCES t1(a));
INSERT INTO t1 VALUES (1,1);
INSERT INTO t2 VALUES (1);
DELETE FROM t1;

An error is returned:

SQL ERROR (3001):  Foreign key violation [TTFOREIGN_0] a row in child table T2 
has a parent in the delete range.

Delete an employee from employees. Declare empid and name as variables with the same data types as employee_id and last_name. Delete the row, returning employee_id and last_name into the variables. Verify that the correct row was deleted.

Command> VARIABLE empid NUMBER(6) NOT NULL;
Command> VARIABLE name VARCHAR2(25) INLINE NOT NULL;
Command> DELETE FROM employees WHERE last_name='Ernst'
       > RETURNING employee_id, last_name INTO :empid,:name;
1 row deleted.
Command> PRINT empid name;
EMPID                : 104
NAME                 : Ernst

DROP ACTIVE STANDBY PAIR

This statement drops an active standby pair replication scheme.

Required privilege

ADMIN

SQL syntax

DROP ACTIVE STANDBY PAIR

Parameters

DROP ACTIVE STANDBY PAIR has no parameters.

Description

The active standby pair is dropped, but all objects such as tables, cache groups, and materialized views still exist on the database on which the statement was issued.

You cannot execute the DROP ACTIVE STANDBY PAIR statement when Oracle Clusterware is used with TimesTen.

See also


ALTER ACTIVE STANDBY PAIR
CREATE ACTIVE STANDBY PAIR

DROP CACHE GROUP

The DROP CACHE GROUP statement drops the table associated with the cache group, and removes the cache group definition from the CACHE_GROUP system table.

Required privilege

No privilege is required for the cache group owner or DROP ANY CACHE GROUP if not the cache group owner and

DROP ANY TABLE if at least one table in the cache group is not owned by the current user.

SQL syntax

DROP CACHE GROUP [Owner.]GroupName

Parameters

ParameterDescription
[Owner.]GroupNameName of the cache group to be deleted.

Description

  • If you attempt to delete a cache group table that is in use, TimesTen returns an error.

  • Asynchronous writethrough cache groups cannot be dropped while the replication agent is running.

  • Automatically installed Oracle objects for read-only cache groups and cache groups with the AUTOREFRESH attribute are uninstalled by the cache agent. If the cache agent is not running during the DROP CACHE GROUP operation, the Oracle objects are uninstalled on the next startup of the cache agent.

  • You cannot execute the DROP CACHE GROUP statement when performed under the serializable isolation level. An error message is returned when attempted.

  • If you issue a DROP CACHE GROUP statement, and there is an autorefresh operation currently running, then:

    • If LockWait interval is 0, the DROP CACHE GROUP statement fails with a lock timeout error.

    • If LockWait interval is non-zero, then the current autorefresh transaction is preempted (rolled back), and the DROP statement continues. This affects all cache groups with the same autorefresh interval.

Examples

DROP CACHE GROUP westerncustomers;

See also


ALTER CACHE GROUP
CREATE CACHE GROUP

DROP FUNCTION

The DROP FUNCTION statement removes a standalone stored function from the database. Do not use this statement to remove a function that is part of a package.

Required privilege

No privilege is required for the function owner.

DROP ANY PROCEDURE for another user's function.

SQL syntax

DROP FUNCTION [Owner.]FunctionName

Parameters

ParameterDescription
[Owner.]FunctionNameName of the function to be dropped.

Description

  • When you drop a function, TimesTen invalidates objects that depend on the dropped function. If you subsequently reference one of these objects, TimesTen attempts to recompile the object and returns an error message if you have not re-created the dropped function.

  • Do not use this statement to remove a function that is part of a package. Either drop the package or redefine the package without the function using the CREATE PACKAGE statement with the OR REPLACE clause

  • To use the DROP FUNCTION statement, you must have PL/SQL enabled in your database. If you do not have PL/SQL enabled in your database, an error is thrown.

Examples

The following statement drops the function myfunc and invalidates all objects that depend on myfunc:

Command> DROP FUNCTION myfunc;
 
Function dropped.

If PL/SQL is not enabled in your database, TimesTen returns an error:

Command> DROP FUNCTION myfunc;
 8501: PL/SQL feature not installed in this TimesTen database
The command failed.

See also

CREATE FUNCTION


DROP INDEX

The DROP INDEX statement removes the specified index.

Required privilege

No privilege is required for the index owner.

DROP ANY INDEX for another user's index.

SQL syntax

DROP INDEX [Owner.]IndexName [FROM [Owner.]TableName]

Parameters

ParameterDescription
[Owner.]IndexNameName of the index to be dropped. It may include the name of the owner of the table that has the index.
[Owner.]TableNameName of the table upon which the index was created.

Description

  • If you attempt to drop a "busy" index—an index that is in use or that enforces a foreign key—an error results. To drop a foreign key and the index associated with it, use the ALTER TABLE statement.

  • If an index is created through a UNIQUE column constraint, it can only be dropped by dropping the constraint with an ALTER TABLE DROP UNIQUE statement. See "CREATE TABLE" for more information about the UNIQUE column constraint.

  • If a DROP INDEX operation is or was active in an uncommitted transaction, other transactions doing DML operations that do not access that index are blocked.

  • If an index is dropped, any prepared statement that uses the index is prepared again automatically the next time the statement is executed.

  • If no table name is specified, the index name must be unique for the specified or implicit owner. The implicit owner, in the absence of a specified table or owner, is the current user running the program.

  • If no index owner is specified and a table is specified, the default owner is the table owner.

  • If a table is specified and no owner is specified for it, the default table owner is the current user running the program.

  • The table and index owners must be the same.

  • An index on a temporary table cannot be dropped by a connection if some other connection has an instance of the table that is not empty.

  • If the index is replicated across an active standby pair and if DDL_REPLICATION_LEVEL is 2, use the DROP INDEX statement to drop the index from the standby pair in the replication scheme. See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

Examples

Drop index partsorderedindex which is defined on table orderitems using one of the following:

DROP INDEX partsorderedindex
   FROM purchasing.orderitems;

or

DROP INDEX purchasing.partsorderedindex;

See also

CREATE INDEX


DROP [MATERIALIZED] VIEW

The DROP [MATERIALIZED] VIEW statement removes the specified view, including any hash indexes and any range indexes associated with it.

Required privilege

  • View owner or DROP ANY [MATERIALIZED] VIEW (if not owner) and

  • Table owner or DROP ANY TABLE (if not owner) and

  • Index owner or DROP ANY INDEX (if not owner) if there is an index on the view.

SQL syntax

DROP [MATERIALIZED] VIEW [Owner.]ViewName

Parameters

ParameterDescription
MATERIALIZEDSpecifies that the view is materialized.
[Owner.]ViewNameIdentifies the view to be dropped.

Description

When you perform a DROP VIEW operation on a materialized view, the detail tables are updated and locked. An error may result if the detail table was already locked by another transaction.

Examples

The following statement drops the custorder view.

DROP VIEW custorder;

See also


CREATE MATERIALIZED VIEW
CREATE VIEW

DROP MATERIALIZED VIEW LOG

The DROP MATERIALIZED VIEW LOG statement removes the materialized view log for a detail table. It also drops the global temporary table that was created by the CREATE MATERIALIZED VIEW LOG statement.

Required privilege

No privilege is required for the table owner.

DROP ANY TABLE for another user's table.

SQL syntax

DROP MATERIALIZED VIEW LOG ON [Owner.]TableName

Parameters

ParameterDescription
[Owner.]TableNameName of the detail table for which the materialized view log was created.

Description

This statement drops the materialized view log for the specified detail table. The materialized view log cannot be dropped if there is an asynchronous materialized view that depends on the log for refreshing.

Examples

DROP MATERIALIZED VIEW LOG ON employees;

See also


CREATE MATERIALIZED VIEW LOG
CREATE MATERIALIZED VIEW
DROP [MATERIALIZED] VIEW

DROP PACKAGE [BODY]

The DROP PACKAGE statement removes a stored package from the database. Both the specification and the body are dropped. DROP PACKAGE BODY removes only the body of the package.

Required privilege

No privilege is required for the package owner.

DROP ANY PROCEDURE for another user's package.

SQL syntax

DROP PACKAGE [BODY] [Owner.]PackageName

Parameters

ParameterDescription
PACKAGE [BODY]Specify BODY to drop only the body of the package. Omit BODY to drop both the specification and body of the package.
[Owner.]PackageNameName of the package to be dropped.

Description

  • When you drop only the body of the package, TimesTen does not invalidate dependent objects. However, you cannot execute one of the procedures or stored functions declared in the package specification until you re-create the package body.

  • TimesTen invalidates any objects that depend on the package specification. If you subsequently reference one of these objects, then TimesTen tries to recompile the object and returns an error if you have not re-created the dropped package.

  • Do not use this statement to remove a single object from the package. Instead, re-create the package without the object using the CREATE PACKAGE and CREATE PACKAGE BODY statements with the OR REPLACE clause.

  • To use the DROP PACKAGE [BODY] statement, you must have PL/SQL enabled in your database. If you do not have PL/SQL enabled in your database, TimesTen returns an error.

Example

The following statement drops the body of package samplePackage:

Command> DROP PACKAGE BODY SamplePackage;
Package body dropped.

To drop both the specification and body of package samplepackage:

Command> DROP PACKAGE samplepackage;
Package dropped.

See also

CREATE PACKAGE


DROP PROCEDURE

The DROP PROCEDURE statement removes a standalone stored procedure from the database. Do not use this statement to remove a procedure that is part of a package.

Required privilege

No privilege is required for the procedure owner.

DROP ANY PROCEDURE for another user's procedure.

SQL syntax

DROP PROCEDURE [Owner.]ProcedureName

Parameters

ParameterDescription
[Owner.]ProcedureNameName of the procedure to be dropped.

Description

  • When you drop a procedure, TimesTen invalidates objects that depend on the dropped procedure. If you subsequently reference one of these objects, TimesTen attempts to recompile the object and returns an error message if you have not re-created the dropped procedure.

  • Do not use this statement to remove a procedure that is part of a package. Either drop the package or redefine the package without the procedure using the CREATE PACKAGE statement with the OR REPLACE clause.

  • To use the DROP PROCEDURE statement, you must have PL/SQL enabled in your database. If you do not have PL/SQL enabled in your database, an error is thrown.

Examples

The following statement drops the procedure myproc and invalidates all objects that depend on myproc:

Command> DROP PROCEDURE myproc;
Procedure dropped.

If PL/SQL is not enabled in your database, TimesTen returns an error:

Command> DROP PROCEDURE myproc;
 
 8501: PL/SQL feature not installed in this TimesTen databaseThe command failed.

See also

CREATE PROCEDURE


DROP REPLICATION

The DROP REPLICATION statement destroys a replication scheme and removes it from the executing database.

Required privilege

ADMIN

SQL syntax

DROP REPLICATION [Owner.]ReplicationSchemeName

Parameters

ParameterDescription
[Owner.]ReplicationSchemeNameName assigned to the replication scheme.

Description

Dropping the last replication scheme at a database does not delete the replicated tables. These tables exist and persist at a database whether or not any replication schemes are defined.

Examples

The following statement erases the executing database's knowledge of replication scheme, r:

DROP REPLICATION r;

See also


ALTER REPLICATION
CREATE REPLICATION

DROP SEQUENCE

The DROP SEQUENCE statement removes an existing sequence number generator.

Required privilege

No privilege is required for the sequence owner.

DROP ANY SEQUENCE for another user's sequence.

SQL syntax

DROP SEQUENCE [Owner.]SequenceName

Parameters

ParameterDescription
[Owner.]SequenceNameName of the sequence number generator

Description

  • Sequences can be dropped while they are in use.

  • There is no ALTER SEQUENCE statement in TimesTen. To alter a sequence, use the DROP SEQUENCE statement and then create a new sequence with the same name. For example, to change the MINVALUE, drop the sequence and re-create it with the same name and with the desired MINVALUE.

  • If the sequence is part of a replication scheme, use the ALTER REPLICATION statement to drop the sequence from the replication scheme. Then use the DROP SEQUENCE statement to drop the sequence.

Examples

The following statement drops mysequence:

DROP SEQUENCE mysequence;

See also

CREATE SEQUENCE


DROP SYNONYM

The DROP SYNONYM statement removes a synonym from the database.

If the synonym is replicated across an active standby pair and if DDL_REPLICATION_LEVEL is 2, use the DROP SYNONYM statement to drop the synonym from the active standby pair in the replication scheme. See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

Required privilege

No privilege is required to drop the private synonym by its owner. The DROP ANY SYNONYM privilege is required to drop another user's private synonym.

The DROP PUBLIC SYNONYM privilege is required to drop a PUBLIC synonym.

SQL syntax

To drop a private synonym, use the following syntax:

DROP SYNONYM [Owner.]SynonymName

To drop a public synonym:

DROP PUBLIC SYNONYM SynonymName

Parameters

ParameterDescription
PUBLICSpecify PUBLIC to drop a public synonym.
[Owner.]Optionally, specify the owner for a private synonym. If you omit the owner, the private synonym must exist in the current user's schema.
SynonymNameSpecify the name of the synonym to be dropped.

Examples

Drop the public synonym pubemp:

DROP PUBLIC SYNONYM pubemp;
Synonym dropped.

Drop the private synjobs synonym:

DROP SYNONYM synjobs;
Synonym dropped.

As user terry with DROP ANY SYNONYM privilege, drop the private syntab synonym owned by ttuser.

DROP SYNONYM ttuser.syntab;
Synonym dropped.

See also

CREATE SYNONYM


DROP TABLE

The DROP TABLE statement removes the specified table, including any hash indexes and any range indexes associated with it.

Required privilege

No privilege is required for the table owner.

DROP ANY TABLE for another user's table.

SQL syntax

DROP TABLE [Owner.]TableName

Parameters

ParameterDescription
[Owner.]TableNameIdentifies the table to be dropped.

Description

  • If you attempt to drop a table that is in use, an error results.

  • If a DROP TABLE operation is or was active in an uncommitted transaction, other transactions doing DML operations that do not access that table are allowed to proceed.

  • If the table is a replicated table, you can do one of the following:

    • Use the DROP REPLICATION statement to drop the replication scheme before issuing the DROP TABLE statement.

    • If DDL_REPLICATION_LEVEL is 2, use the DROP TABLE statement to drop the table from the active standby pair in the replication scheme.

      If DDL_REPLICATION_LEVEL is 1, stop the replication agent and use the ALTER ACTIVE STANDBY PAIR EXCLUDE TABLE statement to exclude the table from the replication scheme. Then use the DROP TABLE statement to drop the table.

      See "Making DDL changes in an active standby pair" in the Oracle TimesTen In-Memory Database Replication Guide for more information.

  • A temporary table cannot be dropped by a connection if some other connection has some non-empty instance of the table.

Examples

CREATE TABLE vendorperf
   (ordernumber INTEGER,
    delivday TT_SMALLINT,
    delivmonth TT_SMALLINT,
    delivyear TT_SMALLINT,
    delivqty TT_SMALLINT,
    remarks VARCHAR2(60));
CREATE UNIQUE INDEX vendorperfindex ON vendorperf (ordernumber);

The following statement drops the table and index.

DROP TABLE vendorperf ;

DROP USER

The DROP USER statement removes a user from the database.

Required privilege

ADMIN

SQL syntax

DROP USER user

Parameters

ParameterDescription
userName of the user that is being dropped from the database.

Description

Before you can drop a user:

  • The user must exist either internally or externally in the database.

  • You must drop objects that the user owns.

  • When replication is configured, this statement is replicated.

Examples

Drop user terry from the database:

DROP USER terry;
User dropped.

See also


CREATE USER
ALTER USER
GRANT
REVOKE

FLUSH CACHE GROUP

The FLUSH CACHE GROUP statement flushes data from TimesTen cache tables to Oracle tables. This statement is available only for user managed cache groups. For a description of cache group types, see "User managed and system managed cache groups".

There are two variants to this operation: one that accepts a WHERE clause, and one that accepts a WITH ID clause.

FLUSH CACHE GROUP is meant to be used when commit propagation (from TimesTen to Oracle) is turned off. Instead of propagating every transaction upon commit, many transactions can be committed before changes are propagated to Oracle. For each cache instance ID, if the cache instance exists in the Oracle database, the operation in the Oracle database consists of an update. If the cache instance does not exist in the Oracle database, TimesTen inserts it.

This is useful, for example, in a shopping cart application in which many changes may be made to the cart, which uses TimesTen as a high-speed cache, before the order is committed to the master Oracle table.


Note:

Using a WITH ID clause usually results in better system performance than using a WHERE clause.

Only inserts and updates are flushed. Inserts are propagated as inserts if the record does not exist in the Oracle table or as updates (if the record already exists). It is not possible to flush a delete. That is, if a record is deleted on TimesTen, there is no way to "flush" that delete to the Oracle table. Deletes must be propagated either manually or by turning commit propagation on. Attempts to flush deleted records are silently ignored. No error or warning is issued. Records from tables that are specified as READ ONLY or PROPAGATE cannot be flushed to Oracle tables.

Required privileges

No privilege is required for the cache group owner.

FLUSH or FLUSH ANY CACHE GROUP for another user's cache group.

SQL syntax

FLUSH CACHE GROUP [Owner.]GroupName
[WHERE ConditionalExpression];

or

FLUSH CACHE GROUP [Owner.]GroupName
WITH ID (ColumnValueList)

Parameters

ParameterDescription
[Owner.]GroupNameName of the cache group to be flushed.
ConditionalExpressionA search condition to qualify the target rows of the operation. When using more than one table with columns with the same name, the table names in subqueries in the WHERE clause of the FLUSH CACHE GROUP statement must be fully qualified.
WITH ID ColumnValueListThe WITH ID clauses enables you to use primary key values to flush the cache instance. Specify ColumnValueList as either a list of literals or binding parameters to represent the primary key values.

Description

  • WHERE clauses are generally used to apply the operation to a set of instances, rather than to a single instance or to all instances. The flush operation uses the WHERE clause to determine which instances to send to the Oracle database.

  • Generally, you do not have to fully qualify the column names in the WHERE clause of the FLUSH CACHE GROUP statement. However, since TimesTen automatically generates queries that join multiple tables in the same cache group, a column needs to be fully qualified if there is more than one table in the cache group that contains columns with the same name. Without an owner name, all tables referenced by cache group WHERE clauses are owned by the current login name executing the cache group operation.

  • When the WHERE clause is omitted, the entire contents of the cache group is flushed to Oracle tables. When the WHERE clause is included, it is allowed to include only the root table.

  • Following the execution of a FLUSH CACHE GROUP statement, the ODBC function SQLRowCount(), the JDBC method getUpdateCount(), and the OCI function OCIAttrGet() with the OCI_ATTR_ROW_COUNT argument return the number of cache instances that were flushed.

  • Use the WITH ID clause to specify binding parameters

Restrictions

  • Do not use the WITH ID clause on AWT or SWT cache groups, user managed cache groups with the propagate attribute, or autorefreshed and propagated user managed cache groups unless the cache group is a dynamic cache group.

  • Do not use the WITH ID clause with the COMMIT EVERY n ROWS clause.

Examples

FLUSH CACHE GROUP marketbasket;

FLUSH CACHE GROUP marketbasket
WITH ID(10);

See also


CREATE CACHE GROUP

GRANT

The GRANT statement assigns one or more privileges to a user.

Required privilege

ADMIN to grant system privileges.

ADMIN or the object owner to grant object privileges.

SQL syntax

GRANT {SystemPrivilege [,...] | ALL [PRIVILEGES]} [...] TO {user |PUBLIC} [,...]

GRANT {{ObjectPrivilege [,...] | ALL [PRIVILEGES]} ON {[owner.]object}[,...]} TO
{user | PUBLIC} [,...]

Parameters

The following parameters are for granting system privileges:

ParameterDescription
SystemPrivilegeSee "System privileges" for a list of acceptable values.
ALL [PRIVILEGES]Assigns all system privileges to the user.
userName of the user to whom privileges are being granted. The user name must first have been introduced to the TimesTen database by a CREATE USER statement.
PUBLICSpecifies that the privilege is granted to all users.

The following parameters are for granting object privileges:

ParameterDescription
ObjectPrivilegeSee "Object privileges" for a list of acceptable values.
ALL [PRIVILEGES]Assigns all object privileges to the user.
[owner.]objectobject is the name of the object on which privileges are being granted. owner is the owner of the object. If owner is not specified, the user who is granting the privilege is the owner.
userName of the user to whom privileges are being granted. The user must exist in the database.
PUBLICSpecifies that the privilege is granted to all users.

Description

  • One or more system privileges can be granted to a user by a user with ADMIN privilege.

  • One or more object privileges can be granted to a user by the owner of the object.

  • One or more object privileges can be granted to a user on any object by a user with ADMIN privilege.

  • To remove a privilege from a user, use the REVOKE statement.

  • You cannot grant system privileges and object privileges in the same statement.

  • Only one object can be specified in an object privilege statement.

  • When replication is configured, this statement is replicated.

Examples

Grant the ADMIN privilege to the user terry:

GRANT admin TO terry;

Assuming the grantor has ADMIN privilege, grant the SELECT privilege to user terry on the customers table owned by user pat:

GRANT SELECT ON pat.customers TO terry;

Grant an object privilege to user terry:

GRANT SELECT ON emp_details_view TO terry;

See also


CREATE USER
ALTER USER
DROP USER
REVOKE
The PUBLIC role

INSERT

The INSERT statement adds rows to a table.

The following expressions can be used in the VALUES clause of an INSERT statement:

Required privilege

No privilege is required for the table owner.

INSERT for another user's table.

SQL syntax

INSERT INTO [Owner.]TableName [(Column [,...])]
VALUES (SingleRowValues)
[RETURNING|RETURN Expression[,...] INTO DataItem[,...]]

The SingleRowValues parameter has the syntax:

{NULL|{?|:DynamicParameter}|{Constant}| DEFAULT}[,...]

Parameters

ParameterDescription
OwnerThe owner of the table into which data is inserted.
TableNameName of the table into which data is inserted.
ColumnEach column in this list is assigned a value from SingleRowValues.

If you omit one or more of the table's columns from this list, then the value of the omitted column in the inserted row is the column default value as specified when the table was created or last altered. If any omitted column has a NOT NULL constraint and has no default value, then the database returns an error.

If you omit a list of columns completely, then you must specify values for all columns in the table.

?

:DynamicParameter

Placeholder for a dynamic parameter in a prepared SQL statement. The value of the dynamic parameter is supplied when the statement is executed.
ConstantA specific value. See "Constants".
DEFAULTSpecifies that the column should be updated with the default value.
ExpressionValid expression syntax. See Chapter 3, "Expressions".
DataItemHost variable or PL/SQL variable that stores the retrieved Expression value.

Description

  • If you omit any of the table's columns from the column name list, the INSERT statement places the default value in the omitted columns. If the table definition specifies NOT NULL for any of the omitted columns and there is no default value, the INSERT statement fails.

  • BINARY and VARBINARY data can be inserted in character or hexadecimal format:

    • Character format requires single quotes.

    • Hexadecimal format requires the prefix 0x before the value.

  • The INSERT operation fails if it violates a foreign key constraint. See "CREATE TABLE" for a description of the foreign key constraint.

  • Restrictions on the RETURNING clause:

    • Each Expression must be a simple expression. Aggregate functions are not supported.

    • You cannot return a sequence number into an OUT parameter.

    • ROWNUM and subqueries cannot be used in the RETURNING clause.

    • Parameters in the RETURNING clause cannot be duplicated anywhere in the INSERT statement.

    • In PL/SQL, you cannot use a RETURNING clause with a WHERE CURRENT operation.

Examples

A new single row is added to the purchasing.vendors table.

INSERT INTO purchasing.vendors
VALUES (9016,
       'Secure Systems, Inc.',
       'Jane Secret',
       '454-255-2087',
       '1111 Encryption Way',
       'Hush',
       'MD',
       '00007',
       'discount rates are secret');

:pno and :pname are dynamic parameters whose values are supplied at runtime.

INSERT INTO purchasing.parts (partnumber, partname)
  VALUES (:pno, :pname);

Return the annual salary and job_id of a new employee. Declare the variables sal and jobid with the same data types as salary and job_id. Insert the row into employees. Print the variables for verification.

Command> VARIABLE sal12 NUMBER(8,2);
Command> VARIABLE jobid VARCHAR2(10) INLINE NOT NULL;

Command> INSERT INTO employees(employee_id, last_name, email, hire_date, 
       > job_id, salary)
       > VALUES (211,'Doe','JDOE',sysdate,'ST_CLERK',2400)
       > RETURNING salary*12, job_id INTO :sal12,:jobid;
1 row inserted.

PRINT sal12 jobid;
SAL12                 : 28800
JOBID                 : ST_CLERK

See also


CREATE TABLE
INSERT...SELECT
Chapter 3, "Expressions"

INSERT...SELECT

The INSERT...SELECT statement inserts the results of a query into a table.

Required privilege

No privilege is required for the object owner.

INSERT and SELECT for another user's object.

SQL syntax

INSERT INTO [Owner.]TableName [(ColumnName [,...])] InsertQuery

Parameters

ParameterDescription
[Owner.]TableNameTable to which data is to be added.
ColumnNameColumn for which values are supplied. If you omit any of the table's columns from the column name list, the INSERT...SELECT statement places the default value in the omitted columns. If the table definition specifies NOT NULL, without a default value, for any of the omitted columns, the INSERT...SELECT statement fails. You can omit the column name list if you provide values for all columns of the table in the same order the columns were specified in the CREATE TABLE statement. If too few values are provided, the remaining columns are assigned default values.
InsertQueryAny supported SELECT query. See "SELECT".

Description

  • The column types of the result set must be compatible with the column types of the target table.

  • You can specify a sequence CURRVAL or NEXTVAL when inserting values. See "Incrementing SEQUENCE values with CURRVAL and NEXTVAL" for more details.

  • In the InsertQuery, the ORDER BY clause is allowed. The sort order may be modified using the ORDER BY clause when the result set is inserted into the target table, but the order is not guaranteed.

  • The INSERT operation fails if there is an error in the InsertQuery.

  • A RETURNING clause cannot be used in an INSERT...SELECT statement.

Examples

New rows are added to the purchasing.parts table that describe which parts are delivered in 20 days or less.

INSERT INTO purchasing.parts
SELECT partnumber, deliverydays
FROM purchasing.supplyprice
WHERE deliverydays < 20;

LOAD CACHE GROUP

The LOAD CACHE GROUP statement loads data from an Oracle table into a TimesTen cache group. The load operation is local. It is not propagated across cache grid members.

Required privilege

No privilege is required for the cache group owner.

LOAD CACHE GROUP or LOAD ANY CACHE GROUP for another user's cache group.

SQL syntax

LOAD CACHE GROUP [Owner.]GroupName 
[WHERE ConditionalExpression] 
COMMIT EVERY n ROWS
[PARALLEL NumThreads]

or

LOAD CACHE GROUP [Owner.]GroupName
WITH ID (ColumnValueList)

Parameters

ParameterDescription
[Owner.]GroupNameName assigned to the cache group.
ConditionalExpressionA search condition to qualify the target rows of the operation. When using more than one table with columns with the same name, the table names in subqueries in the WHERE clause of the LOAD CACHE GROUP statement must be fully qualified.
nThe number of rows to insert into the cache group before committing the work. It must be a nonnegative integer. If it is 0, the entire statement is executed as one transaction.
[PARALLEL NumThreads]Provides parallel loading for cache group tables. Specifies the number of loading threads to run concurrently. One thread performs the bulk fetch from Oracle and the other threads (NumThreads - 1 threads) perform the inserts into TimesTen. Each thread uses its own connection or transaction.

The minimum value for NumThreads is 2. The maximum value is 10. If you specify a value greater than 10, TimesTen assigns the value 10.

WITH ID ColumnValueListThe WITH ID clauses enables you to use primary key values to load the cache instance. Specify ColumnValueList as either a list of literals or binding parameters to represent the primary key values.

Description

  • LOAD CACHE GROUP loads all new instances from Oracle that satisfy the cache group definition and are not yet present in the cache group.

  • Before issuing the LOAD CACHE GROUP statement, ensure that the replication agent is running if the cache group is replicated or is an AWT cache group.

  • LOAD CACHE GROUP is executed in its own transaction, and must be the first operation in a transaction.

  • For an explicitly loaded cache group, LOAD CACHE GROUP does not update cache instances that are already present in the TimesTen cache tables. Therefore, LOAD CACHE GROUP loads only inserts on Oracle tables into the corresponding TimesTen cache tables.

  • For a dynamic cache group, LOAD CACHE GROUP loads rows that have been inserted, updated and deleted on Oracle tables into the cache tables. For more information about explicitly loaded and dynamic cache groups, see Oracle In-Memory Database Cache User's Guide.

  • The transaction size is the number of rows inserted before committing the work. The value of n in COMMIT EVERY n ROWS must be nonnegative and is rounded up to the nearest multiple of 256 for performance reasons.

  • Errors cause a rollback. When rows are committed periodically, errors abort the remainder of the load. The load is rolled back to the last commit.

  • If the LOAD CACHE GROUP statement fails when you specify COMMIT EVERY n ROWS (where n is greater than 0), the content of the target cache group could be in an inconsistent state since some of the loaded rows are already committed. Some cache instances may be partially loaded. Use the UNLOAD statement to bring it back to a consistent state, then load again.

  • Generally, you do not have to fully qualify the column names in the WHERE clause of the LOAD CACHE GROUP statement. However, since TimesTen automatically generates queries that join multiple tables in the same cache group, a column needs to be fully qualified if there is more than one table in the cache group that contains columns with the same name.

  • When loading a read-only cache group:

    • The AUTOREFRESH state must be paused.

    • The LOAD CACHE GROUP statement cannot have a WHERE clause (except on a dynamic cache group).

    • The cache group must be empty.

  • If the automatic refresh state of a cache group (explicitly loaded or dynamic) is PAUSED, the state is changed to ON after a LOAD CACHE GROUP statement that was issued on the cache group completes.If the automatic refresh state of a dynamic cache group is PAUSED and the cache tables are populated, the state remains PAUSED after a LOAD CACHE GROUP statement that was issued on the cache group completes.

  • Following the execution of a LOAD CACHE GROUP statement, the ODBC function SQLRowCount(), the JDBC method getUpdateCount(), and the OCI function OCIAttrGet() with the OCI_ATTR_ROW_COUNT argument return the number of cache instances that were loaded.

  • Use the WITH ID clause as follows:

    • In place of the WHERE clause for faster loading of the cache instance

    • To specify binding parameters

    • If you want to roll back the load transaction upon failure

Restrictions

  • Do not reference child tables in the WHERE clause.

  • Do not specify the PARALLEL clause in the following circumstances:

    • With the WITH ID clause

    • With the COMMIT EVERY 0 ROWS clause

    • When database level locking is enabled (connection attribute LockLevel is set to 1)

  • Do not use the WITH ID clause when loading these types of cache groups:

    • Explicitly loaded read-only cache group

    • Explicitly loaded user managed cache group with the autorefresh attribute

    • User managed cache group with the AUTOREFRESH and PROPAGATE attributes

  • Do not use the WITH ID clause with the COMMIT EVERY n ROWS clause.

  • The WITH ID clause cannot be used to acquire a cache instance from another cache grid member.

Examples

CREATE CACHE GROUP recreation.cache
    FROM recreation.clubs (
        clubname CHAR(15) NOT NULL,
        clubphone SMALLINT,
        activity CHAR(18),
        PRIMARY KEY(clubname))
    WHERE (recreation.clubs.activity IS NOT NULL);

LOAD CACHE GROUP recreation.cache
    COMMIT EVERY 30 ROWS;

Use the HR schema to illustrate the use of the PARALLEL clause with the LOAD CACHE GROUP statement. The COMMIT EVERY n ROWS clause (where n is greater than 0) is required. Issue the CACHEGROUPS command. You see cache group cg2 is defined and the autorefresh state is paused. Unload cache group cg2, then specify the LOAD CACHE GROUP statement with the PARALLEL clause to provide parallel loading. You see 25 cache instances loaded.

Command> CACHEGROUPS;

Cache Group SAMPLEUSER.CG2:

  Cache Group Type: Read Only
  Autorefresh: Yes
  Autorefresh Mode: Incremental
  Autorefresh State: Paused
  Autorefresh Interval: 1.5 Minutes

  Root Table: SAMPLEUSER.COUNTRIES
  Table Type: Read Only

  Child Table: SAMPLEUSER.LOCATIONS
  Table Type: Read Only

  Child Table: SAMPLEUSER.DEPARTMENTS
  Table Type: Read Only

1 cache group found.

Command> UNLOAD CACHE GROUP cg2;
25 cache instances affected.
Command> COMMIT;
Command> LOAD CACHE GROUP cg2 COMMIT EVERY 10 ROWS PARALLEL 2;
25 cache instances affected.
Command> COMMIT;

The following example loads only the cache instances for customers whose customer number is greater than or equal to 5000 into the TimesTen cache tables in the new_customers cache group from the corresponding Oracle tables:

LOAD CACHE GROUP new_customers WHERE (oratt.customer.cust_num >= 5000) COMMIT
EVERY 256 ROWS;

See also


REFRESH CACHE GROUP
UNLOAD CACHE GROUP

MERGE

The MERGE statement enables you to select rows from one or more sources for update or insertion into a target table. You can specify conditions that are used to evaluate which rows are updated or inserted into the target table.

Use this statement to combine multiple INSERT and UPDATE statements.

MERGE is a deterministic statement: You cannot update the same row of the target table multiple times in the same MERGE statement.

Required privilege

No privilege is required for the owner of the target table and the source table.

INSERT or UPDATE on a target table owned by another user and SELECT on a source table owned by another user.

SQL syntax

MERGE INTO [Owner.]TargetTableName [Alias] USING
    {[Owner.]SourceTableName|(Subquery)}[Alias] ON (Condtion)
    {MergeUpdateClause MergeInsertClause |
     MergeInsertClause MergeUpdateClause |
     MergeUpdateClause | MergeInsertClause
    }

The syntax for MergeUpdateClause is as follows:

WHEN MATCHED THEN UPDATE SET SetClause [WHERE Condition1]

The syntax for MergeInsertClause is as follows:

WHEN NOT MATCHED THEN INSERT [Columns [,...]] VALUES
    ( {{Expression | DEFAULT|NULL} [,...] }) [WHERE Condition2]

Parameters

ParameterDescription
[Owner.]TargetTableNameName of the target table. This is the table in which rows are either updated or inserted.
[Alias]You can optionally specify an alias name for the target or source table.
USING {[Owner.]SourceTableName | (Subquery)} [Alias]The USING clause indicates the table name or the subquery that is used for the source of the data. Use a subquery if you want to use joins or aggregates. Optionally, you can specify an alias for the table name or the subquery.
ON (Condition)You specify the condition that is used to evaluate each row of the target table to determine if the row should be considered for either a merge insert or a merge update. If the condition is true when evaluated, then the MergeUpdateClause is considered for the target row using the matching row from the SourceTableName. An error is generated if more than one row in the source table matches the same row in the target table. If the condition is not true when evaluated, then the MergeInsertClause is considered for that row.
SET SetClauseClause used with the UPDATE statement. For information on the UPDATE statement, see "UPDATE".
[WHERE Condition1]For each row that matches the ON (Condition), Condition1 is evaluated. If the condition is true when evaluated, the row is updated. You can refer to either the target table or the source table in this clause. You cannot use a subquery. The clause is optional.
INSERT [Columns[,...]]VALUES ({{Expression |DEFAULT|NULL} [,...]})Columns to insert into the target table. For more information on the INSERT statement, see "INSERT".
[WHERE Condition2]If specified, Condition2 is evaluated. If the condition is true when evaluated, the row is inserted into the target table. The condition can refer to the source table only. You cannot use a subquery.

Description

  • You can specify the MergeUpdateClause and MergeInsertClause together or separately. If you specify both, they can be in either order.

  • If DUAL is the only table specified in the USING clause and it is not referenced elsewhere in the MERGE statement, specify DUAL as a simple table rather than using it in a subquery. In this simple case, to help performance, specify a key condition on a unique index of the target table in the ON clause.

  • Restrictions on the MergeUpdateClause:

    • You cannot update a column that is referenced in the ON condition clause.

    • You cannot update source table columns.

  • Restrictions on the MergeInsertClause:

    • You cannot insert values of target table columns.

  • Other restrictions:

    • Do not use the set operators in the subquery of the source table.

    • Do not use a subquery in the WHERE condition of either the MergeUpdateClause or the MergeInsertClause.

    • The target table cannot be a detail table of a materialized view.

    • The RETURNING clause cannot be used in a MERGE statement.

Examples

In this example, dual is specified as a simple table. There is a key condition on the UNIQUE index of the target table specified in the ON clause. The DuplicateBindMode attribute is set to 1 in this example. (The default is 0.)

Command> CREATE TABLE mergedualex (col1 TT_INTEGER NOT NULL, 
       > col2 TT_INTEGER, PRIMARY KEY (col1));
Command> MERGE INTO mergedualex USING dual ON (col1 = :v1)
       > WHEN MATCHED THEN UPDATE SET col2 = col2 + 1
       > WHEN NOT MATCHED THEN INSERT VALUES (:v1, 1);

Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.

Enter Parameter 1  'V1' (TT_INTEGER) > 10
1 row merged.
Command> SELECT * FROM mergedualex;
< 10, 1 >
1 row found.

In this example, a table called contacts is created with columns employee_id and manager_id. One row is inserted into the contacts table with values 101 and NULL for employee_id and manager_id, respectively. The MERGE statement is used to insert rows into the contacts table using the data in the employees table. A SELECT FIRST 3 rows is used to illustrate that in the case where employee_id is equal to 101, manager_id is updated to 100. The remaining 106 rows from the employees table are inserted into the contacts table:

Command> CREATE TABLE contacts (employee_id NUMBER (6) NOT NULL PRIMARY KEY, 
       > manager_id NUMBER (6));
Command> SELECT employee_id, manager_id FROM employees WHERE employee_id =101;
< 101, 100 >
1 row found.
Command> INSERT INTO contacts VALUES (101,null);
1 row inserted.
Command> SELECT COUNT (*) FROM employees;
< 107 >
1 row found.
Command> MERGE INTO contacts c
       >   USING employees e
       >   ON (c.employee_id = e.employee_id)
       > WHEN MATCHED THEN
       >   UPDATE SET c.manager_id = e.manager_id
       > WHEN NOT MATCHED THEN
       >   INSERT (employee_id, manager_id)
       >   VALUES (e.employee_id, e.manager_id);
107 rows merged.
Command> SELECT COUNT (*) FROM contacts;
< 107 >
1 row found.
Command> SELECT FIRST 3 employee_id,manager_id FROM employees;
< 100, <NULL> >
< 101, 100 >
< 102, 100 >
3 rows found.
Command> SELECT FIRST 3 employee_id, manager_id FROM contacts;
< 100, <NULL> >
< 101, 100 >
< 102, 100 >
3 rows found.

REFRESH CACHE GROUP

The REFRESH CACHE GROUP statement is equivalent to an UNLOAD CACHE GROUP statement followed by a LOAD CACHE GROUP statement.

Required privilege

  • CREATE SESSION on the Oracle schema and SELECT on the Oracle tables.

  • No privilege for the cache group is required for the cache group owner.

  • REFRESH CACHE GROUP or REFRESH ANY CACHE GROUP for another user's cache group.

SQL syntax

REFRESH CACHE GROUP [Owner.]GroupName 
[WHERE ConditionalExpression]
COMMIT EVERY n ROWS
[PARALLEL NumThreads]

or

REFRESH CACHE GROUP [Owner.]GroupName 
WITH ID (ColumnValueList)

Parameters

ParameterDescription
[Owner.]GroupNameName assigned to the cache group.
ConditionalExpressionA search condition to qualify the target rows of the operation. When using more than one table with columns with the same name, the table names in subqueries in the WHERE clause of the REFRESH CACHE GROUP statement must be fully qualified.
nThe number of rows to insert into the cache group before committing the work. The value must be a nonnegative integer. If the value is 0, the entire statement is executed as one transaction.
[PARALLEL NumThreads]Provides parallel loading for cache group tables. Specifies the number of loading threads to run concurrently. One thread performs the bulk fetch from Oracle and the other threads (NumThreads - 1 threads) perform the inserts into TimesTen. Each thread uses its own connection or transaction.

The minimum value for NumThreads is 2. The maximum value is 10. If you specify a value greater than 10, TimesTen assigns the value 10.

WITH ID ColumnValueListThe WITH ID clauses enables you to use primary key values to refresh the cache instance. Specify ColumnValueList as either a list of literals or binding parameters to represent the primary key values.

Description

  • A REFRESH CACHE GROUP statement must be executed in its own transaction.

  • Before issuing the REFRESH CACHE GROUP statement, ensure that the replication agent is running if the cache group is replicated or is an AWT cache group.

  • REFRESH CACHE GROUP replaces all or specified cache instances in the TimesTen cache tables with the most current data from the corresponding Oracle tables even if an instance is already present in the cache tables. For explicitly loaded cache groups, a refresh operation is equivalent to an UNLOAD CACHE GROUP statement followed by a LOAD CACHE GROUP statement. Operations on all rows in the Oracle tables including inserts, updates, and deletes are applied to the cache tables. For dynamic cache groups, a refresh operation refreshes only rows that are updated or deleted on Oracle tables into the cache tables. For more information on explicitly loaded and dynamic cache groups, see Oracle In-Memory Database Cache User's Guide.

  • When refreshing a read-only cache group:

    • The AUTOREFRESH statement must be paused

    • If the cache group is a read-only dynamic cache group, do not use the PARALLEL clause.

  • If the automatic refresh state of a cache group (dynamic or explicitly loaded) is PAUSED, the state is changed to ON after an unconditional REFRESH CACHE GROUP statement issued on the cache group completes.

  • If the automatic refresh state of a dynamic cache group is PAUSED, the state remains PAUSED after a REFRESH CACHE GROUP...WITH ID statement completes.

  • Generally, you do not have to fully qualify the column names in the WHERE clause of the REFRESH CACHE GROUP statement. However, since TimesTen automatically generates queries that join multiple tables in the same cache group, a column needs to be fully qualified if there is more than one table in the cache group that contains columns with the same name.

  • If the REFRESH CACHE GROUP statement fails when you specify COMMIT EVERY n ROWS (where n is greater than 0), the content of the target cache group could be in an inconsistent state since some of the loaded rows are already committed. Some cache instances may be partially loaded. Use the UNLOAD CACHE GROUP statement to unload the cache group, then use the LOAD CACHE GROUP statement to reload the cache group.

  • Following the execution of a REFRESH CACHE GROUP statement, the ODBC function SQLRowCount(), the JDBC method getUpdateCount(), and the OCI function OCIAttrGet() with the OCI_ATTR_ROW_COUNT argument return the number of cache instances that were refreshed.

  • Use the WITH ID clause:

    • In place of the WHERE clause for faster refreshing of the cache instance

    • To specify binding parameters

    • If you want to roll back the refresh transaction upon failure

Restrictions

  • Do not specify the PARALLEL clause:

    • With the WITH ID clause

    • With the COMMIT EVERY 0 ROWS clause

    • When database level locking is enabled (connection attribute LockLevel is set to 1)

    • for read-only dynamic cache groups

  • Do not use the WITH ID clause when refreshing these types of cache groups:

    • Explicitly loaded read-only cache groups

    • Explicitly loaded user managed cache groups with the autorefresh attribute

    • User managed cache groups with the autorefresh and propagate attributes

  • Do not use the WITH ID clause with the COMMIT EVERY n ROWS clause.

  • Do not use the WHERE clause with dynamic cache groups.

Examples

REFRESH CACHE GROUP recreation.cache COMMIT EVERY 30 ROWS;

Is equivalent to:

UNLOAD CACHE GROUP recreation.cache;
LOAD CACHE GROUP recreation.cache COMMIT EVERY 30 ROWS;

Use the HR schema to illustrate the use of the PARALLEL clause with the REFRESH CACHE GROUP statement. The COMMIT EVERY n ROWS (where n is greater than 0) is required. Issue the CACHEGROUPS command. You see cache group cg2 is defined and the autorefresh state is paused. Specify the REFRESH CACHE GROUP statement with the PARALLEL clause to provide parallel loading. You see 25 cache instances refreshed.

Command> CACHEGROUPS;

Cache Group SAMPLEUSER.CG2:

  Cache Group Type: Read Only
  Autorefresh: Yes
  Autorefresh Mode: Incremental
  Autorefresh State: Paused
  Autorefresh Interval: 1.5 Minutes

  Root Table: SAMPLEUSER.COUNTRIES
  Table Type: Read Only

  Child Table: SAMPLEUSER.LOCATIONS
  Table Type: Read Only

  Child Table: SAMPLEUSER.DEPARTMENTS
  Table Type: Read Only

1 cache group found.
Command> REFRESH CACHE GROUP cg2 COMMIT EVERY 20 ROWS PARALLEL 2;
25 cache instances affected.

See also


ALTER CACHE GROUP
CREATE CACHE GROUP
DROP CACHE GROUP
FLUSH CACHE GROUP
LOAD CACHE GROUP
UNLOAD CACHE GROUP

REFRESH MATERIALIZED VIEW

The REFRESH MATERIALIZED VIEW statement refreshes an asynchronous materialized view manually.

Required privilege

Required privilege on the materialized view log tables:

  • No privilege is required for the owner of the materialized view log tables.

  • SELECT ANY TABLE if not the owner of materialized view log tables.

Required privilege on the materialized view:

  • No privilege is required for the owner of the materialized view.

  • SELECT ANY TABLE if not the owner of materialized view.

SQL syntax

REFRESH MATERIALIZED VIEW ViewName

Parameters

ParameterDescription
ViewNameName of the asynchronous materialized view

Description

This statement refreshes the specified asynchronous materialized view. It is executed in a separate thread as a separate transaction and committed. The user transaction is not affected, but the user thread waits for the refresh operation to be completed before returning to the user. If you have not specified a refresh interval for an asynchronous materialized view, using this statement is the only way to refresh the view. If you have specified a refresh interval, you can still use this statement to refresh the view manually.

Since the refresh operation is always performed in a separate transaction, the refresh operation does not wait for any uncommitted user transactions to commit. Only the committed rows are considered for the refresh operation. This is true for the manual refresh statement as well as the automatic refresh that takes place at regular intervals.

If the CREATE MATERIALIZED VIEW statement for the view specified a FAST refresh, then the REFRESH MATERIALIZED VIEW statement uses the incremental refresh method. Otherwise this statement uses the full refresh method.

Examples

REFRESH MATERALIZED VIEW bookorders;

See also


CREATE MATERIALIZED VIEW
DROP [MATERIALIZED] VIEW

REVOKE

The REVOKE statement removes one or more privileges from a user.

Required privilege

ADMIN to revoke system privileges.

ADMIN or object owner to revoke object privileges.

SQL syntax

REVOKE {SystemPrivilege [,...] | ALL [PRIVILEGES]} FROM {User |PUBLIC} [,...]

REVOKE {{ObjectPrivilege [,...] | ALL [PRIVILEGES]} ON {[Owner.Object}} [,...]
FROM {user | PUBLIC}[,...]

Parameters

The following parameters are for revoking system privileges:

ParameterDescription
SystemPrivilegeSee "System privileges" for a list of acceptable values.
ALL [PRIVILEGES]Revokes all system privileges from the user.
UserName of the user from whom privileges are being revoked. The user name must first have been introduced to the TimesTen database by a CREATE USER statement.
PUBLICSpecifies that the privilege is revoked for all users.

The following parameters are for revoking object privileges:

ParameterDescription
ObjectPrivilegeSee "Object privileges" for a list of acceptable values.
ALL [PRIVILEGES]Revokes all object privileges from the user.
UserName of the user from whom privileges are to be revoked. The user name must first have been introduced to the TimesTen database through a CREATE USER statement.
[Owner.]ObjectObject is the name of the object on which privileges are being revoked. Owner is the owner of the object. If Owner is not specified, then the user who is revoking the privilege is known as the owner.
PUBLICSpecifies that the privilege is revoked for all users.

Description

  • Privileges on objects cannot be revoked from the owner of the objects.

  • Any user who can grant a privilege can revoke the privilege even if they were not the user who originally granted the privilege.

  • Privileges must be revoked at the same level they were granted. You cannot revoke an object privilege from a user who has the associated system privilege. For example, if you grant SELECT ANY TABLE to a user and then try to revoke SELECT ON BOB.TABLE1, the revoke fails unless you have specifically granted SELECT ON BOB.TABLE1 in addition to SELECT ANY TABLE.

  • If a user has been granted all system privileges, you can revoke a specific privilege. For example, you can revoke ALTER ANY TABLE from a user who has been granted all system privileges.

  • If a user has been granted all object privileges, you can revoke a specific privilege on a specific object from the user. For example, you can revoke the DELETE privilege on table CUSTOMERS from user TERRY even if TERRY has previously been granted all object privileges.

  • You can revoke all privileges from a user even if the user has not previously been granted all privileges.

  • You cannot revoke a specific privilege from a user who has not been granted the privilege.

  • You cannot revoke privileges on objects owned by a user.

  • You cannot revoke system privileges and object privileges in the same statement.

  • You can specify only one object in an object privilege statement.

  • Revoking the SELECT privilege on a detail table or a system privilege that includes the SELECT privilege from user2 on a detail table owned by user1 causes associated materialized views owned by user2 to be marked invalid. See "Invalid materialized views".

  • When replication is configured, this statement is replicated.

Examples

Revoke the ADMIN and DDL privileges from the user terry:

REVOKE admin, ddl FROM terry;

Assuming the revoker has ADMIN privilege, revoke the UPDATE privilege from terry on the customers table owned by pat:

REVOKE update ON pat.customers FROM terry;

See also


ALTER USER
CREATE USER
DROP USER
GRANT
"The PUBLIC role"

ROLLBACK

Use the ROLLBACK statement to undo work done in the current transaction.

Required privilege

None

SQL syntax

ROLLBACK [WORK]

Parameters

The ROLLBACK statement enables the following optional keyword:

ParameterDescription
[WORK]Optional clause supported for compliance with the SQL standard. ROLLBACK and ROLLBACK WORK are equivalent.

Description

When the PassThrough connection attribute is specified with a value greater than zero, the Oracle transaction will also be rolled back.

A rollback closes all open cursors.

Examples

Insert a row into the regions table of the HR schema and then roll back the transaction. First set AUTOCOMMIT to 0:

Command> SET AUTOCOMMIT 0;
Command> INSERT INTO regions VALUES (5,'Australia');
1 row inserted.
Command> SELECT * FROM regions;
< 1, Europe >
< 2, Americas >
< 3, Asia >
< 4, Middle East and Africa >
< 5, Australia >
5 rows found.
Command> ROLLBACK;
Command> SELECT * FROM regions;
< 1, Europe >
< 2, Americas >
< 3, Asia >
< 4, Middle East and Africa >
4 rows found.

See also


COMMIT

SELECT

The SELECT statement retrieves data from one or more tables. The retrieved data is presented in the form of a table that is called the result table, result set, or query result.

Required privilege

No privilege is required for the object owner.

SELECT for another user's object.

SELECT...FOR UPDATE also requires UPDATE privilege for another user's object.

SQL syntax

The general syntax for a SELECT statement is the following:

[WithClause] SELECT [FIRST NumRows | ROWS m TO n] [ALL | DISTINCT] SelectList
  FROM TableSpec [,...]
  [WHERE SearchCondition]
  [GROUP BY GroupByClause [,...] [HAVING SearchCondition]]
  [ORDER BY OrderByClause [,...]]
  [FOR UPDATE [OF [[Owner.]TableName.]ColumnName [,...]] 
    [NOWAIT | WAIT Seconds] ]

The syntax for a SELECT statement that contains the set operators UNION, UNION ALL, MINUS, or INTERSECT is as follows:

SELECT [ROWS m TO n] [ALL] SelectList
  FROM TableSpec [,...]
    [WHERE SearchCondition]
    [GROUP BY GroupByClause [,...] [HAVING SearchCondition] [,...]]
  {UNION [ALL] | MINUS | INTERSECT}
  SELECT [ROWS m TO n] [ALL] SelectList
    FROM TableSpec [,...]
     [WHERE SearchCondition]
     [GROUP BY GroupByClause [,...] [HAVING SearchCondition [,...] ] ]
     [ORDER BY OrderByClause [,...] ]

The syntax for OrderByClause is as follows:

{ColumnID|ColumnAlias|Expression} [ASC|DESC] [NULLS { FIRST|LAST }]

Parameters

ParameterDescription
[WithClause]The WITH clause, also known as subquery factoring, enables you to assign a name to a subquery block, which can subsequently be referenced multiple times within the top-level SELECT statement. The syntax of the WITH clause is presented under "WithClause".
FIRST NumRowsSpecifies the number of rows to retrieve. NumRows must be either a positive INTEGER value or a dynamic parameter placeholder. The syntax for a dynamic parameter placeholder is either ? or :DynamicParameter. The value of the dynamic parameter is supplied when the statement is executed.
ROWS m TO nSpecifies the range of rows to retrieve where m is the first row to be selected and n is the last row to be selected. Row counting starts at row 1. The query SELECT ROWS 1 TO n returns the same rows as SELECT FIRST NumRows assuming the queries are ordered and n and NumRows have the same value.

Use either a positive INTEGER value or a dynamic parameter placeholder for m and n values. The syntax for a dynamic parameter placeholder is either ? or :DynamicParameter. The value of the dynamic parameter is supplied when the statement is executed.

ALLPrevents elimination of duplicate rows from the query result. If neither ALL nor DISTINCT is specified, ALL is the default.
DISTINCTEnsures that each row in the query result is unique. All NULL values are considered equal for this comparison. Duplicate rows are not evaluated.

You cannot use SELECT ... on a LOB column.

SelectListSpecifies how the columns of the query result are to be derived. The syntax of select list is presented under "SelectList".
FROM TableSpecIdentifies the tables referenced in the SELECT statement. The maximum number of tables per query is 24.

TableSpec identifies a table from which rows are selected. The table can be a derived table, which is the result of a SELECT statement in the FROM clause. The syntax of TableSpec is presented under "TableSpec".

WHERE SearchConditionThe WHERE clause determines the set of rows to be retrieved. Normally, rows for which SearchCondition is FALSE or NULL are excluded from processing, but SearchCondition can be used to specify an outer join in which rows from an outer table that do not have SearchCondition evaluated to TRUE with respect to any rows from the associated inner table are also returned, with projected expressions referencing the inner table set to NULL.

The unary (+) operator may follow some column and ROWID expressions to indicate an outer join. The (+) operator must follow all column and ROWID expressions in the join conditions that refer to the inner table. There are several conditions on the placement of the (+) operator. These generally restrict the type of outer join queries that can be expressed. The (+) operator may appear in WHERE clauses but not in HAVING clauses. Two tables cannot be outer joined together. An outer join condition cannot be connected by OR.

See Chapter 5, "Search Conditions" for more information on search conditions.

GROUP BY GroupByClause [,...]The GROUP BY clause identifies one or more expressions to be used for grouping when aggregate functions are specified in the select list and when you want to apply the function to groups of rows. The syntax and description for the GROUP BY clause is described in "GROUP BY clause".
HAVING SearchConditionThe HAVING clause can be used in a SELECT statement to filter groups of an aggregate result. The existence of a HAVING clause in a SELECT statement turns the query into an aggregate query. All columns referenced outside the sources of aggregate functions in any clause except the WHERE clause must be included in the GROUP BY clause.

Subqueries can be specified in the HAVING clause.

(+)A simple join (also called an inner join) returns a row for each pair of rows from the joined tables that satisfy the join condition specified in SearchCondition. Outer joins are an extension of this operator in which all rows of the outer table are returned, whether or not matching rows from the joined inner table are found. In the case no matching rows are found, any projected expressions referencing the inner table are given the value NULL.
ORDER BY OrderByClause [,...]Sorts the query result rows in order by specified columns or expressions. Specify the sort key columns in order from major sort key to minor sort key.

The ORDER BY clause supports column aliases, which can be referenced only in an ORDER BY clause. A single query may declare several column aliases with the same name, but any reference to that alias results in an error.

ColumnIDMust correspond to a column in the select list. You can identify a column to be sorted by specifying its name or its ordinal number. The first column in the select list is column number 1. It is better to use a column number when referring to columns in the select list if they are not simple columns. Some examples are aggregate functions, arithmetic expressions, and constants.

A ColumnID in the ORDER BY clause has this syntax:

{ColumnNumber |[[Owner.]TableName.] ColumnName}

ColumnAliasUsed in an ORDER BY clause, the column alias must correspond to a column in the select list. The same alias can identify multiple columns.

{* | [Owner.]TableName.* |

{Expression | [[Owner.]TableName.]ColumnName |

[[Owner.]TableName.]ROWID

}

[[AS] ColumnAlias]} [,...]

ASC|DESCFor each column designated in the ORDER BY clause, you can specify whether the sort order is to be ascending or descending. If neither ASC (ascending) nor DESC (descending) is specified, ascending order is used. All character data types are sorted according to the current value of the NLS_SORT session parameter.
NULLS { FIRST | LAST }Valid with ORDER BY clause and is optional. If you specify ASC or DESC, NULLS FIRST or NULLS LAST must follow ASC or DESC.

Specify NULLS FIRST to have rows with NULL values returned first in your ordered query. Specify NULLS LAST to have rows with NULL values returned last in your ordered query. NULLS LAST is the default when rows are returned in ascending order. NULLS FIRST is the default when rows are returned in descending order.

If you specify the ORDER BY clause without the ASC or DESC clause and without the NULLS FIRST or NULLS LAST clause, the default ordering sequence is ascending NULLS LAST.

FOR UPDATE

[OF [[Owner.]

TableName.]

ColumnName [,...]]

[NOWAIT | WAIT Seconds]

FOR UPDATE
  • FOR UPDATE maintains a lock on an element (usually a row) until the end of the current transaction, regardless of isolation. All other transactions are excluded from performing any operation on that element until the transaction is committed or rolled back.

  • FOR UPDATE may be used with joins and the ORDER BY, GROUP BY, and DISTINCT clauses. Update locks are obtained on either tables or rows, depending on the table/row locking method chosen by the optimizer.

  • Rows from all tables that satisfy the WHERE clause are locked in UPDATE mode unless the FOR UPDATE OF clause is specified. This clause specifies which tables to lock.

  • If using row locks, all qualifying rows in all tables from the table list in the FROM clause are locked in update mode. Qualifying rows are those rows that satisfy the WHERE clause. When table locks are used, the table is locked in update mode whether or not there are any qualifying rows.

  • If the serializable isolation level and row locking are enabled, nonqualifying rows are downgraded to Shared mode. If a read-committed isolation level and row locking are turned on, nonqualifying rows are unlocked.

  • SELECT...FOR UPDATE locks are not blocked by SELECT locks.

FOR UPDATE [OF [[Owner.]TableName.]ColumnName [,...] ]

  • This mode optionally includes the name of the column or columns in the table to be locked for update.

[NOWAIT | WAIT Seconds ]

  • This specifies how to proceed if the selected rows are locked. It does not apply to table-level locks or database-level locks.

  • NOWAIT specifies that there is no waiting period for locks. An error is returned if the lock is not available.

  • WAIT Seconds specifies the lock timeout setting.

    An error is returned if the lock is not obtained in the specified amount of time.

    The lock timeout setting is expressed in seconds or fractions of second. The data type for Seconds is NUMBER. Values between 0.0 and 1000000.0 are valid.

  • If neither NOWAIT nor WAIT is specified, the lock timeout interval for the transaction is used.

SelectQuery1

{UNION [ALL] | MINUS | INTERSECT}

SelectQuery2

Specifies that the results of SelectQuery1 and SelectQuery2 are to be combined, where SelectQuery1 and SelectQuery2 are general SELECT statements with some restrictions.

The UNION operator combines the results of two queries where the SelectList is compatible. If UNION ALL is specified, duplicate rows from both SELECT statements are retained. Otherwise, duplicates are removed.

The MINUS operator combines rows returned by the first query but not by the second into a single result.

The INTERSECT operator combines only those rows returned by both queries into a single result.

The data type of corresponding selected entries in both SELECT statements must be compatible. One type can be converted to the other type using the CAST operator. Nullability does not need to match.

The length of a column in the result is the longer length of correspondent selected values for the column. The column names of the final result are the column names of the leftmost select.

You can combine multiple queries using the set operators UNION, UNION ALL, MINUS, and INTERSECT.

One or both operands of a set operator can be a set operator. Multiple or nested set operators are evaluated from left to right.

The set operators can be mixed in the same query.

Restrictions on the SELECT statement that specify the set operators are as follows:

  • Neither SELECT statement can specify FIRST NumRows.

  • ORDER BY can be specified to sort the final result but cannot be used with any individual operand of a set operator. Only column names of tables or column alias from the leftmost SELECT statement can be specified in the ORDER BY clause.

  • GROUP BY can be used to group an individual SELECT operand of a set operator but cannot be used to group a set operator result.

  • The set operators cannot be used in materialized view or a joined table.


Description

  • When you use a correlation name, the correlation name must conform to the syntax rules for a basic name. (See "Basic names".) All correlation names within one SELECT statement must be unique. Correlation names are useful when you join a table to itself. Define multiple correlation names for the table in the FROM clause and use the correlation names in the select list and the WHERE clause to qualify columns from that table. See "TableSpec" for more information about correlation names.

  • SELECT...FOR UPDATE is supported in a SELECT statement that specifies a subquery, but it can be specified only in the outermost query.

  • If your query specifies either FIRST NumRows or ROWS m TO n, ROWNUM may not be used to restrict the number of rows returned.

  • FIRST NumRows and ROWS m TO n cannot be used together in the same SELECT statement.

Examples

This example shows the use of a column alias (max_salary) in the SELECT statement:

SELECT MAX(salary) AS max_salary 
FROM employees 
WHERE employees.hire_date > '2000-01-01 00:00:00';
< 10500 >
1 row found.

This example uses two tables, orders and lineitems.

The orders table and lineitems table are created as follows:

CREATE TABLE orders(orderno INTEGER, orderdate DATE, customer CHAR(20));

CREATE TABLE lineitems(orderno INTEGER, lineno INTEGER, 
  qty INTEGER, unitprice DECIMAL(10,2));

Thus for each order, there is one record in the orders table and a record for each line of the order in lineitems.

To find the total value of all orders entered since the beginning of the year, use the HAVING clause to select only those orders that were entered on or after January 1, 2000:

SELECT o.orderno, customer, orderdate, SUM(qty * unitprice)
FROM orders o, lineitems l
WHERE o.orderno=l.orderno
GROUP BY o.orderno, customer, orderdate
HAVING orderdate >= DATE '2000-01-01';

Consider this query:

SELECT * FROM tablea, tableb
WHERE tablea.column1 = tableb.column1 AND tableb.column2 > 5
FOR UPDATE;

The query locks all rows in tablea where:

  • tablea.column1 equals at least one tableb.column1 value where tableb.column2 is greater than 5.

The query also locks all rows in tableb where:

  • tableb.column2 is greater than 5.

  • tableb.column1 equals at least one tablea.column1 value.

If no WHERE clause is specified, all rows in both tables are locked.

This example demonstrates the (+) join operator:

SELECT * FROM t1, t2
WHERE t1.x = t2.x(+);

The following query returns an error because an outer join condition cannot be connected by OR:

SELECT * FROM t1, t2, t3
WHERE t1.x = t2.x(+) OR t3.y = 5;

The following query is valid:

SELECT * FROM t1, t2, t3
WHERE t1.x = t2.x(+) AND (t3.y = 4 OR t3.y = 5);

A condition cannot use the IN operator to compare a column marked with (+). For example, the following query returns an error:

SELECT * FROM t1, t2, t3
WHERE t1.x = t2.x(+) AND t2.y(+) IN (4,5);

The following query is valid:

SELECT * FROM t1, t2, t3
WHERE t1.x = t2.x(+) AND t1.y IN (4,5);

The following query results in an inner join. The condition without the (+) operator is treated as an inner join condition:

SELECT * FROM t1, t2
WHERE t1.x = t2.x(+) AND t1.y = t2.y;

In the following query, the WHERE clause contains a condition that compares an inner table column of an outer join with a constant. The (+) operator is not specified and hence the condition is treated as an inner join condition.

SELECT * FROM t1, t2
WHERE t1.x = t2.x(+) AND t2.y = 3;

For more join examples, see "JoinedTable".

This example returns the current sequence value in the student table:

SELECT SEQ.CURRVAL FROM student;

The following query produces a derived table because it contains a SELECT statement in the FROM clause:

SELECT * FROM t1, (SELECT MAX(x2) maxx2 FROM t2) tab2 
WHERE t1.x1 = tab2.maxx2;

The following query joins the results of two SELECT statements:

SELECT * FROM t1 
WHERE x1 IN (SELECT x2 FROM t2) 
UNION 
SELECT * FROM t1 
WHERE x1 IN (SELECT x3 FROM t3);

Select all orders that have the same price as the highest price in their category:

SELECT * FROM orders WHERE price = (SELECT MAX(price) 
FROM stock WHERE stock.cat=orders.cat);

The next example illustrates the use of the INTERSECT set operator. There is a department_id value in the employees table that is NULL. In the departments table, the department_id is defined as a NOT NULL primary key. The rows returned from using the INTERSECT set operator do not include the row in the departments table whose department_id value is NULL.

Command> SELECT department_id FROM employees INTERSECT SELECT department_id 
       > FROM departments;
< 10 >
< 20 >
< 30 >
< 40 >
< 50 >
< 60 >
< 70 >
< 80 >
< 90 >
< 100 >
< 110 >
11 rows found.
Command> SELECT DISTINCT department_id FROM employees;
< 10 >
< 20 >
< 30 >
< 40 >
< 50 >
< 60 >
< 70 >
< 80 >
< 90 >
< 100 >
< 110 >
< <NULL> >
12 rows found.

The next example illustrates the use of the MINUS set operator by combining rows returned by the first query but not the second. The row containing the NULL department_id value in the employees table is the only row returned.

Command> SELECT department_id FROM employees 
       > MINUS SELECT department_id FROM departments;
< <NULL> >
1 row found.

The following example illustrates the use of the SUBSTR expression in a GROUP BY clause and the use of a subquery in a HAVING clause. The first 10 rows are returned.

Command> SELECT ROWS 1 TO 10 SUBSTR (job_id, 4,10), department_id, manager_id, 
       > SUM (salary) FROM employees
       > GROUP BY SUBSTR (job_id,4,10),department_id, manager_id
       > HAVING (department_id, manager_id) IN
       > (SELECT department_id, manager_id FROM employees x
       > WHERE x.department_id = employees.department_id)
       > ORDER BY SUBSTR (job_id, 4,10),department_id,manager_id;
< ACCOUNT, 100, 108, 39600 >
< ACCOUNT, 110, 205, 8300 >
< ASST, 10, 101, 4400 >
< CLERK, 30, 114, 13900 >
< CLERK, 50, 120, 22100 >
< CLERK, 50, 121, 25400 >
< CLERK, 50, 122, 23600 >
< CLERK, 50, 123, 25900 >
< CLERK, 50, 124, 23000 >
< MAN, 20, 100, 13000 >
10 rows found.

The following example locks the employees table for update and waits 10 seconds for the lock to be available. An error is returned if the lock is not acquired in 10 seconds. The first five rows are selected.

Command> SELECT FIRST 5 last_name FROM employees FOR UPDATE WAIT 10;
< King >
< Kochhar >
< De Haan >
< Hunold >
< Ernst >
5 rows found.

The next example locks the departments table for update. If the selected rows are locked by another process, an error is returned if the lock is not available. This is because NOWAIT is specified.

Command> SELECT FIRST 5 last_name e FROM employees e, departments d 
       > WHERE e.department_id = d.department_id 
       > FOR UPDATE OF d.department_id NOWAIT;
< Whalen >
< Hartstein >
< Fay >
< Raphaely >
< Khoo >
5 rows found.

Use the HR schema to illustrate the use of a subquery with the FOR UPDATE clause:

Command> SELECT employee_id, job_id FROM job_history 
       > WHERE (employee_id, job_id) NOT IN (SELECT employee_id, job_id 
       > FROM employees) 
       > FOR UPDATE;
< 101, AC_ACCOUNT >
< 101, AC_MGR >
< 102, IT_PROG >
< 114, ST_CLERK >
< 122, ST_CLERK >
< 176, SA_MAN >
< 200, AC_ACCOUNT >
< 201, MK_REP >
8 rows found.

Use a dynamic parameter placeholder for SELECT ROWS m TO n and SELECT FIRST:

Command> SELECT ROWS ? TO ? employee_id FROM employees;

Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.

Enter Parameter 1 (TT_INTEGER) > 1
Enter Parameter 2 (TT_INTEGER) > 3
< 100 >
< 101 >
< 102 >
3 rows found.
Command> SELECT ROWS :a TO :b employee_id FROM employees;

Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.

Enter Parameter 1 (TT_INTEGER) > 1
Enter Parameter 2 (TT_INTEGER) > 3
< 100 >
< 101 >
< 102 >
3 rows found.
Command> SELECT FIRST ? employee_id FROM employees;

Type '?' for help on entering parameter values.
Type '*' to end prompting and abort the command.
Type '-' to leave the parameter unbound.
Type '/;' to leave the remaining parameters unbound and execute the command.

Enter Parameter 1 (TT_INTEGER) > 3
< 100 >
< 101 >
< 102 >
3 rows found.

The following example illustrates the use of NULLS LAST in the ORDER BY clause. Query the employees table to find employees with a commission percentage greater than .30 or a commission percentage that is NULL. Select the first seven employees and order by commission_pct and last_name. Order commision_pct in descending order and use NULLS LAST to display rows with NULL values last in the query. Output commission_pct and last_name.

Command> SELECT FIRST 7 commission_pct,last_name
         FROM employees where commission_pct > .30
         OR commission_pct IS NULL
         ORDER BY commission_pct DESC NULLS LAST,last_name;
< .4, Russell >
< .35, King >
< .35, McEwen >
< .35, Sully >
< <NULL>, Atkinson >
< <NULL>, Austin >
< <NULL>, Baer >
7 rows found.

WithClause

Syntax

WithClause has the following syntax:

WITH QueryName AS ( Subquery ) [, QueryName AS ( Subquery )] ...

Parameters

WithClause has the following parameter:

ParameterDescription
QueryName AS (Subquery)Specifies an alias for a subquery that can be used multiple times within the SELECT statement.

Description

Subquery factoring provides the WITH clause that enables you to assign a name to a subquery block, which can subsequently be referenced multiple times within the main SELECT query. The query name is visible to the main query and any subquery contained in the main query.

The WITH clause can only be defined as a prefix to the main SELECT statement.

Subquery factoring is useful in simplifying complex queries that use duplicate or complex subquery blocks in one or more places. In addition, TimesTen uses subquery factoring to optimize the query by evaluating and materializing the subquery block once and providing the result for each reference in the SELECT statement.

Restrictions using the WITH clause:

  • Do not use the WITH clause in a view or materialized view definition.

  • Do not use the WITH clause in global queries.

  • Do not use the set operators (UNION, INTERSECT, or MINUS) in the main query.

  • Recursive subquery factoring is not supported.

  • You cannot provide a column parameter list for the query alias.

Example

The following example creates the query names dept_costs and avg_cost for the initial query block, then uses these names in the body of the main query.

Command> WITH dept_costs AS (
> SELECT department_name, SUM(salary) dept_total
> FROM employees e, departments d
> WHERE e.department_id = d.department_id
> GROUP BY department_name),
> avg_cost AS (
> SELECT SUM(dept_total)/COUNT(*) avg
> FROM dept_costs)
> SELECT * FROM dept_costs
> WHERE dept_total >
> (SELECT avg FROM avg_cost)
> ORDER BY department_name;

> DEPARTMENT_NAME DEPT_TOTAL
-------------------------------
Sales 304500
Shipping 156400

SelectList

SQL syntax

The SelectList parameter of the SELECT statement has the following syntax:

{* | [Owner.]TableName.* | 
  { Expression | [[Owner.]TableName.]ColumnName |
    [[Owner.]TableName.]ROWID | NULL
  }
  [[AS] ColumnAlias] } [,...]

Parameters

The SelectList parameter of the SELECT statement has the following parameters:

ParameterDescription
*
Includes, as columns of the query result, all columns of all tables specified in the FROM clause.
[Owner.]TableName.*Includes all columns of the specified table in the result.
ExpressionAn aggregate query includes a GROUP BY clause or an aggregate function.

When the select list is not an aggregate query, the column reference must reference a table in the FROM clause.

A column reference in the select list of an aggregate query must reference a column list in the GROUP BY clause. If there is no GROUP BY clause, then the column reference must reference a table in the FROM clause. See "GROUP BY clause" for more information on the GROUP BY clause.

[[Owner.]Table.] ColumnNameIncludes a particular column from the named owner's indicated table. You can also specify the CURRVAL or NEXTVAL column of a sequence. See "Incrementing SEQUENCE values with CURRVAL and NEXTVAL" for more details.
[[Owner.]Table.] ROWIDIncludes the ROWID pseudocolumn from the named owner's indicated table.
NULLWhen NULL is specified, the default for the resulting data type is VARCHAR(0). You can use the CAST function to convert the result to a different data type. NULL can be specified in the ORDER BY clause.
ColumnAliasUsed in an ORDER BY clause, the column alias must correspond to a column in the select list. The same alias can identify multiple columns.

{*|[Owner.]TableName.*|

{Expression |[[Owner.]TableName.]ColumnName |

[[Owner.]TableName.]ROWID

}

[[AS] ColumnAlias]} [,...]


Description

  • The clauses must be specified in the order given in the syntax diagram.

  • TimesTen does not support subqueries in the select list

  • A result column in the select list can be derived in any of the following ways:

    • A result column can be taken directly from one of the tables listed in the FROM clause.

    • Values in a result column can be computed, using an arithmetic expression, from values in a specified column of a table listed in the FROM clause.

    • Values in several columns of a single table can be combined in an arithmetic expression to produce the result column values.

    • Aggregate functions (AVG, MAX, MIN, SUM, and COUNT) can be used to compute result column values over groups of rows. Aggregate functions can be used alone or in an expression. You can specify aggregate functions containing the DISTINCT option that operate on different columns in the same table. If the GROUP BY clause is not specified, the function is applied over all rows that satisfy the query. If the GROUP BY clause is specified, the function is applied once for each group defined by the GROUP BY clause. When you use aggregate functions with the GROUP BY clause, the select list can contain aggregate functions, arithmetic expressions, and columns in the GROUP BY clause. For more details on the GROUP BY clause, see "GROUP BY clause".

    • A result column containing a fixed value can be created by specifying a constant or an expression involving only constants.

  • In addition to specifying how the result columns are derived, the select list also controls their relative position from left to right in the query result. The first result column specified by the select list becomes the leftmost column in the query result, and so on.

  • Result columns in the select list are numbered from left to right. The leftmost column is number 1. Result columns can be referred to by column number in the ORDER BY clause. This is especially useful if you want to refer to a column defined by an arithmetic expression or an aggregate.

  • To join a table with itself, define multiple correlation names for the table in the FROM clause and use the correlation names in the select list and the WHERE clause to qualify columns from that table.

  • When you use the GROUP BY clause, one answer is returned per group in accordance with the select list, as follows:

    • The WHERE clause eliminates rows before groups are formed.

    • The GROUP BY clause groups the resulting rows. See "GROUP BY clause" for more details.

    • The select list aggregate functions are computed for each group.

Examples

In this example, one value, the average number of days you wait for a part, is returned by the statement:

SELECT AVG(deliverydays)
FROM purchasing.supplyprice;

The part number and delivery time for all parts that take fewer than 20 days to deliver are returned by the following statement:

SELECT partnumber, deliverydays
FROM purchasing.supplyprice
WHERE deliverydays < 20;

Multiple rows may be returned for a single part.

The part number and average price of each part are returned by the following statement:

SELECT partnumber, AVG(unitprice)
FROM purchasing.supplyprice
GROUP BY partnumber;

In the following example, the join returns names and locations of California suppliers. Rows are returned in ascending order by partnumber values. Rows containing duplicate part numbers are returned in ascending order by vendorname values. The FROM clause defines two correlation names (v and s), which are used in both the select list and the WHERE clause. The vendornumber column is the only common column between vendors and supplyprice.

SELECT partnumber, vendorname, s.vendornumber,vendorcity
  FROM purchasing.supplyprice s, purchasing.vendors v
  WHERE s.vendornumber = v.vendornumber AND vendorstate = 'CA'
ORDER BY partnumber, vendorname;

The following query joins table purchasing.parts to itself to determine which parts have the same sales price as the part whose serial number is '1133-P-01'.

SELECT q.partnumber, q.salesprice
  FROM purchasing.parts p, purchasing.parts q
  WHERE p.salesprice = q.salesprice AND p.serialnumber = '1133-P-01';

The next example shows how to retrieve the rowid of a specific row. The retrieved rowid value can be used later for another SELECT, DELETE, or UPDATE statement.

SELECT rowid
FROM purchasing.vendors
WHERE vendornumber = 123;

The following example shows how to use a column alias to retrieve data from the table employees.

SELECT MAX(salary) AS max_salary FROM employees;

TableSpec

SQL syntax

The TableSpec parameter of the SELECT statement has the following syntax:

{[Owner.]TableName [CorrelationName] | JoinedTable | DerivedTable}

A simple table specification has the following syntax:

[Owner.]TableName

Parameters

The TableSpec parameter of the SELECT statement has the following parameters:

ParameterDescription
[Owner.]TableNameIdentifies a table to be referenced.
CorrelationNameCorrelationName specifies an alias for the immediately preceding table. When accessing columns of that table elsewhere in the SELECT statement, use the correlation name instead of the actual table name within the statement. The scope of the correlation name is the SQL statement in which it is used. The correlation name must conform to the syntax rules for a basic name. See "Basic names".

All correlation names within one statement must be unique.

JoinedTableSpecifies the query that defines the table join. The syntax of JoinedTable is presented under "JoinedTable".
DerivedTableSpecifies a table derived from the evaluation of a SELECT statement. No FIRST NumRows or ROWS m TO n clauses are allowed in this SELECT statement. The syntax of DerivedTable is presented under "DerivedTable"


JoinedTable

The JoinedTable parameter specifies a table derived from CROSS JOIN, INNER JOIN, LEFT OUTER JOIN or RIGHT OUTER JOIN.

SQL syntax

The syntax for JoinedTable is as follows:

{CrossJoin | QualifiedJoin}

Where CrossJoin is:

TableSpec1 CROSS JOIN TableSpec2

And QualifiedJoin is:

TableSpec1 [JoinType] JOIN TableSpec2 ON SearchCondition

In the QualifiedJoin parameter, JoinType syntax is as follows:

{INNER | LEFT [OUTER] | RIGHT [OUTER]}

Parameters

The JoinedTable parameter of the TableSpec clause of a SELECT statement has the following parameters:

ParameterDescription
CrossJoinPerforms a cross join on two tables. A cross join returns a result table that is the cartesian product of the input tables. The result is the same as that of a query with the following syntax:

SELECT Selectlist FROM Table1, Table2

QualifiedJoinSpecifies that the join is of type JoinType.
TableSpec1Specifies the first table of the JOIN clause.
TableSpec2Specifies the second table of the JOIN clause.
JoinType JOINSpecifies the type of join to perform. These are the supported join types:
  • INNER

  • LEFT [OUTER]

  • RIGHT [OUTER]

INNER JOIN returns a result table that combines the rows from two tables that meet SearchCondition.

LEFT OUTER JOIN returns join rows that match SearchCondition and rows from the first table that do not have SearchCondition evaluated as true with any row from the second table.

RIGHT OUTER JOIN returns join rows that match SearchCondition and rows from the second table that do not have SearchCondition evaluated as true with any row from the first table.

ON SearchConditionSpecifies the search criteria to be used in a JOIN parameter. SearchCondition can refer only to tables referenced in the current qualified join.

Description

  • FULL OUTER JOIN is not supported.

  • A joined table can be used to replace a table in a FROM clause anywhere except in a statement that defines a materialized view. Thus, a joined table can be used in UNION, MINUS, INTERSECT, a subquery, a nonmaterialized view, or a derived table.

  • A subquery cannot be specified in the operand of a joined table. For example, the following statement is not supported:

    SELECT * FROM
      regions INNER JOIN (SELECT * FROM countries) table2
      ON regions.region_id=table2.region_id;
    
  • A view can be specified as an operand of a joined table.

  • A temporary table cannot be specified as an operand of a joined table.

  • OUTER JOIN can be specified in two ways, either using the (+) operator in SearchCondition of the WHERE clause or using a JOIN table operation. The two specification methods cannot coexist in the same statement.

  • Join order and grouping can be specified with a JoinedTable operation, but they cannot be specified with the (+) operator. For example, the following operation cannot be specified with the (+) operator:

    t LEFT JOIN (t2 INNER JOIN t3 ON x2=x3) ON (x1 = x2 - x3)
    

Examples

These examples use the regions and countries tables from the HR schema.

Perform a left outer join:

SELECT * FROM regions LEFT JOIN countries
  ON regions.region_id=countries.region_id
  WHERE regions.region_id=3;

< 3, Asia, JP, Japan, 3 >
< 3, Asia, CN, China, 3 >
< 3, Asia, IN, India, 3 >
< 3, Asia, AU, Australia, 3 >
< 3, Asia, SG, Singapore, 3 >
< 3, Asia, HK, HongKong, 3 >
6 rows found.

You can also perform a left outer join with the (+) operator, as follows.

SELECT * FROM regions, countries
  WHERE regions.region_id=countries.region_id (+)
    AND regions.region_id=3;

For more examples of joins specified with the (+) operator, see "Examples".

The following performs a right outer join:

SELECT * FROM regions RIGHT JOIN countries
  ON regions.region_id=wountries.region_id
  WHERE regions.region_id=3;

< AU, Australia, 3, 3, Asia >
< CN, China, 3, 3, Asia >
< HK, HongKong, 3, 3, Asia >
< IN, India, 3, 3, Asia >
< JP, Japan, 3, 3, Asia >
< SG, Singapore, 3, 3, Asia >
6 rows found.

The next example performs a right outer join with the (+) operator:

SELECT * FROM countries, regions
       WHERE regions.region_id (+)=countries.region_id
       AND countries.region_id=3;
< JP, Japan, 3, 3, Asia >
< CN, China, 3, 3, Asia >
< IN, India, 3, 3, Asia >
< AU, Australia, 3, 3, Asia >
< SG, Singapore, 3, 3, Asia >
< HK, HongKong, 3, 3, Asia >
6 rows found.

Note that the right join methods produce the same rows but in a different display order. There should be no expectation of row order for join results.

The following performs an inner join:

SELECT * FROM regions INNER JOIN countries
  ON regions.region_id=countries.region_id
  WHERE regions.region_id=2;

< 2, Americas, US, United States of America, 2 >
< 2, Americas, CA, Canada, 2 >
< 2, Americas, BR, Brazil, 2 >
< 2, Americas, MX, Mexico, 2 >
< 2, Americas, AR, Argentina, 2 >
5 rows found.

The next example performs a cross join:

SELECT * FROM regions CROSS JOIN countries 
  WHERE regions.region_id=1;

< 1, Europe, AR, Argentina, 2 >
< 1, Europe, AU, Australia, 3 >
< 1, Europe, BE, Belgium, 1 >
< 1, Europe, BR, Brazil, 2 >
...
< 1, Europe, SG, Singapore, 3 >
< 1, Europe, UK, United Kingdom, 1 >
< 1, Europe, US, United States of America, 2 >
< 1, Europe, ZM, Zambia, 4 >
< 1, Europe, ZW, Zimbabwe, 4 >
25 rows found.

See also


CREATE TABLE
INSERT
INSERT...SELECT
UPDATE

DerivedTable

A derived table is the result of a SELECT statement in the FROM clause, with an alias.

SQL syntax

The syntax for DerivedTable is as follows:

(Subquery) [CorrelationName]

Parameters

The DerivedTable parameter of the TableSpec clause of a SELECT statement has the following parameters:

ParameterDescription
SubqueryFor information on subqueries, see "Subqueries".
CorrelationNameOptionally use CorrelationName to specify an alias for the derived table. It must be different from any table name referenced in the query.

Description

When using a derived table, these restrictions apply:

  • The DUAL table can be used in a SELECT statement that references no other tables, but needs to return at least one row. Selecting from DUAL is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once.

  • Subquery cannot refer to a column from another derived table.

  • A derived table cannot be used as a source of a joined table.

  • A derived table cannot be used as a target of a DELETE or UPDATE statement.


GROUP BY clause

Specify the GROUP BY clause if you want the database to group the selected rows based on the value of expressions for each row and return a single row of summary information for each group. If the GROUP BY clause is omitted, the entire query result is treated as one group. If this clause contains CUBE or ROLLUP, the results contain superaggregate groupings in addition to the regular groupings.

The expressions in the GROUP BY clause can do the following:

  • Designate single or multiple columns.

  • Include arithmetic operations, the ROWID pseudocolumn, or NULL.

  • Include a date, a constant, or a dynamic parameter.

  • Include ROLLUP or CUBE clauses, where the results produce superaggregate groupings in addition to the regular groupings. Superaggregate groupings are calculated subtotals and totals returned with the regular groupings in the GROUP BY clause.

  • Include GROUPING SETS clause to distinguish which superaggregate groupings to produce.

When you use the GROUP BY clause, the select list can contain only aggregate functions and columns referenced in the GROUP BY clause. If the select list contains the construct *, TableName.*, or Owner.TableName.*, the GROUP BY clause must contain all columns that the * includes. NULL values are considered equivalent in grouping rows. If all other columns are equal, all NULL values in a column are placed in a single group.


Note:

To identify and potentially eliminate NULL groupings from the superaggregate groupings, use the GROUPING function, as described in "GROUPING".

SQL syntax

The general syntax for the GROUP BY clause is the following:

GROUP BY
 {Expression | RollupCubeClause | GroupingSetsClause }[,...]
 
GroupingSetsClause::=  GROUPING SETS 
 GroupingExpressionList | RollupCubeClause [,...]

RollupCubeClause
{ ROLLUP | CUBE } ( GroupingExpressionList ) }

GroupingExpressionList::=   
{ Expression | ExpressionList [, { Expression | ExpressionList } ] ...}
 
ExpressionList :: = ( Expression [, Expression ] ...)

Parameters

ParameterDescription
ExpressionValid expression syntax. See Chapter 3, "Expressions".
RollupCubeClauseThe GROUP BY clause may include one or more ROLLUP or CUBE clauses.
GroupingSetsClauseThe GROUP BY clause may include one or more GROUPING SETS clauses. The GROUPING SETS clause enables you to explicitly specify which groupings of data that the database returns. For more information, see "GROUPING SETS".
GroupingExpressionListThe GROUP BY clause can contain multiple expressions or expression lists.
ROLLUP GroupingExpressionListThe ROLLUP clause is used to generate superaggregate rows from groups. For more information, see "ROLLUP".
CUBE GroupingExpressionListThe CUBE clause groups selected rows based on the values of all possible combinations of the grouping columns in the CUBE clause. For more information, see "CUBE".
ExpressionListA list of one or more expressions, each separated by a comma.

Examples

The following GROUP BY example sums the salaries for employees in the employees table and uses the SUBSTR expression to group the data by job function.

Command> SELECT SUBSTR (job_id, 4,10), SUM (salary) FROM employees
       > GROUP BY SUBSTR (job_id,4,10);
< PRES, 24000 >
< VP, 34000 >
< PROG, 28800 >
< MGR, 24000 >
< ACCOUNT, 47900 >
< MAN, 121400 >
< CLERK, 133900 >
< REP, 273000 >
< ASST, 4400 >
9 rows found.

Query emp_details_view to select the first 10 departments and managers within the department and count the number of employees in the department with the same manager. Use the GROUP BY clause to group the result by department and manager.

Command> columnlabels on;
Command> SELECT first 10 department_id AS DEPT, manager_id AS MGR,
       > COUNT(employee_id) AS NUM_EMP
       > FROM emp_details_view
       > GROUP BY (department_id, manager_id)
       > ORDER BY department_id, manager_id;

DEPT, MGR, NUM_EMP
< 10, 101, 1 >
< 20, 100, 1 >
< 20, 201, 1 >
< 30, 100, 1 >
< 30, 114, 5 >
< 40, 101, 1 >
< 50, 100, 5 >
< 50, 120, 8 >
< 50, 121, 8 >
< 50, 122, 8 >
10 rows found.

ROLLUP, CUBE and GROUPING SETS clauses

The following definitions describe how columns can be grouped within the ROLLUP, CUBE or GROUPING SETS clauses:

  • Grouping column: A single column used in a GROUP BY clause. For example, in the following GROUP BY clause, X, Y, and Z are group columns.

    GROUP BY X, GROUPING SETS(Y, Z)
    
  • Composite Column: A list of grouping columns inside parentheses. For example, in the following clause, (C1, C2) and (C3, C4) are composite columns:

    GROUP BY ROLLUP( (C1,C2), (C3,C4), C5);
    
  • Grouping: Grouping is a single level of aggregation from within a grouping set. For example, in the following statement, (C1) and (C2, C3) are individual groupings:

    GROUP BY GROUPING SETS(C1, (C2,C3));
    
  • Grouping Set: A collection of groupings inside parentheses. For example, in the following statement, (C1, (C2, C3)) and (C2, (C4, C5)) are two individual grouping sets:

    GROUP BY GROUPING SETS(C1, (C2,C3)), GROUPING SETS(C2, (C4, C5));
    
  • Concatenated grouping sets: Separate multiple grouping sets with commas. The result is a cross-product of groupings from each grouping set.

  • Grand Total or Empty set column: A grand total or empty set grouping computes aggregation by considering all rows as one group. Grand totals are automatically provided in the results for ROLLUP and CUBE clauses; however, you request the grand total in the GROUPING SETS clause by providing an empty parenthesis "( )".

Duplicate grouping columns can be used in ROLLUP, CUBE or GROUPING SETS. However, it does result in duplicated result rows.

Restrictions for ROLLUP, CUBE and GROUPING SETS clauses are as follows:

  • These clauses are not supported within a materialized view definition.

  • These clauses are not supported for global queries across a cache grid.

The following sections describe the ROLLUP, CUBE and GROUPING SETS clauses:

GROUPING SETS

The GROUPING SETS clause enables you to explicitly specify which groupings of data that the database returns. You specify only the desired groups by enclosing them within parentheses, so the database only generates the superaggregate summaries in which you are interested.

The following statement produces three groups: one group returns results for each gender and year columns, a second for a summary superaggregate for each of the months and the last result for the grand total.

SELECT GENDER, YEAR, MONTH,
   SUM (NUM_OF_STUDENTS) AS TOTAL
   FROM INSTRUCTOR_SUMMARY
   GROUP BY GROUPING SETS ((GENDER, YEAR),  -- 1ST GROUP
                           (MONTH), -- 2ND GROUP
                           ()); -- 3RD GROUP
 

You can combine multiple GROUPING SETS to generate specific combinations between the multiple GROUPING SETS. The following statement contains two GROUPING SETS clauses:

GROUP BY GROUPING SETS (YEAR, MONTH),
         GROUPING SETS (WEEK, DAY);

This is equivalent to the following GROUPING SETS statement:

GROUP BY GROUPING SETS (YEAR, WEEK), 
 (YEAR, DAY), 
 (MONTH, WEEK), 
 (MONTH, DAY);

When a GROUP BY clause has both regular grouping columns and a GROUPING SETS clause, the results are grouped by the regular grouping column as follows:

GROUP BY a, b GROUPING SETS(c, d);

This is equivalent to the following:

GROUP BY GROUPING SETS((a, b, c), (a, b, d));

Example

The following example specifies the grouping sets of (region_name, country_name), state_province, and grand totals.

Command> SELECT region_name AS Region,
       >    country_name AS Country,
       >    state_province AS State,
       >    COUNT(employee_id) AS "Total Emp"
       > FROM regions r, countries c, locations l, departments d, employees e
       > WHERE r.region_id = c.region_id AND
       >    l.country_id = c.country_id AND
       >    d.location_id = l.location_id AND
       >    d.department_id = e.department_id
       > GROUP BY grouping sets((region_name, country_name), state_province, ())
       > ORDER BY region_name, state_province;
 
REGION, COUNTRY, STATE, TOTAL EMP
< Americas, Canada, <NULL>, 2 >
< Americas, United States of America, <NULL>, 68 >
< Europe, Germany, <NULL>, 1 >
< Europe, United Kingdom, <NULL>, 35 >
< <NULL>, <NULL>, Bavaria, 1 >
< <NULL>, <NULL>, California, 45 >
< <NULL>, <NULL>, Ontario, 2 >
< <NULL>, <NULL>, Oxford, 34 >
< <NULL>, <NULL>, Texas, 5 >
< <NULL>, <NULL>, Washington, 18 >
< <NULL>, <NULL>, <NULL>, 106 >
< <NULL>, <NULL>, <NULL>, 1 >
12 rows found.

ROLLUP

ROLLUP is used within the GROUP BY clause. When used with SUM, ROLLUP generates subtotals from most detailed level (all columns specified in the ROLLUP clause) to the grand total level, by removing one column at each level. These are known as superaggregate rows.

The ROLLUP clause returns the following:

  • Regular aggregate rows that would be produced by GROUP BY without using ROLLUP.

  • Subtotals following the grouping list specified in the ROLLUP clause. ROLLUP takes as its argument an ordered list of grouping columns. Each subtotal is created for the ordered list of grouping columns dropping the right-most grouping column until it reaches the grand total. For instance, if you specify GROUP BY ROLLUP(x, y, z), the returned superaggregate groups would be as follows: (x,y,z), (x,y), (x), ( ).

    The number of subtotals created is n+1 aggregate levels, where n is the number of grouping columns. For example, three expressions (n=3) in the ROLLUP clause results in n+1 = 3+1 = 4 groupings.

  • Grand total row.

You can group columns using composite columns inside parentheses. For example, in the following statement:

GROUP BY ROLLUP( (a, b), (c, d), e);

The (a, b) and (c, d) composite columns are treated as a unit when the database produces the ROLLUP results. In this example, the grouping sets returned are as follows: ( (a, b), (c, d), e ), ( (a, b), (c, d) ), (a, b) and ().

You can execute several ROLLUP clauses within your SELECT statement, as follows:

SELECT C1, COUNT(*)
FROM T
GROUP BY ROLLUP(a, b), ROLLUP(c, d);

This is equivalent to the following statement:

SELECT C1, COUNT(*)
FROM T
GROUP BY GROUPING SETS((a, b),(a),()), 
 GROUPING SETS((c, d),(c), ());

Examples

Query the employees table to select the first 10 departments and return the number of employees under each manager in each department. Use ROLLUP to subtotal the number of employees in each department and return a grand total of all employees in the company.

Command> SELECT first 10 department_id AS Dept,
       > manager_id AS Mgr,
       > COUNT(employee_id) AS "Total emp"
       > FROM employees
       > GROUP BY ROLLUP(department_id, manager_id)
       > ORDER BY department_id, manager_id;
 
DEPT, MGR, TOTAL EMP
< 10, 101, 1 >
< 10, <NULL>, 1 >
< 20, 100, 1 >
< 20, 201, 1 >
< 20, <NULL>, 2 >
< 30, 100, 1 >
< 30, 114, 5 >
< 30, <NULL>, 6 >
< 40, 101, 1 >
< 40, <NULL>, 1 >
10 rows found.

The following query returns the number of employees in each region, country and state or province. The rollup returns superaggregate rows for subtotals of all employees in each state or province and in each country and a grand total for all employees in the company. By combining the region and country as its own unit (within parenthesis), the rollup does not return all employees for each region.

Command> SELECT region_name AS Region,       >  country_name AS Country,       >  state_province AS State,       >  COUNT(employee_id) AS "Total Emp"       >  FROM regions r, countries c, locations l, departments d, employees e       >  WHERE r.region_id = c.region_id       >  AND l.country_id = c.country_id       >  AND d.location_id = l.location_id       >  AND d.department_id = e.department_id       >  GROUP BY rollup((region_name, country_name), state_province)       >  ORDER BY region_name;REGION, COUNTRY, STATE, TOTAL EMP< Americas, Canada, Ontario, 2 >< Americas, United States of America, Texas, 5 >< Americas, United States of America, California, 45 >< Americas, United States of America, Washington, 18 >< Americas, Canada, <NULL>, 2 >< Americas, United States of America, <NULL>, 68 >< Europe, Germany, Bavaria, 1 >< Europe, United Kingdom, <NULL>, 1 >< Europe, United Kingdom, Oxford, 34 >< Europe, Germany, <NULL>, 1 >< Europe, United Kingdom, <NULL>, 35 >< <NULL>, <NULL>, <NULL>, 106 >12 rows found. 

CUBE

The CUBE clause groups the selected rows based on the values of all possible combinations of the grouping columns in the CUBE clause. It returns a single row of summary information for each group. For example, three expressions (n=3) in the CUBE clause results in 2n = 23 = 8 groupings. Rows grouped on the values of n expressions are called regular rows; all others are called superaggregate rows. You can group using composite columns. For instance, a commonly requested CUBE operation is for state sales subtotals on all combinations of month, state, and product sold.

For instance, if you specify GROUP BY CUBE(a, b, c), the resulting aggregate groupings generated are as follows: (a,b,c), (a,b), (a,c), (b,c), a, b, c, ( ).

Example

To return the number of employees for each region and country, issue the following query:

Command> SELECT region_name AS Region,
       > country_name AS Country,
       > COUNT(employee_id) AS "Total Emp"
       > FROM regions r, countries c, locations l, departments d, employees e
       > WHERE r.region_id = c.region_id
       > AND l.country_id = c.country_id
       > AND d.location_id = l.location_id
       > AND d.department_id = e.department_id
       > GROUP BY CUBE(region_name, country_name)
       > ORDER BY region_name;
 
REGION, COUNTRY, TOTAL EMP
< Americas, Canada, 2 >
< Americas, United States of America, 68 >
< Americas, <NULL>, 70 >
< Europe, Germany, 1 >
< Europe, United Kingdom, 35 >
< Europe, <NULL>, 36 >
< <NULL>, Canada, 2 >
< <NULL>, Germany, 1 >
< <NULL>, United Kingdom, 35 >
< <NULL>, United States of America, 68 >
< <NULL>, <NULL>, 106 >
11 rows found.


TRUNCATE TABLE

The TRUNCATE TABLE statement is similar to a DELETE statement that deletes all rows. However, it is faster than DELETE in most circumstances, as DELETE removes each row individually.

Required privilege

No privilege is required for the table owner.

DELETE for another user's table.

SQL syntax

TRUNCATE TABLE [Owner.]TableName

Parameters

ParameterDescription
[Owner.]TableNameIdentifies the table to be truncated.

Description

  • TRUNCATE is a DDL statement and thus is controlled by the DDLCommitBehavior attribute. If DDLCommitBehavior=0 (the default), then a commit is performed before and after execution of the TRUNCATE statement. If DDLCommitBehavior=1, then TRUNCATE is part of a transaction and these transactional rules apply:

    • TRUNCATE operations can be rolled back.

    • Subsequent INSERT statements are not allowed in the same transaction as a TRUNCATE statement.

  • Concurrent read committed read operations are allowed, and semantics of the reads are the same as for read committed reads in presence of DELETE statements

  • TRUNCATE is allowed even when there are child tables. However, child tables need to be empty for TRUNCATE to proceed. If any of the child tables have any rows in them, TimesTen returns an error indicating that a child table is not empty.

  • TRUNCATE is not supported with any detail table of a materialized view, table that is a part of a cache group, or temporary table.

  • When a table contains out of line varying-length data, the performance of TRUNCATE TABLE is similar to that of DELETE statement that deletes all rows in a table. For more details on out-of line data, see "Numeric data types".

  • Where tables are being replicated, the TRUNCATE statement replicates to the subscriber, even when no rows are operated upon.

  • When tables are being replicated with timestamp conflict checking enabled, conflicts are not reported.

  • DROP TABLE and ALTER TABLE operations cannot be used to change hash pages on uncommitted truncated tables.

Examples

To delete all the rows from the recreation.clubs table, use:

TRUNCATE TABLE recreation.clubs;

See also


ALTER TABLE
DROP TABLE

UNLOAD CACHE GROUP

The UNLOAD CACHE GROUP statement deletes all rows from the cache group. The unload operation is local. It is not propagated across cache grid members.

Required privilege

No privilege is required for the cache group owner.

UNLOAD CACHE GROUP or UNLOAD ANY CACHE GROUP for another user's cache group.

SQL syntax

UNLOAD CACHE GROUP [Owner.]GroupName 
[WHERE ConditionalExpression]

or

UNLOAD CACHE GROUP [Owner.]GroupName 
WITH ID (ColumnValueList);

Parameters

ParameterDescription
[Owner.]GroupNameName assigned to the cache group.
ConditionalExpressionA search condition to qualify the target rows of the operation.
WITH ID ColumnValueListThe WITH ID clauses enables you to use primary key values to unload the cache instance. Specify ColumnValueList as either a list of literals or binding parameters to represent the primary key values.

Description

  • This statement causes the entire content of the cache group to be deleted from the database.

  • If the cache group is replicated, an UNLOAD CACHE GROUP statement deletes the entire contents of any replicated cache group as well.

  • Execution of the UNLOAD CACHE GROUP statement for an AWT cache group waits until updates on the rows have been propagated to the Oracle database.

  • The UNLOAD CACHE GROUP statement can be used for any type of cache group. For a description of cache group types, see "User managed and system managed cache groups".

  • Use the UNLOAD CACHE GROUP statement carefully with cache groups that have the AUTOREFRESH attribute. A row that is unloaded can reappear in the cache group as the result of an autorefresh operation if the row or its child rows are updated in Oracle Database.

  • Following the execution of an UNLOAD CACHE GROUP statement, the ODBC function SQLRowCount(), the JDBC method getUpdateCount(), and the OCI function OCIAttrGet() with the OCI_ATTR_ROW_COUNT argument return the number of cache instances that were unloaded.

  • Use the WITH ID clause to specify binding parameters.

Restrictions

  • Do not reference child tables in the WHERE clause.

  • Do not use the WITH ID clause on read-only cache groups or user managed cache groups with the autorefresh attribute unless the cache group is a dynamic cache group.

Examples

CREATE CACHE GROUP recreation.cache
    FROM recreation.clubs (
        clubname CHAR(15) NOT NULL,
        clubphone SMALLINT,
        activity CHAR(18),
        PRIMARY KEY(clubname))
    WHERE (recreation.clubs.activity IS NOT NULL);
UNLOAD CACHE GROUP recreation.cache;

See also


ALTER CACHE GROUP
CREATE CACHE GROUP
DROP CACHE GROUP
FLUSH CACHE GROUP
LOAD CACHE GROUP

UPDATE

The UPDATE statement updates the values of one or more columns in all rows of a table or in rows that satisfy a search condition.

Required privilege

No privilege is required for the table owner.

UPDATE for another user's table.

SQL syntax

UPDATE [FIRST NumRows] 
{[Owner.]TableName [CorrelationName]}
SET {ColumnName =
{Expression1 | NULL | DEFAULT}} [,...]
[ WHERE SearchCondition ]
RETURNING|RETURN Expression2[,...] INTO DataItem[,...]

Parameters

ParameterDescription
FIRST NumRowsSpecifies the number of rows to update. FIRST NumRows is not supported in subquery statements. NumRows must be either a positive INTEGER value or a dynamic parameter placeholder. The syntax for a dynamic parameter placeholder is either ? or :DynamicParameter. The value of the dynamic parameter is supplied when the statement is executed.
[Owner.]TableName [CorrelationName][Owner.]TableName identifies the table to be updated.

CorrelationName specifies an alias for the table and must conform to the syntax rules for a basic name according to "Basic names". When accessing columns of that table elsewhere in the UPDATE statement, use the correlation name instead of the actual table name. The scope of the correlation name is the SQL statement in which it is used.

All correlation names within one statement must be unique.

SET ColumnNameColumnName specifies a column to be updated. You can update several columns of the same table with a single UPDATE statement. Primary key columns can be included in the list of columns to be updated as long as the values of the primary key columns are not changed.
Expression1Any expression that does not contain an aggregate function. The expression is evaluated for each row qualifying for the update operation. The data type of the expression must be compatible with the data type of the updated column. Expression1 can specify a column or sequence CURRVAL or NEXTVAL reference when updating values. See "Incrementing SEQUENCE values with CURRVAL and NEXTVAL" for more details.
NULLPuts a NULL value in the specified column of each row satisfying the WHERE clause. The column must allow NULL values.
DEFAULTSpecifies that the column should be updated with the default value.
WHERE SearchConditionThe search condition can contain a subquery. All rows for which the search condition is true are updated as specified in the SET clause. Rows that do not satisfy the search condition are not affected. If no rows satisfy the search condition, the table is not changed.
Expression2Valid expression syntax. See Chapter 3, "Expressions".
DataItemHost variable or PL/SQL variable that stores the retrieved Expression2 value.

Description

  • If the WHERE clause is omitted, all rows of the table are updated as specified by the SET clause.

  • TimesTen generates a warning when a character or binary string is truncated during an UPDATE operation.

  • A table on which a unique constraint is defined cannot be updated to contain duplicate rows.

  • The UPDATE operation fails if it violates any foreign key constraint. See "CREATE TABLE" for a description of foreign key constraints.

  • Restrictions on the RETURNING clause:

    • Each Expression2 must be a simple expression. Aggregate functions are not supported.

    • You cannot return a sequence number into an OUT parameter.

    • ROWNUM and subqueries cannot be used in the RETURNING clause.

    • Parameters in the RETURNING clause cannot be duplicated anywhere in the UPDATE statement.

    • Using the RETURNING clause to return multiple rows requires PL/SQL BULK COLLECT functionality. See Oracle TimesTen In-Memory Database PL/SQL Developer's Guide.

    • In PL/SQL, you cannot use a RETURNING clause with a WHERE CURRENT operation.

Examples

The following example increases the price of parts costing more than $500 by 25 percent:

UPDATE purchasing.parts
SET salesprice = salesprice * 1.25
WHERE salesprice > 500.00;

This next example updates the column with the NEXTVAL value from sequence seq:

UPDATE student SET studentno = seq.NEXTVAL WHERE name = 'Sally';

The following query updates the status of all the customers who have at least one unshipped order:

UPDATE customers SET customers.status = 'unshipped'
WHERE customers.id = ANY
    (SELECT orders.custid FROM orders
        WHERE orders.status = 'unshipped');

The following statement updates all the duplicate orders, assuming id is not a primary key:

UPDATE orders a
    WHERE EXISTS (SELECT 1 FROM orders b
        WHERE a.id = b.id AND a.rowid < b.rowid);

This next example updates job_id, salary and department_id for an employee whose last name is'Jones' in the employees table. The values of salary, last_name and department_id are returned into variables.

Command> VARIABLE bnd1 NUMBER(8,2);
Command> VARIABLE bnd2 VARCHAR2(25) INLINE NOT NULL;
Command> VARIABLE bnd3 NUMBER(4);
Command> UPDATE employees SET job_id='SA_MAN', salary=salary+1000,
       > department_id=140 WHERE last_name='Jones'
       > RETURNING salary*0.25, last_name, department_id
       > INTO :bnd1, :bnd2, :bnd3;
1 row updated.
Command> PRINT bnd1 bnd2 bnd3;
BND1                 : 950
BND2                 : Jones
BND3                 : 140

Join update

TimesTen supports join update statements. A join update can be used to update one or more columns of a table using the result of a subquery.

Syntax

UPDATE [Owner.]TableName
SET ColumnName=Subquery
 [WHERE SearchCondition]

or

UPDATE [Owner.]TableName
SET (ColumnName[,...])=Subquery
 [WHERE SearchCondition]

Parameters

A join update statement has the following parameters:

ParameterDescription
[Owner.]TableNameIdentifies the table to be updated.
SET (ColumnName[,...])= SubquerySpecifies the column to be updated. You can update several columns of the same table with a single UPDATE statement. The SET clause can contain only one subquery, although this subquery can be nested.

The number of values in the select list of the subquery must be the same as the number of columns specified in the SET clause. An error is returned if the subquery returns more than one row for any updated row.

WHERE SearchConditionThe search condition can contain a subquery. All rows for which the search condition is true are updated as specified in the SET clause. Rows that do not satisfy the search condition are not affected. If no rows satisfy the search condition, the table is not changed.

Description

The subquery in the SET clause of a join update does not reduce the number of rows from the target table that are to be updated. The reduction must be specified using the WHERE clause. Thus if a row from the target table qualifies the WHERE clause but the subquery returns no rows for this row, this row is updated with a NULL value in the updated column.

Examples

In this example, if a row from t1 has no match in t2, then its x1 value in the first SELECT and its x1 and y1 values in the second SELECT are set to NULL.

UPDATE t1 SET x1=(SELECT x2 FROM t2 WHERE id1=id2);
UPDATE t1 SET (x1,y1)=(SELECT x2,y2 FROM t2 WHERE id1=id2);

In order to restrict the UPDATE statement to update only rows from t1 that have a match in t2, a WHERE clause with a subquery has to be provided as follows:

UPDATE t1 SET x1=(SELECT x2 FROM t2 WHERE id1=id2) 
  WHERE id1 IN (SELECT id2 FROM t2);
UPDATE t1 SET (x1,y1)=(SELECT x2,y2 FROM t2 WHERE id1=id2) 
  WHERE id1 IN (SELECT id2 FROM t2);

See also

SELECT

PKj PK*AOEBPS/privileges.htm Privileges

7 Privileges

When multiple users can access database objects, authorization can be controlled to these objects with privileges. Every object has an owner. Privileges control if a user can modify an object owned by another user. Privileges are granted or revoked either by the instance administrator, a user with the ADMIN privilege or, for privileges to a certain object, by the owner of the object.

The "Providing authorization to objects through privileges" section in the Oracle TimesTen In-Memory Database Operations Guide provides a detailed description of how to grant and revoke privileges for the different objects. In addition, the following sections provide a quick reference on all privileges that are required to perform TimesTen operations:

System privileges

A system privilege is the right to perform a particular action or to perform an action on any object of a particular type. Objects include tables, views, materialized views, synonyms, indexes, sequences, cache groups, replication schemes and PL/SQL functions, procedures and packages. Only the instance administrator or a user with ADMIN privilege can grant or revoke system privileges.

Table 7-1 System privileges

PrivilegeDescription

ADMIN

Enables a user to perform administrative tasks including checkpointing, backups, migration, and user creation and deletion.

ALTER ANY CACHE GROUP

Enables a user to alter any cache group in the database.

ALTER ANY INDEX

Enables a user to alter any index in the database.

Note: There is no ALTER INDEX statement.

ALTER ANY MATERIALIZED VIEW

Enables a user to alter any materialized view in the database.

Note: There is no ALTER MATERIALIZED VIEW statement.

ALTER ANY PROCEDURE

Enables a user to alter any PL/SQL procedure, function or package in the database.

ALTER ANY SEQUENCE

Enables a user to alter any sequence in the database.

Note: There is no ALTER SEQUENCE statement.

ALTER ANY TABLE

Enables a user to alter any table in the database.

ALTER ANY VIEW

Enables a user to alter any view in the database.

Note: There is no ALTER VIEW statement.

CACHE_MANAGER

Enables a user to perform operations related to cache groups.

CREATE ANY CACHE GROUP

Enables a user to create a cache group owned by any user in the database.

CREATE ANY INDEX

Enables a user to create an index on any table or materialized view in the database.

CREATE ANY MATERIALIZED VIEW

Enables a user to create a materialized view owned by any user in the database.

CREATE ANY PROCEDURE

Enables a user to create a PL/SQL procedure, function or package owned by any user in the database.

CREATE ANY SEQUENCE

Enables a user to create a sequence owned by any user in the database.

CREATE ANY SYNONYM

Enables a user to create a private synonym owned by any user in the database.

CREATE ANY TABLE

Enables a user to create a table owned by any user in the database.

CREATE ANY VIEW

Enables a user to create a view owned by any user in the database.

CREATE CACHE GROUP

Enables a user to create a cache group owned by that user.

CREATE MATERIALIZED VIEW

Enables a user to create a materialized view owned by that user.

CREATE PROCEDURE

Enables a user to create a PL/SQL procedure, function or package owned by that user.

CREATE PUBLIC SYNONYM

Enables a user to create a public synonym.

CREATE SEQUENCE

Enables a user to create a sequence owned by that user.

CREATE SESSION

Enables a user to create a connection to the database.

CREATE SYNONYM

Enables a user to create a private synonym.

CREATE TABLE

Enables a user to create a table owned by that user.

CREATE VIEW

Enables a user to create a view owned by that user.

DELETE ANY TABLE

Enables a user to delete from any table in the database.

DROP ANY CACHE GROUP

Enables a user to drop any cache group in the database.

DROP ANY INDEX

Enables a user to drop any index in the database.

DROP ANY MATERIALIZED VIEW

Enables a user to drop any materialized view in the database.

DROP ANY PROCEDURE

Enables a user to drop any PL/SQL procedure, function or package in the database.

DROP ANY SEQUENCE

Enables a user to drop any sequence in the database.

DROP ANY SYNONYM

Enables a user to drop a synonym owned by any user in the database.

DROP ANY TABLE

Enables a user to drop any table in the database.

DROP ANY VIEW

Enables a user to drop any view in the database.

DROP PUBLIC SYNONYM

Enables a user to drop a public synonym.

EXECUTE ANY PROCEDURE

Enables a user to execute any PL/SQL procedure, function or package in the database.

FLUSH ANY CACHE GROUP

Enables a user to flush any cache group in the database.

INSERT ANY TABLE

Enables a user to insert into any table in the database. It also enables the user to insert into any table using the synonym, public or private, to that table.

LOAD ANY CACHE GROUP

Enables a user to load any cache group in the database.

REFRESH ANY CACHE GROUP

Enables a user to flush any cache group in the database.

SELECT ANY SEQUENCE

Enables a user to select from any sequence or synonym on a sequence in the database.

SELECT ANY TABLE

Enables a user to select from any table, view, materialized view, or synonym in the database.

UNLOAD ANY CACHE GROUP

Enables a user to unload any cache group in the database.

UPDATE ANY TABLE

Enables a user to update any table, or synonym in the database.

XLA

Enables a user to connect to a database as an XLA reader.


Object privileges

An object privilege is the right to perform a particular action on an object or to access another user's object. Objects include tables, views, materialized views, indexes, synonyms, sequences, cache groups, replication schemes and PL/SQL functions, procedures and packages.

An object's owner has all object privileges for that object, and those privileges cannot be revoked. The object's owner can grant object privileges for that object to other database users. A user with ADMIN privilege can grant and revoke object privileges from users who do not own the objects on which the privileges are granted.

Table 7-2 Object privileges

PrivilegeObject typeDescription

DELETE

Table

Enables a user to delete from a table.

EXECUTE

PL/SQL package, procedure or function

Enables a user to execute a PL/SQL package, procedure or function directly.

FLUSH

Cache group

Enables a user to flush a cache group.

INDEX

Table or materialized view

Enables a user to create an index on a table or materialized view.

INSERT

Table or synonym

Enables a user to insert into a table or into the table through a synonym.

LOAD

Cache group

Enables a user to load a cache group

REFERENCES

Table or materialized view

Enables a user to create a foreign key dependency on a table or materialized view.

The REFERENCES privilege on a parent table implicitly grants SELECT privilege on the parent table.

REFRESH

Cache group

Enables a user to refresh a cache group

SELECT

Table, sequence, view, materialized view, or synonym

Enables a user to select from a table, sequence, view, materialized view, or synonym.

The SELECT privilege enables a user to perform all operations on a sequence.

A user can be granted the SELECT privilege on a synonym or a view without being explicitly granted the SELECT privilege on the originating table.

UNLOAD

Cache group

Enables a user to unload a cache group

UPDATE

Table

Enables a user to update a table


Privilege hierarchy

Some privileges confer other privileges. For example, ADMIN privilege confers all other privileges. The CREATE ANY TABLE system privilege confers the CREATE TABLE object privilege. Table 7-3 shows the privilege hierarchy.

Table 7-3 Privilege hierarchy

PrivilegeConfers these privileges

ADMIN

All other privileges including CACHE_MANAGER

CREATE ANY INDEX

INDEX ON (any table or materialized view)

CREATE ANY MATERIALIZED VIEW

CREATE MATERIALIZED VIEW

CREATE ANY PROCEDURE

CREATE PROCEDURE

CREATE ANY SEQUENCE

CREATE SEQUENCE

CREATE ANY SYNONYM

CREATE SYNONYM

CREATE ANY TABLE

CREATE TABLE

CREATE ANY VIEW

CREATE VIEW

DELETE ANY TABLE

DELETE (any table)

EXECUTE ANY PROCEDURE

EXECUTE (any procedure)

INSERT ANY TABLE

INSERT (any table)

SELECT ANY SEQUENCE

SELECT (any sequence)

SELECT ANY TABLE

SELECT (any table, view or materialized view)

UPDATE ANY TABLE

UPDATE (any table)


Cache group privileges have a separate hierarchy except that ADMIN confers the CACHE_MANAGER privilege.

The CACHE_MANAGER privilege confers these privileges:

  • CREATE ANY CACHE GROUP

  • ALTER ANY CACHE GROUP

  • DROP ANY CACHE GROUP

  • FLUSH ANY CACHE GROUP

  • LOAD ANY CACHE GROUP

  • UNLOAD ANY CACHE GROUP

  • REFRESH ANY CACHE GROUP

  • FLUSH (object)

  • LOAD (object)

  • UNLOAD (object)

  • REFRESH (object)

The CACHE_MANAGER privilege also includes the ability to start and stop the cache agent and the replication agent and to perform cache grid operations. The built-in procedures and utilities for these operations are documented in Oracle TimesTen In-Memory Database Reference.

CREATE ANY CACHE GROUP confers the CREATE CACHE GROUP privilege for any cache group.

The PUBLIC role

All users of the database have the PUBLIC role. In a newly created TimesTen database, by default PUBLIC has SELECT and EXECUTE privileges on various system tables and views and PL/SQL functions, procedures and packages. You can see the list of objects by using this query:

SELECT table_name, privilege FROM sys.dba_tab_privs WHERE grantee='PUBLIC';

Privileges that are granted to PUBLIC as part of database creation cannot be revoked. To see a list of these privileges, use this query:

SELECT table_name, privilege FROM sys.dba_tab_privs WHERE grantor='SYS';
PK+PK *Aoa,mimetypePK*AeJ[V:iTunesMetadata.plistPK*AYuMETA-INF/container.xmlPK*A[pTOOEBPS/cover.htmPK*A{U#P#OEBPS/whatsnew.htmPK*Acc(,OEBPS/types.htmPK*A\qsnEOEBPS/title.htmPK*A[))OEBPS/preface.htmPK*Ad~J99OEBPS/function.htmPK*AhЭޜʜ OEBPS/index.htmPK*A?^Y OEBPS/img/truthtable.gifPK*ALG OEBPS/img/tablecompress.gifPK*Ae1M"M9 OEBPS/express.htmPK*ArѦ$ OEBPS/img_text/truthtable.htmPK*AaGB ) OEBPS/img_text/tablecompress.htmPK*A 44/, OEBPS/reserved.htmPK*Ak ` OEBPS/toc.ncxPK*AhHC>k OEBPS/content.opfPK*A_ . OEBPS/dcommon/prodbig.gifPK*AY@  OEBPS/dcommon/doclib.gifPK*A{ss؍ OEBPS/dcommon/oracle-logo.jpgPK*A OEBPS/dcommon/contbig.gifPK*A OEBPS/dcommon/darbbook.cssPK*AMά""!  OEBPS/dcommon/O_signature_clr.JPGPK*APz 6+ OEBPS/dcommon/feedbck2.gifPK*A-, OEBPS/dcommon/feedback.gifPK*Aː53 OEBPS/dcommon/booklist.gifPK*AN615 OEBPS/dcommon/cpyr.htmPK*A!:3.G OEBPS/dcommon/masterix.gifPK*AeӺ1,H OEBPS/dcommon/doccd.cssPK*A7 qK OEBPS/dcommon/larrow.gifPK*A#M OEBPS/dcommon/indxicon.gifPK*AS'"P OEBPS/dcommon/leftnav.gifPK*Ahu,qQ OEBPS/dcommon/uarrow.gifPK*Al-OJT OEBPS/dcommon/oracle.gifPK*A(!] OEBPS/dcommon/index.gifPK*AGC g^ OEBPS/dcommon/bookbig.gifPK*AJV^h OEBPS/dcommon/rarrow.gifPK*A枰pkj OEBPS/dcommon/mix.gifPK*Ao"nR M Um OEBPS/dcommon/doccd_epub.jsPK*Av I w OEBPS/dcommon/toc.gifPK*A r~$=y OEBPS/dcommon/topnav.gifPK*A1FAz OEBPS/dcommon/prodicon.gifPK*A3( # 5~ OEBPS/dcommon/bp_layout.cssPK*Ax[?: OEBPS/dcommon/bookicon.gifPK*Ap*c^- OEBPS/dcommon/conticon.gifPK*Aʍؔ OEBPS/dcommon/blafdoc.cssPK*A+&׫ OEBPS/dcommon/rightnav.gifPK*Aje88J OEBPS/dcommon/oracle-small.JPGPK*Aއ{&! OEBPS/dcommon/help.gifPK*Ah͜>> OEBPS/names.htmPK*AbxF`7`&OEBPS/search.htmPK*AdTaJ\J ROEBPS/toc.htmPK*Aj OEBPS/state.htmPK*A+!OEBPS/privileges.htmPK77T_