Databases sql Intermediate

Rolling 30-day Aggregate View

Materialized view of daily module views for the last 30 days, refreshed hourly.

sql
CREATE MATERIALIZED VIEW daily_views_30d AS
  SELECT
    date_trunc('day', viewed_at) AS day,
    module_id,
    count(*) AS views
  FROM module_views
  WHERE viewed_at >= now() - interval '30 days'
  GROUP BY 1, 2;

CREATE UNIQUE INDEX ON daily_views_30d (day, module_id);

-- Refresh with CONCURRENTLY (no lock)
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_views_30d;

Prerequisites

  • PostgreSQL >= 14

Pro Tips

  • → Schedule the REFRESH via pg_cron or an application cron job.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
sql
Level
Intermediate
Read time
4 min
Published
Jan 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.