Junior — Middle
Explain the concept of materialized views in PostgreSQL and their usage.
sobes.tech AI
Answer from AI
A materialized view in PostgreSQL is a database object that stores the result of a query as a physical table. Unlike a regular view, which is computed each time it is accessed, a materialized view stores data and allows for quick retrieval of results without re-computation.
Usage:
- Accelerating complex and resource-intensive queries, especially when data does not change frequently.
- Caching aggregated or joined data.
Features:
- Data in a materialized view is not automatically updated when the underlying tables change.
- To update the data, the REFRESH MATERIALIZED VIEW command must be executed.
Example of creation:
CREATE MATERIALIZED VIEW sales_summary AS
SELECT product_id, SUM(amount) AS total_sales
FROM sales
GROUP BY product_id;
Updating data:
REFRESH MATERIALIZED VIEW sales_summary;