DB2 10.5 for Linux, UNIX, and Windows

Expressions

An expression specifies a value. It can be a simple value, consisting of only a constant or a column name, or it can be more complex. When repeatedly using similar complex expressions, an SQL function to encapsulate a common expression can be considered.

Authorization

The use of some of the expressions, such as a scalar-subselect, sequence-reference, or function-invocation may require having the appropriate authorization. For these expressions, the privileges held by the authorization ID of the statement must include the following authorization:

In a Unicode database, an expression that accepts a character or graphic string will accept any string types for which conversion is supported.

Read syntax diagramSkip visual syntax diagram
expression

     .-operator--------------------------------------.     
     V                                (1)            |     
|------+-----+--+-function-invocation--------------+-+----------|
       +- + -+  +-(expression)---------------------+       
       '- - -'  |          (2)                     |       
                +-constant-------------------------+       
                +-column-name----------------------+       
                |          (3)                     |       
                +-variable-------------------------+       
                |                  (4)             |       
                +-special-register-----------------+       
                |                   (5)            |       
                +-scalar-fullselect----------------+       
                |                  (6)             |       
                +-labeled-duration-----------------+       
                |                 (7)              |       
                +-case-expression------------------+       
                |                    (8)           |       
                +-cast-specification---------------+       
                |                 (9)              |       
                +-field-reference------------------+       
                |                       (10)       |       
                +-xmlcast-specification------------+       
                |                             (11) |       
                +-array-element-specification------+       
                |                   (12)           |       
                +-array-constructor----------------+       
                |                       (13)       |       
                +-dereference-operation------------+       
                |                   (14)           |       
                +-method-invocation----------------+       
                |                    (15)          |       
                +-OLAP-specification---------------+       
                |                       (16)       |       
                +-row-change-expression------------+       
                |                    (17)          |       
                +-sequence-reference---------------+       
                |                   (18)           |       
                '-subtype-treatment----------------'       

operator

            (19)     
|--+-CONCAT------+----------------------------------------------|
   +- / ---------+   
   +- * ---------+   
   +- + ---------+   
   '- - ---------'   

Notes:
  1. See Function invocation for more information.
  2. See Constants for more information.
  3. See References to variables for more information.
  4. See Special registers for more information.
  5. See Scalar fullselect for more information.
  6. See Durations for more information.
  7. See CASE expression for more information.
  8. See CAST specification for more information.
  9. See Field reference for more information.
  10. See XMLCAST specification for more information.
  11. See ARRAY element specification for more information.
  12. See Array constructor for more information.
  13. See Dereference operation for more information.
  14. See Method invocation for more information.
  15. See OLAP specification for more information.
  16. See ROW CHANGE expression for more information.
  17. See Sequence reference for more information.
  18. See Subtype treatment for more information.
  19. || can be used as a synonym for CONCAT.

Expressions without operators

If no operators are used, the result of the expression is the specified value.

Examples:
   SALARY:SALARY'SALARY'MAX(SALARY)

Expressions with the concatenation operator

The concatenation operator (CONCAT) combines two operands to form a string expression.

The first operand is an expression that returns a value of any string data type, any numeric data type, or any datetime data type. The second operand is also an expression that returns a value of any string data type, any numeric data type, or any datetime data type. However, some data types are not supported in combination with the data type of the first operand, as described in the remainder of this section.

The operands can be any combination of string (except binary string), numeric, and datetime values. When any operand is a non-string value, it is implicitly cast to VARCHAR. A binary string can only be concatenated with another binary string. However, through the castable process of function resolution, a binary string can be concatenated with a character string defined as FOR BIT DATA when the first operand is the binary string.

Concatenation involving both character string operands and graphic string operands is supported only in a Unicode database. Character operands are first converted to the graphic data type before the concatenation. Character strings defined as FOR BIT DATA cannot be cast to the graphic data type.

If either operand can be null, the result can be null, and if either is null, the result is the null value. Otherwise, the result consists of the first operand string followed by the second. Note that no check is made for improperly formed mixed data when doing concatenation.

The length of the result is the sum of the lengths of the operands. In a Unicode database, the string unit of the result is the maximum string unit of the operands, as described in "Rules for result data types".

