🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

SQL Views

SQL Database ObjectsViewsđŸŸĸ Free Lesson
SQL Database Objects

SQL Views

Save a query as a virtual table — simplify complex joins and secure sensitive data.

  • Simplify — Hide complex joins and subqueries behind a clean interface
  • Secure — Restrict access to specific columns or rows
  • Standardize — Provide a consistent API even when the underlying schema changes A view is a named query stored in the database — not a new copy of the data.

What Is a View?

Applicationv_employee_dir (View)Underlying Query Executesemployeesid, name, dept_idsalary, hire_datedepartmentsid, namelocationView = named query stored in database (no data copied)
-- Create a view that joins employees with departments
CREATE VIEW v_employee_directory AS
SELECT
    e.employee_id,
    e.first_name,
    e.last_name,
    e.email,
    d.department_name,
    e.salary
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
-- Query the view like a regular table
SELECT * FROM v_employee_directory
WHERE department_name = 'Engineering';

Simple vs Complex Views

CharacteristicSimple ViewComplex View
Source tablesSingle tableMultiple tables
JOINsNoYes
GROUP BYNoYes
Aggregate functionsNoYes
DML (INSERT/UPDATE/DELETE)Usually yesUsually no
WITH CHECK OPTIONSupportedLimited

Creating Views

Basic View

CREATE VIEW v_active_employees AS
SELECT
    employee_id,
    first_name,
    last_name,
    email,
    department_id
FROM employees
WHERE status = 'Active';

View with JOIN

CREATE VIEW v_employee_compensation AS
SELECT
    e.employee_id,
    e.first_name || ' ' || e.last_name AS full_name,
    e.salary,
    COALESCE(b.bonus, 0) AS bonus,
    e.salary + COALESCE(b.bonus, 0) AS total_compensation
FROM employees e
LEFT JOIN bonuses b ON e.employee_id = b.employee_id;

View with Aggregation

CREATE VIEW v_department_summary AS
SELECT
    d.department_name,
    COUNT(e.employee_id) AS employee_count,
    AVG(e.salary) AS avg_salary,
    MAX(e.salary) AS max_salary,
    MIN(e.salary) AS min_salary
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;

View with Subquery

CREATE VIEW v_above_average_salary AS
SELECT
    employee_id,
    first_name,
    last_name,
    salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Modifying and Dropping Views

-- Replace an existing view
CREATE OR REPLACE VIEW v_employee_directory AS
SELECT
    e.employee_id,
    e.first_name,
    e.last_name,
    e.email,
    e.phone,
    d.department_name,
    e.salary,
    e.hire_date
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
-- Drop a view
DROP VIEW IF EXISTS v_employee_directory;
-- Rename a view (PostgreSQL)
ALTER VIEW v_employee_directory RENAME TO v_employee_info;

Updatable Views

-- Updatable view
CREATE VIEW v_senior_employees AS
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE salary >= 80000;

-- This UPDATE flows through to the base table
UPDATE v_senior_employees
SET salary = salary * 1.10
WHERE employee_id = 101;
-- WITH CHECK OPTION prevents inserting rows that violate the view's WHERE clause
CREATE VIEW v_active_engineers AS
SELECT employee_id, first_name, last_name, department_id
FROM employees
WHERE department_id = 5 AND status = 'Active'
WITH CHECK OPTION;

-- This INSERT is rejected — violates the WHERE clause
INSERT INTO v_active_engineers (first_name, last_name, department_id)
VALUES ('Jane', 'Doe', 3);  -- ERROR: department_id is not 5

Materialized Views

-- PostgreSQL: Create a materialized view
CREATE MATERIALIZED VIEW mv_sales_summary AS
SELECT
    product_id,
    DATE_TRUNC('month', sale_date) AS month,
    SUM(amount) AS total_sales,
    COUNT(*) AS transaction_count
FROM sales
GROUP BY product_id, DATE_TRUNC('month', sale_date);
-- Refresh the materialized view
REFRESH MATERIALIZED VIEW mv_sales_summary;
-- Concurrent refresh (PostgreSQL only — allows reads during refresh)
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_sales_summary;
FeatureRegular ViewMaterialized View
Data storageNo (virtual)Yes (physical)
Query performanceExecutes on demandPre-computed, instant
Data freshnessAlways currentStale until refreshed
Refresh neededNoYes
Storage costNoneDisk space required
DML operationsSometimesRarely

Views for Security

-- Hide sensitive salary data
CREATE VIEW v_public_employee_info AS
SELECT
    employee_id,
    first_name,
    last_name,
    email,
    department_id
FROM employees;

-- Grant access only to the view, not the base table
GRANT SELECT ON v_public_employee_info TO public_user;
REVOKE SELECT ON employees FROM public_user;
-- Row-level security via views
CREATE VIEW v_my_team AS
SELECT *
FROM employees
WHERE manager_id = CURRENT_USER_ID();

Performance Considerations

ScenarioRecommendation
Simple column selection from a single tableUse a view for abstraction, not performance
Complex JOIN across many tablesView helps readability; optimize the underlying query
Expensive aggregation run frequentlyUse a materialized view
Dashboard with fixed time rangesMaterialized view refreshed nightly
Real-time data requirementsRegular view (not materialized)

Common Pitfalls

PitfallProblemSolution
Nested views (view of a view)Hard to debug, performance degradesKeep views shallow — one level deep
Overusing views for everythingCreates a maze of dependenciesUse views selectively for complex joins and security
Forgetting to refresh materialized viewsStale data served to usersSchedule refreshes or use triggers
Updatable views with complex joinsDML operations fail silentlyTest DML on views before relying on them
Naming inconsistencyConfusion between tables and viewsPrefix views with v_ or vw_

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement