0

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?

1
  • 2
    For the result variable to be empty, the inner query you are running likely returned no results. You cannot COALESCE across zero rows. What you can probably do, however, is change your return statement to RETURN COALESCE(result, '{}'::json). Commented Mar 23, 2020 at 16:45

1 Answer 1

2

The problem is that the query returns no results, not that the result is NULL. One method is to aggregate the results -- because you can aggregate json -- and take the first value:

SELECT COALESCE( (array_agg(row_to_json(t)))[1], '{}'::json)
INTO result
FROM (SELECT id, foo, bar FROM myschema.mytable WHERE id = log_id) t;

RETURN result;

Alternatively, you could you conditional logic:

if not exists () then use '{}'::json
else use your query
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.