The data type and length attribute of the result is determined from that of the operands as shown in the following table unless an operand is defined with CODEUNITS32:

Table 1. Data Type and Length of Concatenated Operands
Operands Combined Length Attributes1 Result
CHAR(A) CHAR(B) <255 CHAR(A+B)
CHAR(A) CHAR(B) >254 VARCHAR(A+B)
CHAR(A) VARCHAR(B) <4001 VARCHAR(A+B)
CHAR(A) VARCHAR(B) >4000 LONG VARCHAR
CHAR(A) LONG VARCHAR - LONG VARCHAR
VARCHAR(A) VARCHAR(B) <4001 VARCHAR(A+B)
VARCHAR(A) VARCHAR(B) >4000 LONG VARCHAR
VARCHAR(A) LONG VARCHAR - LONG VARCHAR
LONG VARCHAR LONG VARCHAR - LONG VARCHAR
CLOB(A) CHAR(B) - CLOB(MIN(A+B, 2G))
CLOB(A) VARCHAR(B) - CLOB(MIN(A+B, 2G))
CLOB(A) LONG VARCHAR - CLOB(MIN(A+32K, 2G))
CLOB(A) CLOB(B) - CLOB(MIN(A+B, 2G))
GRAPHIC(A) GRAPHIC(B) <128 GRAPHIC(A+B)
GRAPHIC(A) GRAPHIC(B) >127 VARGRAPHIC(A+B)
GRAPHIC(A) VARGRAPHIC(B) <2001 VARGRAPHIC(A+B)
GRAPHIC(A) VARGRAPHIC(B) >2000 LONG VARGRAPHIC
GRAPHIC(A) LONG VARGRAPHIC - LONG VARGRAPHIC
VARGRAPHIC(A) VARGRAPHIC(B) <2001 VARGRAPHIC(A+B)
VARGRAPHIC(A) VARGRAPHIC(B) >2000 LONG VARGRAPHIC
VARGRAPHIC(A) LONG VARGRAPHIC - LONG VARGRAPHIC
LONG VARGRAPHIC LONG VARGRAPHIC - LONG VARGRAPHIC
DBCLOB(A) GRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
DBCLOB(A) VARGRAPHIC(B) - DBCLOB(MIN(A+B, 1G))
DBCLOB(A) LONG VARGRAPHIC - DBCLOB(MIN(A+16K, 1G))
DBCLOB(A) DBCLOB(B) - DBCLOB(MIN(A+B, 1G))
BLOB(A) BLOB(B) - BLOB(MIN(A+B, 2G))
Notes

1 The numbers specified for the Combined Length Attributes are listed in OCTETS for character strings and CODEUNITS16 for graphic strings. Refer to the next table if an operand is defined with CODEUNITS32.

If an operand is defined with CODEUNITS32, the other operand cannot be defined as FOR BIT DATA. Otherwise, when an operand is defined with CODEUNITS32, the data type and length attribute of the result is determined from that of the operands as shown in the following table:

