I'm currently learning PostgreSQL. However, I am a little bit confused about table, view, and materialized view. I understand the basic definitions as well as conceptions. But sometimes, I have a trouble to make a decision that I should create a table, a view, or materialized view. Would anyone share some experience how to apply it correctly? What are the pros and cons of one over the others?
Views are generally used when data is to be accessed infrequently and data in table get updated on frequent basis. On other hand Materialized Views are used when data is to be accessed frequently and data in table not get updated on frequent basis.
Because the data is pre-computed, querying a materialized view is faster than executing a query against the base table of the view. This performance difference can be significant when a query is run frequently or is sufficiently complex.
Materialized views are basically used to increase query performance since it contains results of a query. They should be used for reporting instead of a table for a faster execution.
A view is a database object that allows generating a logical subset of data from one or more tables. A table is a database object or an entity that stores the data of a database.
A table is where data is stored. You always start with tables first, and then your usage pattern dictates whether you need views or materialized views.
A view is like a stored query for future use, if you're frequently joining or filtering the same tables the same way in multiple places.
A materialized view is like a combination of both: it's a table that is automatically populated and refreshed via a view. You'd use this if you were using views, and want to pre-join or pre-aggregate the rows to speed up queries.
This article has a nice explanation on this part. Quoting from it,
When you query a TABLE, you fetch its data directly. On the other hand, when you query a VIEW, you are basically querying another query that is stored in the VIEW's definition.
...
Between the two there is MATERIALIZED VIEW - it's a VIEW that has a query in its definition and uses this query to fetch the data directly from the storage, but it also has it's own storage that basically acts as a cache in between the underlying TABLE(s) and the queries operating on the MATERIALIZED VIEW. It can be refreshed, just like an invalidated cache - a process that would cause its definition's query to be executed again against the actual data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With