Coalesce in oracle

COALESCE returns first not null value out of all the parameters passed into this function. NOTE: All the parameters have been the same datatype

DROP TABLE coalesce_func_test;

CREATE TABLE coalesce_func_test
(
   id     NUMBER,
   col1   VARCHAR2 (10),
   col2   VARCHAR2 (10),
   col3   VARCHAR2 (10),
   col4   NUMBER
);

Sample Data

SET DEFINE OFF;

INSERT INTO coalesce_func_test (id,
                                col1,
                                col2,
                                col3,
                                col4)
     VALUES (1,
             10,
             20,
             30,
             40);

INSERT INTO coalesce_func_test (id,
                                col1,
                                col2,
                                col3)
     VALUES (2,
             31,
             32,
             33);

INSERT INTO coalesce_func_test (id,
                                col1,
                                col2,
                                col4)
     VALUES (3,
             41,
             42,
             43);

INSERT INTO coalesce_func_test (id,
                                col1,
                                col3,
                                col4)
     VALUES (4,
             51,
             53,
             54);

INSERT INTO coalesce_func_test (id,
                                col2,
                                col3,
                                col4)
     VALUES (5,
             72,
             73,
             74);

COMMIT;
IDCOL1COL2COL3COL4
110203040
2313233
3414243
4515354
5727374

Try it

SELECT dt.*,
       COALESCE (col1,
                 col2,
                 col3,
                 col4) COALESCE
  FROM coalesce_func_test dt
ORDER BY 1;

All the Columns have to be same data type
ORA-00932: inconsistent datatypes: expected CHAR got NUMBER

SELECT dt.*,
       COALESCE (col1,
                 col2,
                 col3,
                 to_char(col4)) COALESCE
  FROM coalesce_func_test dt
ORDER BY 1;
IDCOL1COL2COL3COL4COALESCE
11020304010
231323331
341424341
451535451
572737472
  • If we have only 2 parameters, then COALESCE works like NVL.

Oracle Functions