Curriculum
Course: MYSQL
Login

Curriculum

MYSQL

MySQL References

0/140
Text lesson

MySQL Views

MySQL CREATE VIEW Statement

In SQL, a view is a virtual table created from the result-set of an SQL query.

It consists of rows and columns, similar to a physical table, where the fields are derived from one or more real tables in the database.

Views allow you to incorporate SQL statements and functions, presenting data as though it originates from a single table.

A view is established using the CREATE VIEW statement.

CREATE VIEW Syntax

CREATE VIEW view_name AS
SELECT column1column2, …
FROM table_name
WHERE condition;

Note: A view always displays current data! The database engine refreshes the view each time it is queried.

MySQL CREATE VIEW Examples

The following SQL statement creates a view that displays all customers from Brazil:

Example

CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = ‘Brazil’;

We can retrieve data from the view above using the following query:

Example

SELECT * FROM [Brazil Customers];

The following SQL statement creates a view that selects every product from the ‘Products’ table with a price higher than the average price:

Example

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

We can retrieve data from the above view using the following query:

Example

SELECT * FROM [Products Above Average Price];

MySQL Updating a View

A view can be modified using the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column1column2, …
FROM table_name
WHERE condition;

The following SQL statement includes the “City” column in 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

A view is removed using the DROP VIEW statement.

DROP VIEW Syntax

DROP VIEW view_name;

The following SQL statement deletes the “Brazil Customers” view:

Example

DROP VIEW [Brazil Customers];