Oracle Conversion Function - Oracle/PLSQL NVL Function






This Oracle tutorial explains how to use the Oracle/PLSQL NVL function.

The Oracle/PLSQL NVL function can substitute a value for a null value.

NVL() converts a null value to another value. The format of NVL is:

NVL(x, value)

NVL(x, Avalue) returns Avalue if x is null; otherwise x is returned.


select NVL(null, 'it is a null value') from dual;

Syntax

The syntax for the Oracle/PLSQL NVL function is:

NVL( string1, replace_with )

string1 is the string to test for a null value.

replace_with is the value returned if string1 is null.

The following SQL statement returns 'n/a' if the city field is a null value. Otherwise, it would return the city value.

SELECT NVL(city, 'n/a')
 FROM emp;

This SQL statement returns the name field if the desc contained a null value. Otherwise, it would return the desc.

SELECT id,
 NVL(desc, name)
 FROM emp;

The following SQL statement returns 0 if the salary field contained a null value. Otherwise, it would return the salary field.

SELECT NVL(salary, 0)
 FROM emp;




Example

Mark null value with a descriptive string:


CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
                  ENAME VARCHAR2(10),
                  JOB VARCHAR2(9),
                  SAL NUMBER(7, 2),
                  DEPTNO NUMBER(2));
-- from  w ww .j  a  v  a 2  s.  c o m
INSERT INTO EMP VALUES (1, null,    'CLERK',     800,    20);
INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1600,    30);
INSERT INTO EMP VALUES (3, 'WARD',  'SALESMAN', 1250,    30);
INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER',  2975,    20);
INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250,    30);
INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER',  2850,    30);
INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER',  2850,    10);
INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST',  3000,    20);
INSERT INTO EMP VALUES (9, 'KING',  'PRESIDENT',3000,    10);
INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500,    30);
INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK',    1500,    20);

SQL> SELECT empno, NVL(ename, 'Unknown')
  2  FROM emp;

     EMPNO NVL(ENAME,
---------- ----------
         1 Unknown
         2 ALLEN
         3 WARD
         4 JONES
         5 MARTIN
         6 BLAKE
         7 CLARK
         8 SCOTT
         9 KING
        10 TURNER
        11 ADAMS

11 rows selected.

SQL>
SQL>