CAST

CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value.

CAST lets you convert built-in datatypes or collection-typed values of one type into another built-in datatype or collection type. You can cast an unnamed operand (such as a date or the result set of a subquery) or a named collection (such as a varray or a nested table) into a type-compatible datatype or named collection. The type_name must be the name of a built-in datatype or collection type and the operand must be a built-in datatype or must evaluate to a collection value.

For the operand, expr can be either a built-in datatype, a collection type, or an instance of an AnyData type. If expr is an instance of an AnyData type, CAST will try to extract the value of the AnyData instance and return it if it matches the cast target type, otherwise, null will be returned. MULTISET informs Oracle Database to take the result set of the subquery and return a collection value. Table 7-1 shows which built-in datatypes can be cast into which other built-in datatypes. (CAST does not support LONG, LONGRAW, any of the LOB datatypes, or the Oracle-supplied types.)

Table 7-1 Casting Built-In Datatypes

from BINARY_FLOAT, BINARY_DOUBLE

from CHAR, VARCHAR2

fromNUMBER

from DATETIME / INTERVAL (Note 1)

fromRAW

from ROWID, UROWID (Note 2)

from NCHAR, NVARCHAR2

to BINARY_FLOAT, BINARY_DOUBLE

X

X

X

—

—

—

X

to CHAR, VARCHAR2

X

X

X

X

X

X

—

to NUMBER

X

X

X

—

—

—

X

to DATE, TIMESTAMP, INTERVAL

—

X

—

X

—

—

—

to RAW

—

X

—

—

X

—

—

to ROWID, UROWID

—

X

—

—

—

Xa

—

to NCHAR, NVARCHAR2

X

—

X

X

X

X

X

Note 1: Datetime/interval includes DATE, TIMESTAMP, TIMESTAMP WITH TIMEZONE, INTERVAL DAY TO SECOND, and INTERVAL YEAR TO MONTH.

Note 2: You cannot cast a UROWID to a ROWID if the UROWID contains the value of a ROWID of an index-organized table.

If you want to cast a named collection type into another named collection type, then the elements of both collections must be of the same type.

If the result set of subquery can evaluate to multiple rows, then you must specify the MULTISET keyword. The rows resulting from the subquery form the elements of the collection value into which they are cast. Without the MULTISET keyword, the subquery is treated as a scalar subquery.

Built-In Datatype Examples

The following examples use the CAST function with scalar datatypes:

SELECT CAST('22-OCT-1997' AS TIMESTAMP WITH LOCAL TIME ZONE)
FROM dual;
SELECT product_id,
CAST(ad_sourcetext AS VARCHAR2(30))
FROM print_media;

Collection Examples

The CAST examples that follow build on the cust_address_typ found in the sample order entry schema, oe.