sqlintermediate

Create and Refresh Materialized Views

Use materialized views to cache expensive query results for fast reads.

sql
-- Create a materialized view
CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT
  DATE_TRUNC('month', order_date) AS month,
  product_category,
  SUM(total) AS revenue,
  COUNT(*) AS order_count
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY 1, 2;

-- Create index on the materialized view
CREATE INDEX idx_mv_month ON monthly_revenue (month);

-- Refresh the materialized view
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue;

-- Query it like a regular table
SELECT * FROM monthly_revenue
WHERE month >= '2025-01-01'
ORDER BY revenue DESC;

Use Cases

  • Dashboard caching
  • Expensive aggregation queries
  • Reporting performance

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.