Re: BUG #18564: Incorrect sorting with using NULLS LAST (NULLS FIRST)

From: "Daniel Verite" <daniel(at)manitou-mail(dot)org>
To: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: sunnybluemoon050(at)gmail(dot)com,pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #18564: Incorrect sorting with using NULLS LAST (NULLS FIRST)
Date: 2024-08-02 12:04:24
Message-ID: 722b943c-42e7-4386-957a-312808f6e38c@manitou-mail.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

David G. Johnston wrote:

> In short, while this can be controlled at the SQL scope, the comparison
> operator for the json data type provides no such ability for the user to
> control the result of the comparison between null and non-null json
> values.

It looks like a good use case for NULLIF.

SELECT example_jsonb_column->'sorting_param'
FROM example_table
ORDER BY NULLIF(example_jsonb_column->'sorting_param', 'null'::jsonb)
ASC NULLS LAST ;

The doc says that primitive JSON values are compared using the same
comparison rules as for the underlying PostgreSQL data type, so the
non-null values will be sorted as "numeric", which meets the OP's
expectations:

> Expected Behavior:
> NULL values should appear at the end of the sorted results, and the sorting
> should be accurate based on the numeric values.

Best regards,
--
Daniel Vérité
https://postgresql.verite.pro/
Twitter: @DanielVerite

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message David Rowley 2024-08-02 14:14:20 Re: BUG #18558: ALTER PUBLICATION fails with unhelpful error on attempt to use system column
Previous Message Ware, Christopher M. (LARC-D318)[RSES] 2024-08-02 11:38:55 RE: [EXTERNAL] Re: BUG #18528: Installer displays error when installing