Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have indexes on non-materialized views?

Tags:

postgresql

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.

like image 548
Nathan Long Avatar asked Dec 29 '16 21:12

Nathan Long


1 Answers

No

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.

like image 151
Nathan Long Avatar answered Nov 16 '22 04:11

Nathan Long