Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 33/ 160
02. SQL & Data Engineering Basics

Views, Materialized Views & Stored Procedures

Encapsulate logic with views/MVs and understand when stored procedures help or hurt analytics.

IntermediateViews · Materialized Views3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

A materialised daily table

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;

Key takeaway: Views share definitions; materialized views share results at the cost of staleness.

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.

Discovering what a view does

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.

Key takeaway: Metrics in versioned views or models; procedures for maintenance; document and test everything.

How it works, step by step

Step 1 of 4
Stakeholders

1. Agree the metric definition

Write the definition (paid orders minus refunds, IST months) and its owner before coding it.

net revenue = paid − refunds
Key numbers at this step
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

View
Best for: Shared definitions that must be current

Strengths: No storage; always fresh; easy to change.

Watch out: Cost is paid at every read; chains hide complexity.

Materialized view / incremental table
Best for: Heavy aggregates for dashboards and features

Strengths: Fast reads; stable results.

Watch out: Stale between refreshes; storage and refresh cost.

Stored procedure
Best for: Database-side maintenance and batch jobs

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?
Interview tip: Always state the freshness trade-off: "view if it must be current, materialized if an hour old is fine". Then mention versioning definitions.

Knowledge check

Loading quiz

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.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Date/Time & String Functions in SQL
Next topic
Database Indexing & Query Execution Plans