Views, Materialized Views & Stored Procedures
Encapsulate logic with views/MVs and understand when stored procedures help or hurt analytics.
In plain words
A view is a saved question the database answers fresh each time; a materialized view is a saved answer that must be updated.
Think of it like…
A view is a bookmark to a search (always shows current results, re-runs each time). A materialized view is a printed report (fast to read, but as old as the last print). A stored procedure is a recorded macro that someone else maintains.
Where you’ve seen it
Finance and marketing disagreed on monthly revenue by 3 percent. The data team created analytics.v_net_revenue (paid orders minus refunds, in IST months), pointed both dashboards at it, and built analytics.mv_revenue_daily refreshed hourly for the heavy dashboard. Model features read from the same view, so training data and reporting agree. The team keeps one stored procedure for nightly partition maintenance, but metric logic lives in version-controlled views.
Words you’ll hear
- View
- A stored SELECT that runs on every read; always current, no stored data.
- Materialized view
- A stored result set refreshed on demand or schedule; fast reads, possibly stale.
- Refresh
- Recomputing a materialized view (REFRESH MATERIALIZED VIEW, optionally CONCURRENTLY).
- Stored procedure
- Named, reusable database code with parameters and control flow, invoked with CALL.
Visual diagram
Theory & deep dive
Views and materialized views
CREATE VIEW v_net_revenue AS SELECT … FROM orders o LEFT JOIN refunds r … stores only the query; every read re-runs it with current data, and the optimiser usually inlines it into the outer query, so filters can be pushed down. Views give consistent definitions, hide complexity and can restrict columns for access control. Drawbacks: performance depends on the underlying tables, and stacked views obscure what's actually scanned.
CREATE MATERIALIZED VIEW mv_revenue_daily AS SELECT … ; REFRESH MATERIALIZED VIEW CONCURRENTLY mv_revenue_daily; stores the result so dashboards read a small table. In PostgreSQL a plain REFRESH recomputes everything and locks reads, while CONCURRENTLY (which needs a unique index) lets readers continue. Warehouses offer automatic or incremental maintenance (Snowflake, BigQuery and Redshift materialized views, dbt incremental models). Choose by freshness need: if data may be an hour old, materialise; if it must be current, keep a view or query the base tables.
CREATE MATERIALIZED VIEW mv_revenue_daily AS SELECT created_at::date AS day, SUM(amount) AS gross FROM orders GROUP BY 1; CREATE UNIQUE INDEX ON mv_revenue_daily (day); REFRESH MATERIALIZED VIEW CONCURRENTLY mv_revenue_daily;
Stored procedures and what belongs where
A stored procedure (CREATE PROCEDURE archive_old_events(cutoff date) …; CALL archive_old_events('2025-01-01');) runs inside the database, can loop, branch and commit in batches, and reduces round trips. It suits maintenance (partition management, archiving, refreshing summary tables). For analytics logic it's usually the wrong place: code in the database is hard to version, review and test, differs by dialect (PL/pgSQL, T-SQL, Snowflake Scripting), and hides dependencies from lineage tools.
A good rule for data teams: definitions in views or dbt models, heavy results in materialised or incremental tables, orchestration in a scheduler (Airflow, Dagster, cron), and procedures only for database-side maintenance. Whatever you use, document grain, owner and refresh schedule, add tests (unique keys, non-null, reconciliations), and check information_schema.views or the catalog when you inherit a database, because a dashboard may be reading a view you didn't know existed.
SELECT definition FROM pg_views WHERE viewname = 'v_net_revenue'; shows the SQL behind a view. Read it before using the metric, in particular the filters, time zone and refund treatment.
How it works, step by step
Step 1 of 41. Agree the metric definition
Write the definition (paid orders minus refunds, IST months) and its owner before coding it.
- One
- definition
When to use it & trade-offs
What it is
A view is a saved query that behaves like a table: it stores no data and runs its SELECT each time. A materialized view stores the query's result and must be refreshed, trading freshness for speed. A stored procedure is code kept in the database (SQL plus control flow) that you call by name. For analytics, views and materialized views are how teams share governed metric definitions (one definition of "active customer"), while stored procedures are better kept for maintenance jobs than for analysis logic.
Why it matters: Without shared definitions, five dashboards compute revenue five ways. Views fix that, and materialized views make heavy aggregates fast enough for dashboards. But each has costs: a view over a view over a view hides expensive plans, materialized views go stale, and logic hidden in stored procedures is hard to version, test and review. Data scientists need to know what they're reading from and how fresh it is.
When to reach for it
- Governed metrics shared by dashboards and models
- Hourly or daily summaries for BI
- Maintenance tasks such as archiving
When to avoid or be careful
- Business metric logic hidden in stored procedures
- Views stacked many levels deep
- Using a materialized view without knowing its refresh time
Views, materialized views and procedures
Strengths: No storage; always fresh; easy to change.
Watch out: Cost is paid at every read; chains hide complexity.
Strengths: Fast reads; stable results.
Watch out: Stale between refreshes; storage and refresh cost.
Strengths: Fewer round trips; transactional control.
Watch out: Hard to version and test; dialect-specific.
Interview signals & numbers to know
When this topic comes up
- “Finance and marketing report different revenue”
- “The dashboard is slow”
- “What does this view actually do?”
- Semantic layers and dbt
- Data freshness
Benchmarks & rules of thumb
- ≤ 1 hour
- staleness in the example
- 1
- definition per metric
- unique index
- required for CONCURRENTLY refresh in PostgreSQL
Common mistakes & follow-ups
Common interview mistakes
- Training a model on a materialized view that was last refreshed days ago.
- Building view on view on view, so a small query scans huge tables.
- Embedding the churn definition in a stored procedure that nobody reviewed.
Likely interviewer follow-ups
- When would you use a materialized view instead of a view?
- How do you make sure everyone uses the same metric definition?
- Why keep analytics logic out of stored procedures?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Views, Materialized Views & Stored Procedures with data science interview Q&A and hands-on practice.