Materialized views in PostgreSQL differ from the regular ones as they do
physically store the data in the database.
We’ve already covered how to create a regular view in PostgreSQL, so let’s talk about the key differences between materialized and regular views.
You can create a materialized view in PostgreSQL almost like the regular one.
The only thing that you need to add is the word
CREATE MATERIALIZED VIEW view_name AS
Follow up with the SELECT query and that’s it.
Materialized views do physically store data in the database.
This fact makes the access speed much faster as you don’t have to run the query every time.
On the other hand, you don’t get an instant update of the data and might end up in a situation where you’ve received an outdated set of results.
To refresh a materialized view you can run the following query:
REFRESH MATERIALIZED VIEW view_name;
Such refresh is similar to invalidating the cache and will synchronize the materialized view with the actual DB state.