In PostgreSQL 11, I’d like to return a row in JSON format. But unfortunately, COALESCE(row_to_json(t), '{}'::json) still returns null:
CREATE OR REPLACE FUNCTION myschema.get_log(log_id int) RETURNS text AS $$
DECLARE
result text;
BEGIN
SELECT COALESCE(row_to_json(t), '{}'::json)
INTO result
FROM (SELECT id, foo, bar FROM myschema.mytable WHERE id = log_id) t;
RETURN result;
END;
$$ LANGUAGE plpgsql;
How can I return an empty JSON object if there is no row?
resultvariable to be empty, the inner query you are running likely returned no results. You cannotCOALESCEacross zero rows. What you can probably do, however, is change your return statement toRETURN COALESCE(result, '{}'::json).