UNION ALL on JSON data type UNION ALL on JSON data type json json

UNION ALL on JSON data type


It is not trivial to test whether JSON values are "equal". Among other things, attributes can be sorted in any order, or there can be any amount of insignificant white space. So the binary or text representation can be completely different while the value still qualifies as equal according to JSON specifications. That's why there is no equality operator for the data type json in PostgreSQL.

If you are satisfied with the text representations being equal (as it seems from the example) you could UNION ALL with a text column and cast to json later:

SELECT json_col::jsonFROM (   (SELECT '{"billingcode" : "' || billingcode || '"}'::text AS json_col    FROM   billing_2012_08 LIMIT 10)   UNION ALL   (SELECT '{"charged" : "' || charged || '"}'::text    FROM   sending_response_2012_08 LIMIT 10)   ) sub

Or you can use jsonb in Postgres 9.4 or later, which comes with the previously missing equality operator (among other things). See:

Then consider this alternative query:

SELECT to_jsonb(t) AS jsonb_colFROM  (SELECT billingcode FROM billing_2012_08 LIMIT 10) tUNIONSELECT to_jsonb(t)   -- also preserves possible numeric type!FROM  (SELECT charged FROM sending_response_2012_08 LIMIT 10) tORDER  BY 1;  -- possible with jsonb

In addition to UNION, ORDER BY is also possible now.

Note the use of to_jsonb(). By feeding it a row, column name(s) are used as key names automatically. This is cleaner and faster and (among other things) preserves possible numeric types, which can affect equality and sort order. (to_json() is also available.)

db<>fiddle here
Old sqlfiddle