Views in SQL are one of the most powerful and useful features. They help organize and manage data clearly while making complex queries easier to write and understand. Whether you are learning SQL or working with databases, knowing how views work is important for handling data efficiently and safely. In this blog, you will learn all about SQL views, including their types, how to create them, advanced uses, and best practices.
Table of Contents:
Before understanding views in SQL, let us create a table that will be used as an example to understand all the concepts about Views in SQL.
-- Create Students table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Email VARCHAR(100),
Class VARCHAR(10),
Section CHAR(1),
Age INT
);
-- Insert data into the Students table
INSERT INTO Students (StudentID, Name, Email, Class, Section, Age)
VALUES
(1, 'Amit', '[email protected]', '10th', 'A', 15),
(2, 'Riya', '[email protected]', '10th', 'B', 14),
(3, 'Rohit', '[email protected]', '9th', 'A', 14),
(4, 'Sneha', '[email protected]', '10th', 'A', 15),
(5, 'Rahul', '[email protected]', '8th', 'C', 13);
What are Views in SQL
A view in SQL is a virtual table that does not store data itself. Instead, it shows data from one or more real tables by running a saved SQL query each time it is accessed. Views help simplify complex queries and let you see specific data without changing the original tables.
Example: Creating a view to show basic details of students who are in class 10.
--Creating a View
CREATE VIEW Class10View AS
SELECT Name, Email, Class FROM Students WHERE Class = '10th';
---Using a View
SELECT * FROM Class10View;
Output:
Explanation: Here, the view shows details of students in the 10th class. It simplifies getting this data by saving the query for repeated use.
Types of Views in SQL
Views are grouped based on how they are created and what they are used for. Below are the main types of views commonly used in SQL.
1. System-Defined Views
System-defined views are preconfigured views provided by SQL Server that you have not created. They help in viewing the internal structure of the database system and understanding how tables and other objects are stored and managed.
The system-defined views can be used to:
- Check any details of users, tables, columns, or configuration.
- Manage performance and usage of the database.
- Diagnose problems with SQL Server.
System-defined views can be primarily categorized into three classifications:
a. Information Schema Views
Information schema views provide information about your database objects. For example, information schema views will provide you with a list of tables, the columns in a table, and the data types that you have used. You may use information schema views to learn the structure of your database.
b. Catalog Views
Catalog views were introduced in SQL Server 2005. They show internal details about how SQL Server stores data conceptually. Organized into classes, catalog views give more control over managing your database system.
c. Dynamic Management Views (DMVs)
Dynamic management views were also added in SQL Server 2005. DMVs can help you with monitoring the current state of your SQL Server. These views are useful for performance monitoring and for error correction.
2. User-Defined Views in SQL
User-defined views are defined by the database users. Views are useful as they make data easier to understand. Instead of writing long queries again and again, a view can hold that query and work like a table.
There are 2 main types of user-defined views:
a. Simple View
- It is made from a single table.
- It allows operations such as insert, update, and delete.
- It is easy to use and manage.
Example: A view to only show Class 10 students from the Students table.
b. Complex View
- It is made from two or more tables.
- It may not allow operations such as insert, update, and delete.
- Useful for reports and summaries.
Example: A view to display the names of students with their averages from the Students table and the Marks table.
Note: We already created a user-defined view above called Class10View.
Master SQL from Scratch – Enroll in Our Course Today
Get in-depth lessons, real-world projects, certification, and expert support to boost your database skills.
How to Create a View in SQL
You can create a view using the CREATE VIEW statement along with a SELECT query.
CREATE VIEW Class10View AS
SELECT Name, Email, Class FROM Students WHERE Class = '10th';
Output:
Explanation: Here, the view selects Name, Email, and Class of students in the 10th class. It helps quickly access only the 10th-class student details.
1. Creating a View from a Single Table in SQL
A view can be created from one table by selecting specific columns to simplify data access and reuse.
CREATE VIEW SeniorStudents AS
SELECT Name, Age FROM Students WHERE Age > 14;
2. Modify an Existing View
It is used to redefine the view by changing its SELECT query, such as adding or removing columns in the result set.
CREATE OR REPLACE VIEW Class10View AS
SELECT Name, Email, Class, Section FROM Students WHERE Class = '10th';
3. List All Views in Your Database
This command is used to see all the views and records created by the user.
SELECT table_name FROM information_schema.views WHERE table_schema = 'public';
Output:
Explanation: Here, the query checks the database for all views in the public schema. It shows the names of views created by the user.
4. Delete a View
This command is used to remove a view that was previously created by the user from the database.
DROP VIEW Class10View;
Output:
Explanation: Here, Class10View, which we have created in the above example, is deleted with the help of the DROP statement.
Advanced View Examples in SQL
1. Using Subqueries in a View in SQL
A view can include subqueries to filter data or perform calculations inside it.
Example:
CREATE VIEW AboveAverageStudents AS
SELECT Name, Age FROM Students
WHERE Age > (SELECT AVG(Age) FROM Students);
SELECT * FROM AboveAverageStudents;
Output:
Explanation: Here, the view uses a subquery to get the average age of students. It shows only those students whose age is greater than the average.
2. Using CHECK OPTION in a View
This option ensures that any changes made through the view follow the view’s conditions.
CREATE VIEW VerifiedSeniorStudents AS
SELECT * FROM Students WHERE Age > 14
WITH CHECK OPTION;
SELECT * FROM VerifiedSeniorStudents;
Output:
Explanation: Here, if someone tries to insert a student with Age <= 14 using this view, it will be blocked.
Note: The WITH CHECK OPTION is supported in SQL Server, MySQL, and Oracle, but not supported in PostgreSQL views.
3. Views with Multiple Joins in SQL
Suppose there are two tables named Customers and Orders. We can join them using views in SQL.
-- Drop tables and views if they already exist (to avoid errors)
DROP VIEW IF EXISTS OrderSummary;
DROP TABLE IF EXISTS Orders;
DROP TABLE IF EXISTS Customers;
-- Step 2: Creating the Customers table
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(50),
Email VARCHAR(100)
);
-- Step 3: Creating the Orders table
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
Amount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
-- Insert data
INSERT INTO Customers (CustomerID, Name, Email) VALUES
(1, 'Alice', '[email protected]'),
(2, 'Bob', '[email protected]'),
(3, 'Charlie', '[email protected]');
--Insert data
INSERT INTO Orders (OrderID, CustomerID, OrderDate, Amount) VALUES
(101, 1, '2025-06-01', 250.00),
(102, 2, '2025-06-05', 150.00),
(103, 1, '2025-06-10', 300.00),
(104, 3, '2025-06-12', 200.00);
-- Create a View that combines Customers and Orders
CREATE VIEW OrderSummary AS
SELECT
C.CustomerID,
C.Name AS CustomerName,
C.Email,
O.OrderID,
O.OrderDate,
O.Amount
FROM
Customers C
JOIN
Orders O ON C.CustomerID = O.CustomerID;
-- Step 7: Select from the View
SELECT * FROM OrderSummary;
Output:
Explanation: Here, the view uses an inner join to combine the Customers and Orders tables based on the matching CustomerID. This join helps display customer and order details together in one result set.
Get 100% Hike!
Master Most in Demand Skills Now!
Materialized View in SQL
A materialized view can be thought of as a snapshot of some data. It will physically contain the result of a query in the database. You will find this useful for large tables and slow queries.
A materialized view stores data, unlike a normal view, and can be refreshed whenever needed.
Let us understand this with an example:
-- Step 1: Create the Sales table
CREATE TABLE Sales (
ID INT,
Region VARCHAR(50),
Amount DECIMAL(10,2)
);
-- Step 2: Insert initial data into the Sales table
INSERT INTO Sales (ID, Region, Amount) VALUES
(1, 'North', 1000),
(2, 'South', 1500),
(3, 'North', 2000),
(4, 'East', 1800),
(5, 'South', 1200);
-- Step 3: Create a materialized view to summarize total sales by region
CREATE MATERIALIZED VIEW SalesSummary AS
SELECT Region, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Region;
-- Step 4: Refresh the materialized view to make sure it includes the latest data
REFRESH MATERIALIZED VIEW SalesSummary;
-- Step 5: Insert new sales data
INSERT INTO Sales (ID, Region, Amount) VALUES (6, 'North', 500);
-- Step 6: Refresh the materialized view again to update the summary
REFRESH MATERIALIZED VIEW SalesSummary;
-- Step 7: View the updated sales summary
SELECT * FROM SalesSummary;
Output:
Explanation: Here, the materialized view stores the total sales by region from the Sales table. It updates only when refreshed, helping improve performance for summary queries.
Note: PostgreSQL and Oracle support the CREATE MATERIALIZED VIEW and REFRESH MATERIALIZED VIEW commands.
- Select Only Required Columns: Do not use SELECT *, but rather select the columns you need.
- Avoid Excessive Joins: Joining too many tables can slow down your View. Only join if needed.
- Reduce Nested Views Inside Views: Using views inside other views can confuse the database and slow down performance.
- Keep Indexes on Base Tables: Indexes help speed up data searches in the base tables that views use.
Difference Between Table and View in SQL
Feature |
Table |
View |
Stores Data |
Yes, tables physically store the data in the database. |
No, views do not store data themselves (except materialized views). |
Physical Object |
Tables are real database objects that occupy storage space. |
Views are virtual structures and do not occupy physical storage. |
Allows Data Modification |
Yes, you can insert, update, or delete records in a table. |
Sometimes, you can modify data through views if they are updatable. |
Performance |
Tables offer faster access because data is stored directly. |
Performance varies based on the complexity of the view and underlying queries. |
Usage |
Used to store and manage actual data records. |
Used to simplify and customize complex data queries. |
Best Practices for Working with Views in SQL
- Use Clear Names: Use clear and descriptive names for views so their purpose is easy to understand and maintain.
- Include Only Needed Columns: Include only the necessary columns in views to improve performance and make them easier to read and manage.
- Keep Queries Simple: Avoid complex joins and nested views because straightforward queries are faster and easier to work with.
- Use WITH CHECK OPTION: Apply WITH CHECK OPTION to ensure data integrity when inserting or updating data through views.
- Review Views Regularly: Regularly review and update views to make sure they still meet current business needs and reflect any changes in data or requirements.
Common Use Cases of Views in SQL
1. Hiding Complicated Joins and Queries: Views help simplify complex SQL queries with many joins, subqueries, or filters. Instead of writing the same complicated query over and over, you save it as a view and can use it like a table.
2. Providing Limited Access to Data: You can create views that contain only selected columns or rows from a table. This allows you to provide users access to only the data they require, without exposing everything (like passwords or salaries).
3. Making Reports Easier: Views can standardize reports because users can provide standard selections of data in a particular order and format in the view. Consumers of the report from a reporting tool can connect directly to the view to get usable data.
4. Reusing SQL Logic: As an alternative to repeating the same query, if you reuse SQL logic in many different places, simply save it as a view, and it simplifies the steps. You’ve authored the logic once and reused it where you want to use it; that is easier to deal with if there is an update as well.
5. Adding Security and Control to Data: Views help establish an additional layer of security to control what data users see or modify. You can give access to a view instead of the main table to help protect important or sensitive data.
Start Learning SQL for Free – No Cost, No Catch!
Access beginner-friendly tutorials, quizzes, and practical examples to build a strong foundation in databases.
Conclusion
SQL views are a useful and efficient way to organize, simplify, and protect your data without having to store it multiple times. They help you write cleaner, easier-to-understand queries, control exactly what data users can access, and make managing complex information much simpler. When used properly, views can improve the speed of your database, keep data well-organized, and increase overall security. Learning how to create and work with views is an important skill for building reliable, scalable, and easy-to-maintain database systems.
Take your skills to the next level by enrolling in the SQL Course today and gaining hands-on experience. Also, prepare for job interviews with SQL Interview Questions prepared by industry experts.
SQL Views – FAQs
Q1. What is a view in SQL?
A view is a virtual table that shows data from one or more real tables using a SQL query.
Q2. Can we insert or update data through a view?
Yes, but only if the view is simple and based on one table without GROUP BY, JOIN, or aggregate functions.
Q3. What is the use of a view in SQL?
Views help simplify complex queries, protect data, and make reporting easier.
Q4. What is the difference between a table and a view?
A table stores data physically, while a view shows data from tables without storing it.
Q5. Can a view be based on multiple tables?
Yes, you can create a view using JOINs to combine data from multiple tables.