The following bug has been logged on the website:
Bug reference: 14136
Logged by: Sean
Email address: seandknutson@gmail.com
PostgreSQL version: 9.5.0
Operating system: Arch Linux
Description:
It seems that ordering is lost when doing a "select distinct" from a
materialized view.
Say I have a table called "test" that contains
id | name
----+-------
1 | steve
2 | adam
3 | jim
4 | steve
5 | adam
6 | sean
and a materialized view defined as
create materialized view view_test as (select * from test order by name);
If I run
select distinct name from view_test;
I get
name
-------
steve
adam
sean
jim
instead of
name
-------
adam
jim
sean
steve
like I'd expect. If I have a non-materialized view with the same definition,
the query returns
name
-------
adam
jim
sean
steve
as expected.
For simple cases, the workaround is relatively simple: just reapply the same
"order by" in the "select distinct.." query. E.g.
select distinct name from view_test order by name;
However, if the ordering defined in the mat view is complex, it may be
difficult to replicate, or even impossible (say if the order is based on a
column from a table that isn't included in the "select" part of the view
definition).