Skip to main content
SQL Fundamentals
CHAPTER 19 Beginner

Views in SQL

Updated: May 16, 2026
15 min read

# CHAPTER 19

Views in SQL

1. Introduction

In Chapters 16, 17, and 18, we learned to write incredibly complex queries combining multiple JOINs, Aggregate Functions, and Subqueries. If you have a 30-line query that generates the company's daily sales report, typing it out every single day is a waste of time. Furthermore, giving Junior Data Analysts direct access to raw, complex tables is highly dangerous. To solve both of these problems, Database Architects use Views. In this chapter, we will learn how to save complex logic into beautiful, queryable "Virtual Tables."

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a View is in Relational Databases.
  • Encapsulate a complex query using CREATE VIEW.
  • Query a View exactly as if it were a physical table.
  • Utilize Views for security to restrict data access.
  • Modify and Drop existing Views.

3. What is a View? (The Virtual Table)

A View is essentially a saved SQL query that acts like a table. It does *not* physically store data on the hard drive. Instead, every time you query the View, the database engine secretly runs the complex query behind the scenes and hands you the result. It is a virtual window into the underlying data.

4. Creating a View (CREATE VIEW)

Let's imagine we frequently need a list of active users, their total orders, and their shipping addresses. It requires joining 3 tables. Let's encapsulate it into a View.
sql
12345678910111213
-- DDL Command to create the virtual table
CREATE VIEW active_customer_report AS
SELECT 
    u.id, 
    u.name, 
    u.email, 
    COUNT(o.id) AS total_orders,
    a.city
FROM users u
INNER JOIN addresses a ON u.id = a.user_id
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.status = 'Active'
GROUP BY u.id, u.name, u.email, a.city;

*(Success! The View is saved in the database permanently).*

5. Querying the View

Now, whenever the CEO asks for the active customer report, you do not need to write that 15-line JOIN query ever again. You treat the View exactly like a normal table!
sql
1234567
-- Query the virtual table!
SELECT * FROM active_customer_report;

-- You can even filter and sort the View!
SELECT * FROM active_customer_report 
WHERE total_orders > 5 
ORDER BY city;

6. Views for Database Security

Views are not just for saving typing time; they are a critical security mechanism. Suppose your employees table has id, name, department, and salary. You want the IT department to build a public company directory. You cannot give them access to the employees table, because they will be able to see everyone's salary!

The Solution: Create a restricted View!

sql
1234
-- Create a View that deliberately EXCLUDES the salary column
CREATE VIEW public_directory AS
SELECT id, name, department 
FROM employees;

*(Now, you give the IT developer permission to query the public_directory View, while completely denying them access to the base employees table. The sensitive data is mathematically walled off!)*

7. Updating and Dropping Views

If the business requirements change and the CEO wants the customer report to include phone numbers, you must alter the view.
sql
1234567
-- Recreate the view with updated logic
CREATE OR REPLACE VIEW public_directory AS
SELECT id, name, department, phone_number
FROM employees;

-- Delete the view permanently
DROP VIEW public_directory;

8. Mini Project: The Reporting Dashboard

A Node.js backend needs to power a massive dashboard. Instead of writing 100 lines of SQL in the JavaScript code (which is hard to maintain), the DBA creates Views in the database.
  1. 1. CREATE VIEW dailyrevenue AS ...
  1. 2. CREATE VIEW lowstockalerts AS ...
  1. 3. CREATE VIEW topperformingstaff AS ...

The Node.js developer now simply writes: SELECT * FROM dailyrevenue; The backend code is perfectly clean, and the Database Administrator retains full control over the complex logic!

9. Common Mistakes

  • Thinking Views Improve Performance: A common beginner myth is that Views make queries run faster. They do not. Because a View does not physically store data, querying a View simply executes the underlying JOINs in real-time. (Note: Advanced databases support *Materialized Views*, which DO physically store the data for massive speed boosts, but that is an advanced topic).
  • Trying to INSERT into complex Views: While you can technically execute INSERT INTO or UPDATE on a simple 1-table View, if the View contains JOINs or GROUP BY math, it becomes "Read-Only". You cannot INSERT into a mathematical average.

10. Best Practices

  • Naming Conventions: It is an industry standard to prefix or suffix View names to distinguish them from actual physical tables.
*Example:* vwcustomerreport or customerreportv.

11. Exercises

  1. 1. Does a standard SQL View physically duplicate and store data on the server's hard drive?
  1. 2. What DDL command is used to permanently delete a View from the database schema?

12. SQL Challenges

Write the DDL to create a View named vwexpensiveproducts. It should encapsulate a query that selects product_name and price from the products table, strictly filtering for items where the price is greater than 1000.
sql
123
CREATE VIEW vw_expensive_products AS
SELECT product_name, price FROM products
WHERE price > 1000;

13. MCQ Quiz with Answers

Question 1

What is the primary architectural purpose of a standard SQL View?

Question 2

When an IT Department is granted access to query a View named public_employees, but is strictly denied access to the underlying employees base table, what security concept is the Database Architect implementing?

14. Interview Questions

  • Q: Explain the mechanical difference between a Standard View and a Materialized View (conceptually). Why would a company generating a massive 50-table analytics report choose a Materialized View?
  • Q: A junior developer attempts to execute an UPDATE statement against a View that was generated using a GROUP BY clause. Explain why the database engine rejects this operation.

15. FAQs

Q: Can a View query another View? A: Yes! You can build Views on top of Views. However, be extremely careful. If you build a chain of 5 Nested Views, the performance can degrade catastrophically because the database engine struggles to optimize the deeply buried execution plans.

16. Summary

By mastering Views, you have bridged the gap between Database Administration and Backend Development. You can abstract horrifyingly complex JOIN logic into beautiful, queryable virtual tables, vastly improving code maintainability while simultaneously enforcing strict, column-level security across your organization.

17. Next Chapter Recommendation

Our queries are clean, but our database is growing rapidly. If a table hits 10 million rows, even a simple SELECT query might take 10 seconds to execute, crashing the application. In Chapter 20: Indexing and Query Optimization, we will learn the ultimate dark art of database engineering: B-Tree Indexes.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·