0
0
SQLquery~5 mins

Why views are needed in SQL

Choose your learning style9 modes available
Introduction

Views help us see data in a simple way without changing the original tables. They make complex data easier to understand and use.

When you want to show only certain columns or rows to users.
When you want to combine data from multiple tables into one simple table.
When you want to hide complex calculations from users.
When you want to protect sensitive data by showing only what is allowed.
When you want to reuse a complex query easily without rewriting it.
Syntax
SQL
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
A view is like a saved query that you can use like a table.
You can select from a view just like a regular table.
Examples
This view shows only the name and age of employees older than 30.
SQL
CREATE VIEW SimpleView AS
SELECT name, age
FROM Employees
WHERE age > 30;
This view summarizes total sales quantity for each product.
SQL
CREATE VIEW SalesSummary AS
SELECT product_id, SUM(quantity) AS total_sold
FROM Sales
GROUP BY product_id;
Sample Program

This example creates a table of employees, inserts some data, then creates a view showing only employees older than 30. Finally, it selects all data from the view.

SQL
CREATE TABLE Employees (
  id INT,
  name VARCHAR(50),
  age INT,
  salary INT
);

INSERT INTO Employees VALUES
(1, 'Alice', 28, 50000),
(2, 'Bob', 35, 60000),
(3, 'Charlie', 40, 70000);

CREATE VIEW OlderEmployees AS
SELECT name, age
FROM Employees
WHERE age > 30;

SELECT * FROM OlderEmployees;
OutputSuccess
Important Notes

Views do not store data themselves; they show data from the original tables.

Updating data through views can be limited depending on the database system.

Summary

Views simplify complex data by showing only what you need.

They help protect sensitive data by hiding columns or rows.

Views make it easier to reuse queries without rewriting them.