tags:

views:

44

answers:

2

Are views in PostgreSQL completely recalculated every time one of underneath tables are changed?

More precisely, if I have aggregate view over table votes, will complete recalculation of a view be needed, when any changes are made in votes table?

If I expect often changes of votes table, what are alternatives to aggregate view? I need polylogarithmic time complexity of simple querys.

A: 

You could use PostgreSQL's Materialized views.

Materialized views are certainly possible in PostgreSQL. Because of PostgreSQL's powerful PL/pgSQL language, and the functional trigger system, materialized views are somewhat easy to implement. I will examine several methods of implementing materialized views in PostgreSQL.

link text

tinychen
Postgres doesn't have native Materialized View syntax, and this doesn't address the OP's question either...
OMG Ponies
+1  A: 

Normal VIEWS in Postgres (and other RDBMS's that I'm aware of) are really nothing more than a stored SELECT statement. Its not storing the actual information in a static table - thats a materialized VIEW (which Postgres doesn't currently have, and you'll have to roll your own). It will in a sense "recalculate every time", in that it doesn't store the calculated data.

Check the previous link for how to do a materialized view if you want to store the complex calculations.

EDIT: If like OMG Ponies says, you're talking about ALTER TABLE on the underlying table - then its easy...Postgres won't let you change the definition of a column that used in a VIEW without dropping the VIEW first.

rfusca
+1: I agree that views are stored SELECTs, but the OP is asking about if they run an ALTER TABLE statement to add/edit a column - will the PostgreSQL view stay in sync? Assume `SELECT *...` - least, that's why I read the question.
OMG Ponies
I didn't think he was talking about ALTER TABLE, I thought it was just talking about changing the data in the table.
rfusca
Yes, I was talking about changing the data in the table.
stralep