If I perform this simple query
SELECT *
FROM (
SELECT 'abc' AS name
UNION ALL
SELECT 'abc d' AS name
) AS test
ORDER BY name;
I get (as expected) the following result:
name
-------
abc
abc d
(2 rows)
i.e. the space character of string abc d is considered greater than the end of string of abc.
Till here everything is fine.
Next, if I try:
SELECT * FROM (
SELECT '{"name":"AbC"}'::JSON AS json
UNION ALL
SELECT '{"name":"aBc D"}'::JSON AS json
) AS test ORDER BY LOWER((json -> 'name')::TEXT);
I get:
json
------------------
{"name":"aBc D"}
{"name":"AbC"}
(2 rows)
this time the space character of string abc d is considered lesser than the end of string of abc!
I also tried with:
SELECT *
FROM (
SELECT 'abc'::TEXT AS name
UNION ALL SELECT 'abc d'::TEXT AS name
) AS test
ORDER BY name;
SELECT *
FROM (
SELECT 'abc' AS name
UNION ALL
SELECT 'abc d' AS name
) AS test
ORDER BY LOWER(name);
SELECT *
FROM (
SELECT 'abc'::TEXT AS name
UNION ALL
SELECT 'abc d'::TEXT AS name
) AS test
ORDER BY LOWER(name);
and all of them give the expected result.
I also tried:
SELECT * FROM (
SELECT '{"name":"abc"}'::JSON AS json
UNION ALL
SELECT '{"name":"abc d"}'::JSON AS json
) AS test
ORDER BY (json -> 'name')::TEXT;
which considers the space character lesser than the end of string as well.
It seems that the unexpected behavior is originated by the conversion of a string property of a JSON field to a (any?) postgres string type. I tried to search in PostrgeSQL documentation for a reason of this phenomenon but I wasn't able to.
Could somebody point me the documentation speaking about this? Or should we consider this a bug?