Development

How to use MySQL Views

Captain Salem 2 min read

How to use MySQL Views

MySQL is an incredible database that offers a wide collectio of features out-of-the-box. One such feature is MySQL view or views for short.

A view refers to a named query that is stored in the database cataglog. In simple terms, a view is a virtual table that stores the result of another SQL statement.

Since its a virtual table, a view contains both rows and columns and similar properties of a real database table. You can also perform actions such as create and execute functions, insert, update and delete records.

There are various uses of a MySQL view. Example include:

  1. Simplifying Complex Queries - MySQL views are mainly used when you need to simply a relatively complex query. Instead of re-writing the query, you can use a view to create a table with the specific data.
  2. Security - Another common use of views is security. Instead of exposing a whole table, you can use a view to only include the data you wish to expose and protect the main table.

In this article, you will explore how to work with MySQL views in simple and easy-to-follow steps. We will start by discussing how to create a view, shows views within a database, renaming views, etc.

Let’s get started.

MySQL Create View

To create a view in MySQL, we use the CREATE VIEW statement as shown in the syntax below:

CREATE [OR REPLACE] VIEW [db.]view_name [(col_list)]
AS
    SELECT STATEMENT

The query statement follows a relatively simple syntax.

We start with the CREATE VIEW command followed by the target database and name of the view. Keep in mind that a view name cannot be similar to an existing table in the same database.

This is becuase a view and a table share a similar namespace.

If you wish to replace the an already existing view, you can use the OR REPLACE CLAUSE. If the view with the specified name does not exist, the OR REPLACE clause will not perform any action.

After tha, we specify the list of columns we wish to include in the target view. In most cases, the columns of a view are selected from the SELECT statement. Note, the names of the columns to include in the view are specified inside a pair of parenthesis

Finally, using a SELECT statement, define the data that is included in the view. This query will fetch the data from a specific table or an existing view and add to the view. Like any normal SELECT statement, you can include other statements such as ORDER BY, HAVING and other conditional statments.

Example

Let us look at a practical example on how to create a view in MySQL.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.