Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

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
SQL topics
Lesson 110/ 160
06. Database Design, Normalization & Semi-Structured SQL

Views: Creating Virtual Tables for Security & Simplicity

Expose curated query interfaces with views for security and reuse.

BeginnerCREATE VIEW · Abstraction3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A view is a saved question. When you look at it, the database answers the question again using the latest data.

Think of it like…

A saved filter in your email app: "unread from my manager" doesn't copy any emails, it just shows the matching ones each time you open it.

Where you’ve seen it

CREATE VIEW customer_contacts AS SELECT id, name, city FROM customers WHERE deleted_at IS NULL; then GRANT SELECT ON customer_contacts TO support_team;. Support can look up customers, but never sees email, phone or deleted accounts.

Words you’ll hear

View
A named, stored query; no stored data.
Materialized view
A view whose results are stored and must be refreshed.
Updatable view
A simple single-table view you can INSERT, UPDATE or DELETE through.
security_barrier / security_invoker
PostgreSQL options that make views safer as security boundaries.

Visual diagram

Loading interactive diagram

Theory & example queries

What a view is good for

Abstraction: a view gives one agreed definition of a business concept (active customers, net revenue) so every report uses the same logic, and you can change the underlying tables while keeping the view's columns stable for its users.

Security: grant SELECT on the view, not the base tables, to expose only certain columns or rows. In PostgreSQL, add WITH (security_barrier) for row-filtering views so cleverly written functions in user queries can't leak hidden rows, and from PostgreSQL 15, security_invoker makes the view check the caller's own permissions on the base tables.

One definition of net revenueQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE VIEW net_revenue_daily AS2SELECT3  created_at::date AS DAY,4  SUM(amount) - COALESCE(SUM(refund_amount), 0) AS net5FROM6  orders7WHERE8  status IN ('paid', 'refunded')9GROUP BY10  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
View creation status
CREATE VIEW

Note: Representative PostgreSQL response; the grouped revenue is computed only when the view is queried.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Views centralise logic and limit what users can see.

Performance and maintenance

A normal view has no performance benefit of its own: its query runs every time, though the optimizer usually merges it into the outer query so indexes still apply. Views built on views built on views become hard to optimise and debug, so keep the layers shallow.

Views depend on their tables. PostgreSQL won't let you drop a column a view uses, and a view defined with SELECT * stores the column list from when it was created, so columns added later don't appear until you recreate it. List columns explicitly. When the query is expensive and slightly stale data is acceptable, use a materialized view and refresh it on a schedule.

When to materialize insteadQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE MATERIALIZED VIEW sales_by_month2AS3SELECT …;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
query.sql
1REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_month;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Materialized view workflow status
CREATE MATERIALIZED VIEW REFRESH MATERIALIZED VIEW

Note: Assumes the ellipsis is replaced with a complete SELECT and the required unique index exists before the concurrent refresh; command tags vary by client.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then

nightly (CONCURRENTLY needs a unique index on the view).

Key takeaway: Views cost what their query costs; materialize when you need speed over freshness.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1SELECT

Write and test the query

Get the SELECT right first, listing columns explicitly rather than using *.

SQL at this step
1SELECT2  id,3  name,4  city5FROM6  customers7WHERE8  deleted_at IS NULL
What to watch at this step
Avoid
SELECT *
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A view is a saved SELECT query with a name: CREATE VIEW active_customers AS SELECT …. It stores no data of its own; every time you query it, the database runs the underlying query (usually merging it into yours). You can query it like a table, and grant access to it without granting access to the tables beneath.

Why it matters: Views give a stable, simple interface over a messy schema: one definition of "active customer" that every report reuses, and a way to expose only some columns or rows to an analyst or a service. Interviewers often ask "view vs materialized view vs table".

When to reach for it

  • One shared definition of a business metric or entity
  • Exposing a subset of columns or rows to a role
  • Keeping old column names working during a schema change

When to avoid or be careful

  • Expecting a normal view to speed up a slow query
  • Deep stacks of views on views
  • SELECT * in view definitions

View vs materialized view vs table

View
Best for: Reusable logic and restricted access over live data

Strengths: Always current, no storage, no refresh.

Watch out: No faster than the query it wraps.

Materialized view
Best for: Expensive aggregates read often, where some staleness is fine

Strengths: Fast reads from stored results; can be indexed.

Watch out: Must be refreshed; data is as old as the last refresh.

Table (populated by a job)
Best for: Data that needs incremental updates or history

Strengths: Full control over loading, indexing and history.

Watch out: You write and run the loading process yourself.

Interview signals & numbers to know

When this topic comes up

  • “View vs materialized view”
  • “Give analysts access to some columns only”
  • “Every team calculates active users differently”
  • Schema refactoring
  • Row-level access

Benchmarks & rules of thumb

0 bytes -
of data stored by a normal view
PostgreSQL 15 -
added security_invoker views
Unique index -
required for REFRESH … CONCURRENTLY

Common mistakes & follow-ups

Common interview mistakes

  • Creating a view to make a query faster and finding it just as slow.
  • Defining a view with SELECT * and being surprised that new columns don't appear.
  • Granting access to the base tables as well, which defeats the view as a security boundary.

Likely interviewer follow-ups

  • What's the difference between a view and a materialized view?
  • Can you update data through a view? When?
  • How would you use views to give a team access to only some customer columns?
Interview tip: Answer "view vs materialized view" with freshness vs speed: a view is always current and costs a query each time; a materialized view is fast but only as fresh as its last refresh. Then give one use case for each.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Views: Creating Virtual Tables for Security & Simplicity with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Slowly Changing Dimensions (SCD Type 1 & Type 2) in SQL
Next topic
Updatable Views & WITH CHECK OPTION