Table 2. Data Type and Length of Concatenated Operands with CODEUNITS32
Operands Combined Length Attributes Result
CHAR(A) CHAR(B) <64 CHAR(A+B)
CHAR(A) CHAR(B) >63 VARCHAR(A+B)
CHAR(A) VARCHAR(B) - VARCHAR(MIN(A+B, 8168))
VARCHAR(A) VARCHAR(B) - VARCHAR(MIN(A+B, 8168))
CLOB(A) CHAR(B) - CLOB(MIN(A+B, 536870911))
CLOB(A) VARCHAR(B - CLOB(MIN(A+B, 536870911))
CLOB(A) CLOB(B) - CLOB(MIN(A+B, 536870911))
GRAPHIC(A) GRAPHIC(B) <64 GRAPHIC(A+B)
GRAPHIC(A) GRAPHIC(B) >63 VARGRAPHIC(A+B)
GRAPHIC(A) VARGRAPHIC(B) - VARGRAPHIC(MIN(A+B, 8168))
VARGRAPHIC(A) VARGRAPHIC(B) - VARGRAPHIC(MIN(A+B, 8168))
DBCLOB(A) CHAR(B) - DBCLOB(MIN(A+B, 536870911))
DBCLOB(A) VARCHAR(B) - DBCLOB(MIN(A+B, 536870911))
DBCLOB(A) DBCLOB(B) - DBCLOB(MIN(A+B, 536870911))

Note that, for compatibility with previous versions, there is no automatic escalation of results involving LONG VARCHAR or LONG VARGRAPHIC data types to LOB data types. For example, concatenation of a CHAR(200) value and a completely full LONG VARCHAR value would result in an error rather than in a promotion to a CLOB data type.

The code page of the result is considered a derived code page and is determined by the code page of its operands.

One operand may be a parameter marker. If a parameter marker is used, then the data type and length attributes of that operand are considered to be the same as those for the non-parameter marker operand. The order of operations must be considered to determine these attributes in cases with nested concatenation.

Example 1: If FIRSTNME is Pierre and LASTNAME is Fermat, then the following:
   FIRSTNME CONCAT ' ' CONCAT LASTNAME
returns the value Pierre Fermat.
Example 2:  Given:
  • COLA defined as VARCHAR(5) with value 'AA'
  • :host_var defined as a character host variable with length 5 and value 'BB   '
  • COLC defined as CHAR(5) with value 'CC'
  • COLD defined as CHAR(5) with value 'DDDDD'

The value of COLA CONCAT :host_var CONCAT COLC CONCAT COLD is 'AABB   CC   DDDDD'

The data type is VARCHAR, the length attribute is 17 and the result code page is the section code page. For more information about section code pages, see "Derivation of code page values".

Example 3: Given:
  • COLA defined as CHAR(10)
  • COLB defined as VARCHAR(5)
The parameter marker in the expression:
   COLA CONCAT COLB CONCAT ?
is considered VARCHAR(15), because COLA CONCAT COLB is evaluated first, giving a result that is the first operand of the second CONCAT operation.

User-defined types and the concatenation operator

A weakly typed distinct type is the only user-defined type that can be used with the concatenation operator. The source type of the weakly typed distinct type is used as the data type of the operand when processing the concatenation operator.

A strongly typed user-defined type cannot be used with the concatenation operator, even if it is a strongly typed distinct type with a source data type that is a string type. To concatenate, create a function with the CONCAT operator as its source. For example, if there were distinct types TITLE and TITLE_DESCRIPTION, both of which had VARCHAR(25) data types, the following user-defined function, ATTACH, can be used to concatenate them.
   CREATE FUNCTION ATTACH (TITLE, TITLE_DESCRIPTION)
     RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())
Alternately, the concatenation operator can be overloaded using a user-defined function to add the new data types.
   CREATE FUNCTION CONCAT (TITLE, TITLE_DESCRIPTION)
     RETURNS VARCHAR(50) SOURCE CONCAT (VARCHAR(), VARCHAR())

Expressions with arithmetic operators

If arithmetic operators are used, the result of the expression is a value derived from the application of the operators to the values of the operands.

If any operand can be null, or the database is configured with dft_sqlmathwarn set to yes, the result can be null.

If any operand has the null value, the result of the expression is the null value.

Arithmetic operators can be applied to signed numeric types and datetime types (see Datetime arithmetic in SQL). For example, USER+2 is invalid. When any operand of an arithmetic operation is a weakly typed distinct type, the operation is performed assuming that the data type of the operand is the source type of the weakly typed distinct type. Sourced functions can be defined for arithmetic operations on strongly typed distinct types with a source type that is a signed numeric type.

The prefix operator + (unary plus) does not change its operand. The prefix operator - (unary minus) reverses the sign of a nonzero non decimal floating-point operand. The prefix operator - (unary minus) reverses the sign of all decimal floating-point operands, including zero and special values; that is, signalling and non-signalling NaNs and plus and minus infinity. If the data type of A is small integer, the data type of -A is large integer. The first character of the token following a prefix operator must not be a plus or minus sign.

The infix operators +, -, *, and / specify addition, subtraction, multiplication, and division, respectively. The value of the second operand of division must not be zero, except if the calculation is performed using decimal floating-point arithmetic. These operators can also be treated as functions. Thus, the expression "+"(a,b) is equivalent to the expression a+b. "operator" function.

