HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

SQL Views

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the data were coming from one single table.

A view is created with the The CREATE VIEW statement.

CREATE VIEW Syntax


Creates an index on a table. Duplicate values are allowed:

Syntax

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

Note: A view always shows up-to-date data! The database engine recreates the view, every time a user queries it.

SQL CREATE VIEW Examples


The following SQL creates a view that shows all employee from India:

Example

CREATE VIEW [India employee] AS
SELECT Employee_name, Address
FROM employee
WHERE Country = 'India';

We can query the view above as follows:

Example

SELECT *FROM [India employee];

The following SQL creates a view that selects every product in the "Products" table with a price higher than the average price:

Example

CREATE VIEW [products Above Average Price ] AS
SELECT Product_name, Price
FROM products
WHERE Price > ( SELECT AVG(Price) FROM products) ;

We can query the view above as follows:

Example

SELECT *FROM [products Above Average Price];

SQL Updating a View


A view can be updated with theCREATE OR REPLACE VIEW statement.

Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ....
FROM table_name
WHERE condition;

The following SQL adds the "City" column to the "India employee" view:

Example

CREATE OR REPLACE VIEW [India employee] AS
SELECT Employee_name, Address
FROM employee
WHERE Country = 'India';

SQL Dropping a View


A view is deleted with the DROP VIEW statement.

Syntax

DROP VIEW view_name;

The following SQL drop the "India employee" view:

Example

DROP VIEW [India employee];