Skip to content

Materialized views in PostgreSQL store the result of a complex query physically, which can significantly speed up queries on large datasets. Refreshing them automatically keeps their data current without sacrificing that performance. This guide covers a few ways to set up automatic refreshes so a view reflects the latest database state.

What are materialized views in PostgreSQL?

Materialized views in PostgreSQL differ from regular views because they store query results physically. Standard views calculate their results each time you query them, while a materialized view only updates when you refresh it. Used well, materialized views improve your database’s response times.

Setting up automatic refresh

Automating refreshes keeps materialized views up to date without manual work. You can do this with cron jobs or PostgreSQL’s built-in event triggers, depending on your needs.

Using a cron job

A cron job can run the refresh at fixed intervals. To set one up:

  1. Enter the crontab editor by typing crontab -e in your terminal.
  2. Schedule the refresh operation. For daily refreshes at midnight, add the following line:
0 0 * * * psql -d your_database -c 'REFRESH MATERIALIZED VIEW your_materialized_view;'

This runs the refresh once a day.

Leveraging PostgreSQL event triggers

You can also use PostgreSQL event triggers to refresh a view automatically when certain database events occur. Set the triggers up to match your database’s needs so they don’t degrade performance unnecessarily.

Monitoring and optimizing refresh operations

Monitor your refresh operations to make sure they don’t slow down the rest of the database. If refreshes start taking longer, refine the underlying queries or adjust the schedule to fit your database’s workload.

Choose the refresh method that suits your operational requirements, and keep an eye on performance metrics once it’s running.

Written by

Robert Cooper avatar

Robert Cooper

Senior Software Engineer

Robert Cooper is a senior engineer who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.

View full author profile →

Basedash lets you build charts, dashboards, and reports in seconds using all your data.