SQL VIEWS

It provides limited access to specific columns in a database table rather than access entire table and thus gives a flexibility of controlling user access to table.

It also can be formed by combining multiple tables. It also has rows and columns to store data like tables

It is useful for generating reports from multiple tables

CREATE VIEWS

Syntax:

CREATE VIEW view_name AS
            SELECT column1, column2..
             FROM Table_Name
             WHERE [Condition];

Lets take this TRAINEES table
idfirst_namelast_namebirth_dategender
1PeterParker1998-03-04M
2HarryPotter2001-08-30M
3PeterPan2004-09-19M
4AliceKingsleigh1999-07-02F
5JohnConnor2002-01-15M
CREATE VIEW TRAINEES_VIEW AS
SELECT first_name, birth_date
FROM  TRAINEES;

it will create the view TRAINEES_VIEW, now to view it run : SELECT * from TRAINEES_VIEW

Output:

first_namebirth_date
Peter1998-03-04
Harry2001-08-30
Peter2004-09-19
Alice1999-07-02
John2002-01-15

With CHECK Option

This is used while view creation to add constraint to the specific fields

Example:

CREATE VIEW TRAINEES_VIEW AS SELECT first_name, birth_date FROM TRAINEES WHERE birth_date IS NOT NULL;

UPDATE in VIEWS:

UPDATE TRAINEES_VIEW SET birth_date = 2000-01-01 WHERE first_name ='Peter';

DELETE in VIEWS

DELETE FROM VIEWS WHERE first_name='John';

DROP in VIEWS

DROP VIEW TRAINEES_VIEW;

Learn more : SQL Tutorial , SQL Interview Questions