Skip site navigation (1) Skip section navigation (2)

BUG #5564: Odd behavior with aggregate_func(DISTINCT foo ORDER BY foo)

From: "Daniel Grace" <dgrace(at)wingsnw(dot)com>
To: pgsql-bugs(at)postgresql(dot)org
Subject: BUG #5564: Odd behavior with aggregate_func(DISTINCT foo ORDER BY foo)
Date: 2010-07-17 00:07:53
Message-ID: 201007170007.o6H07rBP077265@wwwmaster.postgresql.org (view raw or flat)
Thread:
Lists: pgsql-bugs
The following bug has been logged online:

Bug reference:      5564
Logged by:          Daniel Grace
Email address:      dgrace(at)wingsnw(dot)com
PostgreSQL version: 9.0beta3
Operating system:   Windows XP 32-bit
Description:        Odd behavior with aggregate_func(DISTINCT foo ORDER BY
foo)
Details: 

(Apologies if there's a duplicate, I may have accidentally submitted too
early.  Tab+spacebar is a bad combination on browsers)

The manual states:
"If DISTINCT is specified in addition to an order_by_clause, then all the
ORDER BY expressions must match regular arguments of the aggregate; that is,
you cannot sort on an expression that is not included in the DISTINCT  list.
"

However, in some circumstances Postgres will fail  with "in an aggregate
with DISTINCT, ORDER BY expressions must appear in argument list" when the
same column is named in both places.  It appears to be related to cases when
the aggregate function in question requires implicit typecasts:

This test case fails with the above error:

DROP TABLE IF EXISTS foo;
CREATE TABLE foo (
	t VARCHAR
);

INSERT INTO foo (t) VALUES ('a'), ('a'), ('b'), ('b'), ('c');

SELECT STRING_AGG(DISTINCT t ORDER BY t) FROM foo;

However, if t is cast to text in both halves of the aggregate function, it
works correctly:

SELECT STRING_AGG(DISTINCT t::TEXT ORDER BY t::TEXT) FROM foo;

It also works correctly if t is defined as TEXT instead of VARCHAR in the
table definition.

Note that if t is typecast in the ORDER BY but not the DISTINCT part, the
statement still fails (even though STRING_AGG implicitly casts t to text)

Responses

pgsql-bugs by date

Next:From: Josh BerkusDate: 2010-07-18 14:40:33
Subject: auto-explain does not work with JSON & csvlog
Previous:From: Daniel GraceDate: 2010-07-17 00:04:08
Subject: BUG #5563: Odd behavior with aggregate_func(DISTINCT foo ORDER BY foo)

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group