Loading lesson path
An SQL view is a virtual table based on the result-set of an SQL statement. An SQL view contains rows and columns, just like a real table. The fields in the 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 it were coming from one single table. A view is created with the CREATE VIEW statement.
view_name
column1, column2, ...
table_name
condition
;A view always shows real-time data! The database engine only stores the view's definition (the SELECT statement), not a copy of the data.The following SQL creates a view named "Brazil Customers", that shows all customers from Brazil:
CREATE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName
WHERE Country = 'Brazil';To query the view above, use the following SQL syntax:
SELECT * FROM [Brazil Customers];
The following SQL creates a view named "Products Above Average Price", that selects all products in the "Products" table with a Price higher than the average price:CREATE VIEW [Products Above Average Price] AS SELECT ProductName, Price
WHERE Price > (SELECT AVG(Price) FROM Products);To query the view above, use the following SQL syntax:
SELECT * FROM [Products Above Average Price];
ALTER VIEW Statement (SQL Server)In SQL Server, a view can be updated with the ALTER VIEW statement.
view_name
column1, column2, ...
table_name
condition
;
The following SQL adds the "City" column to the "Brazil Customers" view:ALTER VIEW [Brazil Customers] AS SELECT CustomerName, ContactName, City
WHERE Country = 'Brazil';
CREATE OR REPLACE VIEW Statement (MySQL and Oracle)In MySQL and Oracle, a view can be updated with the CREATE OR REPLACE VIEW statement.
view_name
column1, column2, ...