This can be radically simpler:
SELECT DISTINCT ON (b, c, e, f)
b, c, e, f, id -- add more columns freely
FROM (<duplicate query here>) sub
ORDER BY b, c, e, f, (a IS NOT NULL), id
Your duplicate query has all columns. No need to
JOIN
to the base table again.Use the Postgres extension of the standard SQL
DISTINCT
:DISTINCT ON
:Postgres has a proper boolean type. You can
ORDER BY
boolean expression directly. The sequence isFALSE
(0),TRUE
(1),NULL
(NULL). If a is NULL, this expression isFALSE
and sorts first:(a IS NOT NULL)
. The rest is ordered byid
. Voilá.Selection of
ID
happens automatically. According to your description you want the ID of the row selected in this query. Nothing more to do.You can probably integrate this into your duplicate query directly.