In SQL, Views are like saved queries result that act as virtual tables, It's not an actual table but a saved query result that you can treat as if it were a table.
Views help you organize and simplify your data, making it easier to work with and control who sees what.
CREATE VIEW view_name AS SELECT column1, column2, column3, ... FROM table_name;
• CREATE VIEW : This keyword is used to indicate that you're creating a new view.
• view_name : This is the name you want to give to your view.
• AS : This keyword is used to specify that you're defining the structure of the view.
• After the "AS" keyword, we specify the SELECT statement.
1. Let's assume you have a database with two tables : [i]. Person [ii]. Departments
2. Now, let's create a view that combines data from both tables to show the names, group names of [person] along with their respective department names from [Departments] table:
3. Please run the following SQL statement :
CREATE VIEW Employees_view AS SELECT e.[Name], e.GroupName, d.Department_Name FROM [Person] e JOIN [Departments] d ON d.Department_id = e.Department_id;
4. In above statement, We're creating a view called "EmployeeDepartmentView". The view combines data from the employees and departments tables by joining them on the department_id column. It includes the employee's name (e.name), salary (e.salary), and department name (d.name).
5. Now, you can query this view as if it were a table.
SELECT * FROM Employees_view;
6. Above query returns a result set showing each person's name, group_name, and the department they belong to, without having to join the tables every time.
7. To drop (delete) a view in SQL, run below SQL statement.
DROP VIEW Employees_view;
8. After executing above statement, the "Employees_view" view will be deleted from the database, and you won't be able to query it anymore.
Great job! You've successfully created, selected, and deleted views in SQL!
Views in SQL are virtual tables that display a subset of data from one or more tables.
A SQL view is a virtual table based on the result-set of an SQL statement, while a table contains actual data.
Benefits of views in SQL include data abstraction, security, simplified querying, and logical data independence.
Views in SQL are used to provide a simplified and customized view of data, enhance security, and facilitate complex queries.