Search code examples
postgresqldatabase-administration

Using views in postgresql to enable transparent replacement of backing tables


We have a view that aggregates from a backing table. The idea is to reduce cpu load by using a pre-aggregated table, and to periodically refresh it with the following:

  • create new_backing_table (fill it)
  • begin
  • drop backingtable
  • rename new_backingtable to backingtable
  • commit

while in production. The latency caused by the refresh interval is acceptable. Incremental updates are possible but not desirable.

Anyone has a comment on this scheme ?


Solution

  • Check out materialized views. This may suit your use case. It can be used to store query results at creation then refreshed at a later time.

    A materialized view is defined as a table which is actually physically stored on disk, but is really just a view of other database tables. In PostgreSQL, like many database systems, when data is retrieved from a traditional view it is really executing the underlying query or queries that build that view.

    https://www.postgresql.org/docs/9.3/static/sql-creatematerializedview.html