IBM Books

SQL Getting Started


User-Defined Types

A distinct type is a user-defined data type that shares its internal representation with an existing type (its "source" type), but is considered to be separate and incompatible for most operations. For example, you might want to define an age type, a weight type, and a height type, all of which have quite different semantics, but which use the built-in data type INTEGER for their internal representations.

The following example illustrates the creation of a distinct type named PAY:

     CREATE DISTINCT TYPE PAY AS DECIMAL(9,2) WITH COMPARISONS

Although PAY has the same representation as the built-in data type DECIMAL(9,2), it is considered to be a separate type that is not comparable to DECIMAL(9,2) or to any other type. It is comparable only to the same distinct type. Also, operators and functions that would work on DECIMAL will not apply here. For example, a value with PAY data type cannot be multiplied with a value of INTEGER data type. Therefore, you have to write functions that only apply to the PAY data type.

Using distinct data types limits accidental mistakes. For instance, if the SALARY column of table EMPLOYEE was defined as a PAY data type, it could not be added to COMM even though their sourced types are the same.

Distinct data types support casting. A source type can be cast to a distinct data type, and a distinct data type to a source type. For example, if the SALARY column of the table EMPLOYEE were defined as a PAY data type, the following example would not fail at the comparison operator.

     SELECT * FROM EMPLOYEE 
        WHERE DECIMAL(SALARY) = 41250

DECIMAL(SALARY) returns a decimal data type. Inversely, a numeric data type can be cast to a PAY type. For example, you can cast the number 41250 by using PAY(41250).


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]

[ DB2 List of Books | Search the DB2 Books ]