How many arguments does COALESCE accept?

coalesce, oracle, sql

Solution

Tested on Oracle 10g.

DECLARE
    cur SYS_REFCURSOR;
    vQuery VARCHAR2(32000) := 'SELECT COALESCE(:NULLS) FROM dual';
    vNulls VARCHAR2(32000) := '1, 1';
    i PLS_INTEGER := 2;
BEGIN
    LOOP
        OPEN cur FOR REPLACE (vQuery, ':NULLS', vNulls);
        CLOSE cur;

        i := i + 1;
        vNulls := vNulls || ', 1';
    END LOOP;
    EXCEPTION
        WHEN OTHERS THEN
            DBMS_OUTPUT.PUT_LINE(i || ' ' || SQLERRM);
END;

256 ORA-00939: too many arguments for function

So, the answer is `256`

EDIT: As suggested by Bob Duell:

SELECT func_id, name, minargs, maxargs 
FROM V$SQLFN_METADATA
WHERE name = 'COALESCE'

FUNC_ID NAME        MINARGS MAXARGS 
387     COALESCE    2       0   

:(

EDIT:

The limit on 11.2.0.3 appears to be 65,535.

The above script will not work with that many arguments. You can test the limit by creating and running a very large SQL statement, with a script like the one below.

--Create a COALESCE with 65,536 functions.
--It will fail with: ORA-00939: too many arguments for function
--But if you remove the last argument it will work, at least on 11.2.0.3.
--WARNING: Sending this much data through DBMS_OUTPUT may freeze some tools.
begin
    dbms_output.put_line('select coalesce(');
    for i in 1 .. 6553 loop
        dbms_output.put_line('1,2,3,4,5,6,7,8,9,0,');
    end loop;
    dbms_output.put_line('1,2,3,4,5,6');
    dbms_output.put_line(') from dual;');
end;
/

Problem

I couln't find this in SO and thought it might be worth finding it here as the oracle documentation doesn't specify it. http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm

Original source