Why can't I select un-grouped columns when grouping by a (non-primary) unique key? - Mailing list pgsql-general

From Daniel Lenski
Subject Why can't I select un-grouped columns when grouping by a (non-primary) unique key?
Date
Msg-id CAOw_LSEzXc_pFk7W5bTRQ+6qy0wG8g0yX2s+i8TY1HF-LbZP3Q@mail.gmail.com
Whole thread Raw
Responses Re: Why can't I select un-grouped columns when grouping by a (non-primary) unique key?
List pgsql-general
If I include the primary key of a table in my GROUP BY clause, PG 9.3 allows me to refer to other columns of that table without explicit GROUP BY:

    CREATE TABLE A (id SERIAL PRIMARY KEY, name TEXT UNIQUE NOT NULL, document JSON);

    -- this works fine
    SELECT A.document
    FROM A
    GROUP BY A.primary_key

Why doesn't the same thing work with a non-NULL unique constraint?

    -- ERROR: column "A.document" must appear in the GROUP BY clause or be used in an aggregate function
    SELECT A.document
    FROM A
    GROUP BY A.name

I got thinking about this distinction because I wrote some very ugly SQL in a few cases, to get around the lack of JSON comparison operators in PG 9.3, before I discovered that it would work if I used the PRIMARY KEY instead:

    -- this works but it's ugly
    SELECT A.document::text::json
    FROM table
    GROUP BY A.non_null_unique_key, A.document::text

The manual refers to this situation (http://www.postgresql.org/docs/9.3/static/sql-select.html#SQL-GROUPBY), but I don't understand whether there's a specific reason to distinguish primary keys from non-NULL unique constraints.

Thanks,
Dan Lenski

pgsql-general by date:

Previous
From: Geoff Winkless
Date:
Subject: Re: [ADMIN] readonly user
Next
From: "Ilya I. Ashchepkov"
Date:
Subject: Re: JSONB spaces in text presentation