MySQL VIEWS
MySQL CREATE VIEW Statement
A view in SQL is a virtual table created from a SQL statement’s result set.
A view has rows and columns, exactly like a table in the real world. A view contains fields that come from one or more actual database tables.
A view can have SQL statements and functions added to it so that the data is displayed as though it is from a single table.
The CREATE VIEW statement creates a view.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: Current data is always displayed in a view! Each time a user requests a view, the database engine recreates it.
MySQL CREATE VIEW Examples
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
We can query the view above as follows:
Example
SELECT * FROM [Brazil Customers];
A view that includes all products in the “Products” table with prices greater than average is created by the SQL code below:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, 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];
MySQL Updating a View
The CREATE OR REPLACE VIEW command allows for view updates.
CREATE OR REPLACE VIEW 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 “Brazil Customers” view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
MySQL Dropping a View
The DROP VIEW statement removes a view.
DROP VIEW Syntax
DROP VIEW view_name;
The following SQL drops the “Brazil Customers” view:
Example
DROP VIEW [Brazil Customers];