10 Examples to Understand SQL Views | by Soner Yıldırım | Towards Data Science

SQL is a programming language used to manage and maintain data stored in relational databases. A relational database consists of tables with labelled rows and columns.
One of the most frequent operations with SQL is to query a database to retrieve data. A typical relational database contains many tables that are related to each other by means of shared values in a column known as foreign key.
As the number of tables increases, writing queries starts to become complex. Besides, we usually need to filter or transform data while retrieving from the database. Thus, we end up writing complicated and lengthy queries to obtain the desired data.
It is doable to write a complex query once or twice. However, if we need to use it many times, a more practical approach is necessary. One option is to save the query in a text or sql file and copy it whenever needed. It is fine but there is a better option which is SQL views or simply views.
A view is a stored query. Views are saved in the database server so we do not have to copy them from some other file. We create a view by assigning a name to a query.
Let’s start with an example so that we have an idea about how a view looks like. After that, I will elaborate on the examples and explain the views in more detail.
I have created a customer and orders table with mock data. The tables contain some information about customers of a business and their orders. Here is an overview of the tables:
The tables are related by the customer id (cust_id) column so we use the customer id column to join these tables.
Consider a case where need to find the total order amount for each location. Here is the query that accomplished this task.
#Example 1mysql> select customer.location, sum(orders.amount)    -> from customer    -> join orders    -> on customer.cust_id = orders.cust_id    -> group by customer.location;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin   |            9811.09 || Dallas   |           23288.40 || Houston  |           12978.33 |+----------+--------------------+
We select the location from the customer table and the sum of amount from the orders table. The tables are joined on the customer id column. The group by clause groups the entries (i.e. rows) by location.
We can store this query using a view as follows:
#Example 2mysql> create view totalAmount    -> as    -> select customer.location, sum(orders.amount)    -> from customer    -> join orders    -> on customer.cust_id = orders.cust_id    -> group by customer.location;
The “create view” statement is used along with a name for the view. Then, we write the query after the “as” keyword.
As you notice, creating a view does not return anything or it does not execute the select statement. The views generate a result set only when they are invoked.
We can invoke views just like we query a table. Here is how it’s done:
#Example 3mysql> select * from totalAmount;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin   |            9811.09 || Dallas   |           23288.40 || Houston  |           12978.33 |+----------+--------------------+
The example above makes the views seem like tables. In terms of querying, views can be considered as tables. However, they do not store any data. Once a view is executed, SQL retrieves the data from the tables specified inside the view. Thus, views are sometimes called virtual tables.
Note: It is important to emphasize that we are using MySQL as relational database management system (RDBMS). Although the SQL syntax is mostly the same among different RDBMs, there might be small differences.
We can filter a view by using the where clause.
#Example 4mysql> select * from totalAmount    -> where location = "Austin";+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin   |            9811.09 |+----------+--------------------+
We can only filter based on the columns included in the view. For instance, the orders table has a date column but it cannot be used for filtering. The totalAmount view only refers to the location and sum of the amount. These are the only two values we can use for filtering.
Let’s create another view which allows for filtering based on the date and amount columns.
#Example 5mysql> create view cityOrders    -> as    -> select    ->   customer.location,    ->   orders.date,    ->   orders.amount    -> from customer    -> join orders    -> on customer.cust_id = orders.cust_id;
The cityOrders view refers to three columns which are the location from customer table and the date and amount from orders table.
We can use the cityOrders view to calculate the total order amount for each location on a specific date.
#Example 6mysql> select location, sum(amount)    -> from cityOrders    -> where date = '2020-01-31'    -> group by location;+----------+-------------+| location | sum(amount) |+----------+-------------+| Austin   |       77.94 || Dallas   |      260.77 || Houston  |       72.46 |+----------+-------------+
We can also calculate the number of orders that are higher than a specific amount for each city.
#Example 7mysql> select location, count(amount)    -> from cityOrders    -> where amount > 20    -> group by location;+----------+---------------+| location | count(amount) |+----------+---------------+| Austin   |           160 || Dallas   |           383 || Houston  |           205 |+----------+---------------+
Although both the totalAmount and cityOrders views refer to the amount column, we cannot use single order amounts for filtering in the totalAmount view. The reason is that the totalAmount view refers to the sum of the amounts, not single order amounts.
We can update a view using the “alter view” or “create or replace view” statements. The difference is that the view must exist to use the “alter view” statement. If we are not sure if the view already exists, we should use the “create or replace view” statement.
Let’s modify the cityOrders view.
#Example 8mysql> alter view cityOrders    -> as    -> select    ->   customer.location,    ->   customer.age,    ->   orders.date,    ->   orders.amount    -> from customer    -> join orders    -> on customer.cust_id = orders.cust_id;
We have added the age column from customer table to the cityOrders view. We can now use the age for filtering or aggregation as well. The following query returns the average order amount of customers who are older than 30. It also groups the results based on location.
#Example 9mysql> select location, avg(amount)    -> from cityOrders    -> where age > 30    -> group by location;+----------+-------------+| location | avg(amount) |+----------+-------------+| Austin   |   53.740153 || Dallas   |   47.069703 || Houston  |   49.287771 |+----------+-------------+
If we do not need a view anymore, we can drop it. The syntax is same as dropping a table.
#Example 10mysql> drop view totalAmount;Query OK, 0 rows affected (0.00 sec)mysql> select * from totalAmount;ERROR 1146 (42S02): Table 'practice.totalAmount' doesn't exist
The view is an important concept for SQL. There are many advantages of using a view. The first and foremost, it simplifies complex queries. The examples we have done included joining two tables. In case of larger databases with many tables, the queries might be highly complex. Thus, views provide a more practical way.
The views also save us from writing the same queries over and over. Consider we have a highly complicated routine calculation that involves multiple filtering, aggregations, and nested select statements. It is much better to have it in a view than writing the query each time.
We also have more control over the access to the database using views. A table might contain sensitive information that can only be accessed by certain employees. Using views, we can grant access to only specific columns of a table.
Thank you for reading. Please let me know if you have any feedback.