BUG #4900: Query planner misses obvious optimization on ordered UNION DISTINCT - Mailing list pgsql-bugs

From Peter Headland
Subject BUG #4900: Query planner misses obvious optimization on ordered UNION DISTINCT
Date
Msg-id 200907050121.n651L3eM092244@wwwmaster.postgresql.org
Whole thread Raw
List pgsql-bugs
The following bug has been logged online:

Bug reference:      4900
Logged by:          Peter Headland
Email address:      pheadland@actuate.com
PostgreSQL version: 8.4.0
Operating system:   Windows
Description:        Query planner misses obvious optimization on ordered
UNION DISTINCT
Details:

Consider the following union:

SELECT a, b, c FROM t WHERE d = 1
UNION DISTINCT
SELECT a, b, c FROM t WHERE d = 2
ORDER BY b, c;

I have a table for which the plan for the above is ...->sort->unique->sort.
I infer that the first sort is a,b,c.

The obvious optimization is to reorder the columns used in the first sort to
eliminate the need for the second sort. To illustrate this, I change the
query to

SELECT b, c, a FROM t WHERE d = 1
UNION DISTINCT
SELECT b, c, a FROM t WHERE d = 2
ORDER BY b, c;

the plan now becomes ...->sort->distinct.

pgsql-bugs by date:

Previous
From: "Peter Headland"
Date:
Subject: BUG #4899: Open parenthesis breaks query plan
Next
From: "Peter Headland"
Date:
Subject: Re: BUG #4899: Open parenthesis breaks query plan