Re: Select Distinct Order By Array_Position

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Mark Williams <markwillimas(at)gmail(dot)com>
Cc: pgsql-sql <pgsql-sql(at)lists(dot)postgresql(dot)org>
Subject: Re: Select Distinct Order By Array_Position
Date: 2018-11-26 19:46:22
Message-ID: CAKFQuwYroR1Q_+rF6odeDEA5+NLk6TjCYy-yTJUxf+ob7huhdg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, Nov 26, 2018 at 12:12 PM Mark Williams <markwillimas(at)gmail(dot)com> wrote:
> I am ordering by documents.id and it appears in my select list.
[...]
> SELECT DISTINCT documents.id, page_no FROM texts LEFT JOIN documents on documents.id=texts.doc_id WHERE doc_id IN (26194, 2345, 189) AND (text LIKE '%RIVER%') ORDER BY array_position(ARRAY[26194, 2345, 189]::INTEGER[], documents.id)

No, you are not ordering by documents.id, you are ordering by an
expression into which you are passing the documents.id value as one of
its components.

When you use ORDER BY and DISTINCT together you basically are short-handing:

SELECT sq.*
FROM (SELECT DISTINCT ...) AS sq
ORDER BY sq.?

If you want to order by something you have to include it exactly in
the select-list of the inner/distinct query.

In this example, though, you could just "ORDER BY documents.id DESC"...

David J.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Mark Williams 2018-11-26 19:58:37 RE: Select Distinct Order By Array_Position
Previous Message Rob Sargent 2018-11-26 19:20:14 Re: Select Distinct Order By Array_Position