Volker Grabsch <vog@notjusthosting.com> writes:
> I'm confused about the absence of a very simple optimization
> in PostgreSQL. Suppose we have a VIEW where some columns are
> expensive to be calculated:
> CREATE VIEW a AS
> SELECT
> (... expensive calculation ...) as expensive,
> count(*) as cheap
> FROM
> x;
> where "x" is a sufficiently large table. I would expect the
> following query to be very fast:
> SELECT cheap FROM a;
> However, it takes the same time as "SELECT * FROM a;".
I think your main error is in supposing that count(*) is cheap ...
PG will suppress unused columns when a view can be flattened,
but typically not otherwise. In particular a view involving
aggregates won't get flattened; but given that the aggregates
will force a whole-table scan anyway, I can't get that excited
about removing a subset of them.
regards, tom lane