VIEWS in Database
VIEWS in Database
Views in database are kind of virtual tables. A view also has rows and columns as they
are in a real table in the database. We can create a view by selecting fields from one or
more tables present in the database. A View can either have all the rows of a table or
specific rows based on certain condition.
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a
single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Examples:
Creating View from a single table:
In this example we will create a View named DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a
table.
SELECT * FROM DetailsView;
In this example, we will create a view named StudentNames from the table
StudentDetails.
Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Creating View from multiple tables:
In this example we will create a View named MarksView from two tables StudentDetails
and StudentMarks. To create a View from multiple tables we can simply include multiple
tables in the SELECT statement.
Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any
more? Obviously we will want to delete it. SQL allows us to delete an existing View. We
can delete or drop a View using the DROP statement. Syntax:
DROP VIEW view_name;
view_name: Name of the View which we want to delete.
For example, if we want to delete the View MarksView, we can do this as:
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:
Example: In the below example we will insert a new row in the View DetailsView which
we have created above in the example of “creating views from a single table”.
Uses of a View: