In PostgreSQL, can I have an index on a non-materialized view?
I'm using a view in my application and it basically works well, but I'd like to speed up access to its data. I could switch to a materialized view, but I don't want to have to refresh it.
From http://postgresql.nabble.com/Indexes-not-allowed-on-read-only-views-Why-td4812152.html
in postgres, views are essentially macros, thus there is no data to index
and
A normal (non-materialized) view doesn't have any data of its own, it pulls it from one or more other tables on the fly during query execution. The execution of a view is kind of similar to a set-returning function or a subquery, almost as if you'd substituted the view definition into the original query.
That means that the view will use any indexes on the original table(s), but there isn't really even an opportunity to check for indexes on the view its self because the view's definition is effectively substituted into the query. If the view definition is complex enough that it does a lot of work where indexes on the original table(s) don't help, that work has to be done every time.
and
What you CAN do is use triggers to maintain your own materialized views as regular tables, and have indexes on the tables you maintain using triggers. This is widely discussed on the mailing list and isn't hard to do, though it's tricky to make updates perform well with some kinds of materialized view query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With