A view is a table whose rows are not explicitly stored, a view is a virtual table based on the result-set of an SQL statement. A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables which depends on the written SQL query to create a view.
A view is generated to show the information that the end-user requests the data according to specified needs rather than complete information of the table.
Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific implementation.
CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition;
CREATE VIEW Students_CSE AS
SELECT Roll_no,Name
FROM Students
WHERE Branch = 'CSE';
A view can be updated with the CREATE OR REPLACE VIEW statement.
Syntax in MysqlCREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition;
The following SQL adds the "Mobile" column to the "Students_CSE" view:
CREATE OR REPLACE VIEW Students_CSE AS
SELECT Roll_no,Name,Mobile
FROM Students
WHERE Branch = 'CSE';
CREATE VIEW defines a view on a set of tables or views or both.
REPLACE VIEW redefines an existing view or, if the specified view does not exist,
We can insert a row in a View in a same way as we do in a table. We can use the INSERT INTO statement of SQL to insert a row in a View.
Syntax in MysqlINSERT INTO view_name(column1, column2, ...) VALUES(value1,value2,.....);
INSERT INTO Students_CSE(Roll_no,Name,Mobile)
VALUES(521,'ram',9988776655);
Deleting rows from a view is also as simple as deleting rows from a table. We can use the DELETE statement of SQL to delete rows from a view.
Syntax in MysqlDELETE FROM view_name WHERE condition;
DELETE FROM Students_CSE
WHERE Name="ram";
We can query the view as follows
Syntax in MysqlSELECT * FROM view_name
SELECT * FROM Students_CSE;
In order to delete a view in a database, we can use the DROP VIEW statement.
Syntax in MysqlDROP FROM view_name
DROP FROM Students_CSE;