View in Sql

When working with SQL some time we only need to query some of specific data set not query bunch of data to improve performance. Luckily we can use View to achieve that kind of behavior.

View is a virtual table whose contents (columns and rows) are defined by a query. Use this statement to create a view of the data in one or more tables in the database.  A view can be used for the following purposes:

– To focus, simplify, and customize the perception each user has of the database.

– As a security mechanism by allowing users to access data through the view, without granting the users permissions to directly access the underlying base tables.
– To provide a backward compatible interface to emulate a table whose schema has changed.

We can use SQL functions, Where, Join statement to a view and present data if data coming from one single table.

Syntax to create a view

CREATE VIEW view_name AS
SELECT column1, column2…..FROM table_name
WHERE [condition];

Example: We have Users table like this

IdNameAddressEmail
1TonySài Gòn[email protected]

I will use Create View statement like below

CREATE VIEW USER_VIEW AS
SELECT Id, Name, Email FROM Users

Result

IdNameId
1Tony[email protected]

Syntax to updating a view

A view can be updated with CREATE OR REPLACE VIEW command

ALTER VIEW VIEW_NAME
SELECT VIEW_COLUMN 
WHERE CONDITION;

Syntax to drop a view

DROP VIEW VIEW_NAME;

Delete a row in view

DELETE FROM VIEW_NAME
WHERE CONDITION;

So that is. Happy coding !!!

Leave a comment