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?
-- 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
| Characteristic | Simple View | Complex View |
|---|---|---|
| Source tables | Single table | Multiple tables |
| JOINs | No | Yes |
| GROUP BY | No | Yes |
| Aggregate functions | No | Yes |
| DML (INSERT/UPDATE/DELETE) | Usually yes | Usually no |
| WITH CHECK OPTION | Supported | Limited |
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;
| Feature | Regular View | Materialized View |
|---|---|---|
| Data storage | No (virtual) | Yes (physical) |
| Query performance | Executes on demand | Pre-computed, instant |
| Data freshness | Always current | Stale until refreshed |
| Refresh needed | No | Yes |
| Storage cost | None | Disk space required |
| DML operations | Sometimes | Rarely |
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
| Scenario | Recommendation |
|---|---|
| Simple column selection from a single table | Use a view for abstraction, not performance |
| Complex JOIN across many tables | View helps readability; optimize the underlying query |
| Expensive aggregation run frequently | Use a materialized view |
| Dashboard with fixed time ranges | Materialized view refreshed nightly |
| Real-time data requirements | Regular view (not materialized) |
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
| Nested views (view of a view) | Hard to debug, performance degrades | Keep views shallow â one level deep |
| Overusing views for everything | Creates a maze of dependencies | Use views selectively for complex joins and security |
| Forgetting to refresh materialized views | Stale data served to users | Schedule refreshes or use triggers |
| Updatable views with complex joins | DML operations fail silently | Test DML on views before relying on them |
| Naming inconsistency | Confusion between tables and views | Prefix 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
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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