Operands with a character or graphic string data type, except LOBs, are converted to DECFLOAT(34) using the rules for CAST specification, before performing the arithmetic operation. For more information, see "Casting between data types". Note that arithmetic involving graphic string operands is supported only in a Unicode database.

Operands with a string data type are converted to DECFLOAT(34) using the rules for CAST specification before performing the arithmetic operation. For more information, refer to "Casting between data types". The string must contain a valid representation of a number.

Arithmetic errors

If an arithmetic error such as divide by zero or a numeric overflow occurs during the processing of an non-decimal floating-point expression, an error is returned (SQLSTATE 22003 or 22012). For decimal floating-point expressions, a warning is returned (SQLSTATEs 0168C, 0168D, 0168E, or 0168F) which depends on the nature of the arithmetic condition.

A database can be configured (using dft_sqlmathwarn set to yes) so that arithmetic errors return a null value for the non-decimal floating-point expression, the query returns a warning (SQLSTATE 01519 or 01564), and proceeds with processing the SQL statement.

For decimal floating-point expressions, dft_sqlmathwarn has no effect; arithmetic conditions return an appropriate value (possibly a decimal floating-point special value), the query returns a warning (SQLSTATEs 0168C, 0168D, 0168E, or 0168F), and proceeds with processing of the SQL statement. Special values returned include plus and minus infinity and not a number. Arithmetic expressions involving one or more decimal floating-point numbers never evaluate to a null value unless one or more of the arguments to the expression are null.

When arithmetic errors are treated as nulls, there are implications on the results of SQL statements. The following are some examples of these implications.

If these types of impacts are not acceptable, additional steps should be taken to handle the arithmetic error to produce acceptable results. Examples:
  • Add a case expression to check for zero divide and set the required value for such a situation
  • Add additional predicates to handle nulls (like a check constraint on not nullable columns could become:
       check (c1*c2 is not null and c1*c2>5000)
    to cause the constraint to be violated on an overflow).

Two integer operands

If both operands of an arithmetic operator are integers, the operation is performed in binary and the result is a large integer unless either (or both) operand is a big integer, in which case the result is a big integer. Any remainder of division is lost. The result of an integer arithmetic operation (including unary minus) must be within the range of the result type.

Integer and decimal operands

If one operand is an integer and the other is a decimal, the operation is performed in decimal using a temporary copy of the integer that has been converted to a decimal number with precision p and scale 0; p is 19 for a big integer, 11 for a large integer, and 5 for a small integer.

Two decimal operands

If both operands are decimal, the operation is performed in decimal. The result of any decimal arithmetic operation is a decimal number with a precision and scale that are dependent on the operation and the precision and scale of the operands. If the operation is addition or subtraction and the operands do not have the same scale, the operation is performed with a temporary copy of one of the operands. The copy of the shorter operand is extended with trailing zeros so that its fractional part has the same number of digits as the longer operand.

The result of a decimal operation must not have a precision greater than 31. The result of decimal addition, subtraction, and multiplication is derived from a temporary result which may have a precision greater than 31. If the precision of the temporary result is not greater than 31, the final result is the same as the temporary result.

Decimal arithmetic in SQL

The following formulas define the precision and scale of the result of decimal operations in SQL. The symbols p and s denote the precision and scale of the first operand, and the symbols p' and s' denote the precision and scale of the second operand.

Addition and subtraction

The precision is min(31,max(p-s,p'-s') +max(s,s')+1). The scale of the result of addition and subtraction is max (s,s').

Multiplication

The precision of the result of multiplication is min (31,p+ p') and the scale is min(31,s+s').

Division

The precision of the result of division is 31. The scale is 31-p+s-s'. The scale must not be negative.

Note: The min_dec_div_3 database configuration parameter alters the scale for decimal arithmetic operations involving division. If the parameter value is set to NO, the scale is calculated as 31-p+s-s'. If the parameter is set to YES, the scale is calculated as MAX(3, 31-p+ s-s'). This ensures that the result of decimal division always has a scale of at least 3 (precision is always 31).

Floating-point operands

