Purpose
This function returns different values based on whether the input expression expr1 is null.
If
expr1is not null, it returns the value ofexpr2.If
expr1is null, it returns the value ofexpr3.
Syntax
NVL2(expr1, expr2, expr3)
Parameters
| Parameter | Description |
|---|---|
| expr1 | The first parameter. The data type can be any built-in data type in the database. |
| expr2 | The second parameter. The data type can be any built-in data type in the database. |
| expr3 | The third parameter. The data type can be any built-in data type in the database. |
Return type
If
expr1is null, andexpr3is also null, it returnsNULL. Ifexpr3is not null, the return type is described in the Considerations section below.If
expr1is not null, andexpr2is null, it returnsNULL. Ifexpr2is not null, the return type is described in the Considerations section below.Considerations
If the data types of
expr2andexpr3are different, the database implicitly converts one to the other. If the conversion is not possible, the database returns an error. Ifexpr2is a character or numeric type, the implicit conversion rules are as follows:- If
expr2is a character type, such asCHAR,NCHAR,NVARCHAR,VARCHAR2, orVARCHAR, OceanBase Database first convertsexpr3to the data type ofexpr2and then returns the value. Ifexpr3isNULL, no data type conversion is required, and the result is returned as aVARCHAR2type. - If
expr2is a numeric type, such asNUMBER,FLOAT,BINARY_FLOAT, orBINARY_DOUBLE, OceanBase Database determines which parameter has the highest numeric precedence, implicitly converts the other parameter to that data type, and returns the result in that data type.
- If
Examples
Create a table named tbl1 and insert five rows of data. Replace the null values in the col2 column with 100 and the non-null values with 50.
obclient> CREATE TABLE tbl1 (col1 INT,col2 INT);
Query OK, 0 rows affected
obclient> INSERT INTO tbl1 VALUES (1,30),(2,NULL),(3,50),(4,80),(5,10);
Query OK, 5 rows affected
Records: 5 Duplicates: 0 Warnings: 0
obclient> SELECT col1,NVL2(col2,50,100) FROM tbl1;
+------+-------------------+
| COL1 | NVL2(COL2,50,100) |
+------+-------------------+
| 1 | 50 |
| 2 | 100 |
| 3 | 50 |
| 4 | 50 |
| 5 | 50 |
+------+-------------------+
5 rows in set
