SELECT CASE WHEN true THEN to_json(1) ELSE to_json('hello') END;
ERROR: could not determine polymorphic type because input has type "unknown"
SELECT to_json(CASE WHEN true THEN 1::text ELSE 'hello' END);
Do it the other way round:
SELECT CASE WHEN true THEN to_json(1) ELSE to_json(text 'hello') END;
I.e.: declare 'hello' as type
This way you retain
1 as number and
'hello' as string.
An explicit cast (
'hello'::text) does the trick, too. But it is slightly more efficient to declare the constant as
The reason is the Postgres type system. An unquoted
1 is a legal numeric constant and defaults to the Postgres data type
'hello' is just a string literal that starts out as type
unknown. The function
to_json() is polymorphic, that means it's input parameter is defined as
ANYELEMENT. What it actually does depends on the input data type. And it does not know what to do with data type
unknown. Hence the error message.
The result data type is
json in either case (which is a regular Postgres data type), but that is orthogonal to the problem.