If either operand of an arithmetic operator is floating-point, but not decimal floating-point, the operation is performed in floating-point. The operands are first converted to double-precision floating-point numbers, if necessary. Thus, if any element of an expression is a floating-point number, the result of the expression is a double-precision floating-point number.

An operation involving a floating-point number and an integer is performed with a temporary copy of the integer which has been converted to double-precision floating-point. An operation involving a floating-point number and a decimal number is performed with a temporary copy of the decimal number which has been converted to double-precision floating-point. The result of a floating-point operation must be within the range of floating-point numbers.

The order in which floating-point operands (or arguments to functions) are processed can slightly affect results because floating-point operands are approximate representations of real numbers. Since the order in which operands are processed may be implicitly modified by the optimizer (for example, the optimizer may decide what degree of parallelism to use and what access plan to use), an application that uses floating-point operands should not depend on the results being precisely the same each time an SQL statement is executed.

Decimal floating-point operands

If either operand of an arithmetic operator is decimal floating-point, the operation is performed in decimal floating-point.
Integer and decimal floating-point operands
If one operand is a small integer or large integer and the other is a DECFLOAT(n) number, the operation is performed in DECFLOAT(n) using a temporary copy of the integer that has been converted to a DECFLOAT(n) number. If one operand is a big integer, and the other is a decimal floating-point number, a temporary copy of the big integer is converted to a DECFLOAT(34) number. The rules for two-decimal floating-point operands then apply.
Decimal and decimal floating-point operands
If one operand is a decimal and the other is a decimal floating-point number, the operation is performed in decimal floating-point using a temporary copy of the decimal number that has been converted to a decimal floating-point number based on the precision of the decimal number. If the decimal number has a precision less than 17, the decimal number is converted to a DECFLOAT(16) number; otherwise, the decimal number is converted to a DECFLOAT(34) number. The rules for two-decimal floating-point operands then apply.
Floating-point and decimal floating-point operands
If one operand is a floating-point number (REAL or DOUBLE) and the other is a DECFLOAT(n) number, the operation is performed in decimal floating-point using a temporary copy of the floating-point number that has been converted to a DECFLOAT(n) number.
Two decimal floating-point operands
If both operands are DECFLOAT(n), the operation is performed in DECFLOAT(n). If one operand is DECFLOAT(16) and the other is DECFLOAT(34), the operation is performed in DECFLOAT(34).

General arithmetic operation rules for decimal floating-point

The following general rules apply to all arithmetic operations on the decimal floating-point data type:
  • Every operation on finite numbers is carried out as though an exact mathematical result is computed, using integer arithmetic on the coefficient, where possible.

    If the coefficient of the theoretical exact result has no more than the number of digits that reflect its precision (16 or 34), it is used for the result without change (unless there is an underflow or overflow condition). If the coefficient has more than the number of digits that reflect its precision, it is rounded to exactly the number of digits that reflect its precision (16 or 34), and the exponent is increased by the number of digits that are removed.

    The CURRENT DECFLOAT ROUNDING MODE special register determines the rounding mode.

    If the value of the adjusted exponent of the result is less than Emin, the calculated coefficient and exponent form the result, unless the value of the exponent is less than Etiny, in which case the exponent is set to Etiny, the coefficient is rounded (possibly to zero) to match the adjustment of the exponent, and the sign remains unchanged. If this rounding gives an inexact result, an underflow exception condition is returned.

    If the value of the adjusted exponent of the result is larger than Emax, an overflow exception condition is returned. In this case, the result is defined as an overflow exception condition and might be infinite. It has the same sign as the theoretical result.

  • Arithmetic that uses the special value infinity follows the usual rules, where negative infinity is less than every finite number and positive infinity is greater than every finite number. Under these rules, an infinite result is always exact. Certain uses of infinity return an invalid operation condition. The following list shows the operations that can cause an invalid operation condition. The result of such an operation is NaN when one of the operands is infinity but the other operand is not NaN or sNaN.
    • Add +infinity to -infinity during an addition or subtraction operation
    • Multiply 0 by +infinity or -infinity
    • Divide either +infinity or -infinity by either +infinity or -infinity
    • Either argument of the QUANTIZE function is +infinity or -infinity
    • The second argument of the POWER function is +infinity or -infinity
    • Signaling NaNs used as operands to arithmetic operations
    The following rules apply to arithmetic operations and the NaN value:
    • The result of any arithmetic operation that has a NaN (quiet or signalling) operand is NaN. The sign of the result is copied from the first operand that is a signalling NaN; if neither operand is signalling, the sign is copied from the first operand that is a NaN. Whenever a result is a NaN, the sign of the result depends only on the copied operand.
    • The sign of the result of a multiplication or division operation is negative only if the operands have different signs and neither is a NaN.
    • The sign of the result of an addition or subtraction operation is negative only if the result is less than zero and neither operand is a NaN, except for the following cases where the result is a negative 0:
      • A result is rounded to zero, and the value, before rounding, had a negative sign
      • 0 is subtracted from -0
      • Operands with opposite signs are added, or operands with the same sign are subtracted; the result has a coefficient of 0, and the rounding mode is ROUND_FLOOR
      • Operands are multiplied or divided, the result has a coefficient of 0, and the signs of the operands are different
      • The first argument of the POWER function is -0, and the second argument is a positive odd number
      • The argument of the CEIL, FLOOR, or SQRT function is -0
      • The first argument of the ROUND or TRUNCATE function is -0
The following examples show special decimal floating-point values as operands:
   INFINITY + 1          = INFINITY
   INFINITY + INFINITY   = INFINITY
   INFINITY + -INFINITY  = NAN         -- warning
   NAN + 1               = NAN
   NAN + INFINITY        = NAN
   1 - INFINITY          = -INFINITY
   INFINITY - INFINITY   = NAN         -- warning
   -INFINITY - -INFINITY = NAN         -- warning
   -0.0 - 0.0E1          = -0.0
   -1.0 * 0.0E1          = -0.0
   1.0E1 / 0             = INFINITY    -- warning
   -1.0E5 / 0.0          = -INFINITY   -- warning
   1.0E5 / -0            = -INFINITY   -- warning
   INFINITY / -INFINITY  = NAN         -- warning
   INFINITY / 0          = INFINITY
   -INFINITY / 0         = -INFINITY
   -INFINITY / -0        = INFINITY

User-defined types as operands of arithmetic operators

Weakly typed distinct type operands can be used with arithmetic operators, provided that source type of the weakly typed distinct type is supported by the arithmetic operator. There is no need to create additional user-defined functions to support arithmetic operations for weakly typed distinct type operands.

A strongly typed user-defined type cannot be used with arithmetic operators, even if its source data type is numeric. To perform an arithmetic operation, create a function with the arithmetic operator as its source. For example, if there were strongly typed distinct types INCOME and EXPENSES, both of which had DECIMAL(8,2) data types, then the following user-defined function, REVENUE, could be used to subtract one from the other.
   CREATE FUNCTION REVENUE (INCOME, EXPENSES)
     RETURNS DECIMAL(8,2) SOURCE "-" (DECIMAL, DECIMAL)
Alternately, the - (minus) operator could be overloaded using a user-defined function to subtract the new data types.
   CREATE FUNCTION "-" (INCOME, EXPENSES)
     RETURNS DECIMAL(8,2) SOURCE "-" (DECIMAL, DECIMAL)

Precedence of operations

Expressions within parentheses and dereference operations are evaluated first from left to right. (Parentheses are also used in fullselects, search conditions, and functions. However, they should not be used to arbitrarily group sections within SQL statements.) When the order of evaluation is not specified by parentheses, prefix operators are applied before multiplication and division, and multiplication and division are applied before addition and subtraction. Operators at the same precedence level are applied from left to right.

Figure 1. Precedence of Operations
sqls0opr

Scalar fullselect

Read syntax diagramSkip visual syntax diagram
Scalar fullselect

|--(--fullselect--)---------------------------------------------|

A scalar fullselect is a fullselect, enclosed in parentheses, that returns a single row consisting of a single column value. If the fullselect does not return a row, the result of the expression is the null value. If the select list element is an expression that is simply a column name or a dereference operation, the result column name is based on the name of the column. The authorization required for a scalar fullselect is the same as that required for an SQL query.