Lesson 10 Working With Views
Lesson 10 Working With Views
Learning Objectives
In SQL, a view refers to a virtual table. It can be created by selecting fields from one or more
tables.
SYNTAX
Problem Scenario: You are a data analyst in your company, and you are asked to create a
temporary table of employees with salary more than 22000.
Objective: Use the view command to create a temporary table for the condition mentioned
above.
Creating a View From a Single Table: Example
Step 1: Create a table named employee records with the following data:
Step 2: Use the following view syntax to create a temporary table of employees with salary
more than 22000.
QUERY
Output:
Deleting or Dropping a View
SYNTAX
SYNTAX
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2,…
FROM table_name
WHERE condition;
Updating or Modifying a View: Example
Suppose you want to display different columns in the same view name created earlier, then
you can use the replace view command.
Output:
QUERY
ALTER VIEW command allows you to change the SQL statements present in a view.
SYNTAX
If you want to change the columns of a created Emp_View, then you use the alter command.
Output:
QUERY
Renaming tables and views in MySQL use the same namespace. Therefore, you can use the
RENAME_TABLE statement to rename a view.
SYNTAX
Consider the same employee records table and its view Emp view. If you want to rename the
view name that focuses more on the salary aspect, you can use the following syntax:
QUERY
Now, the output remains the same as the earlier view, but the view name must be changed to
view the results.
Replacing a View
REPLACE VIEW allows you to replace an existing view with a newly specified view.
SYNTAX
In CREATE VIEW command, there is an optional clause called ALGORITHM. This specifies how
the view must be processed.
TEMPLATE
UNDEFINED MERGE
3 1
Workflow of View Processing Algorithms
In MERGE, the text of a statement is merged in such a way that parts of the view definition
replace the corresponding parts of the statement.
Problem Statement: You are the junior DB administrator in your organization, and your
manager has asked you to change the column headers of the employee table and create a
new view.
Objective: Create a view with the merge algorithm and specify the column headers with the
changes.
Workflow of View Processing Algorithms (Merge): Example
Step 1: Create a view with the algorithm as merge. Include column headers that must be
merged or changed in the view.
QUERY
Step 2: Use the select command to extract the data that satisfies the given condition.
QUERY Output:
In TEMPTABLE, the results from the view are retrieved into a temporary table, which is then
used to execute the statement.
The TEMPTABLE algorithm is less efficient than the MERGE algorithm, as MySQL creates a
temporary table to store data from the base table.
Workflow of View Processing Algorithms
UNDEFINED is the default algorithm applied when you create a view without specifying the
ALGORITHM clause.
MySQL decides to go either with MERGE or TEMPTABLE but prefers MERGE as it is more
efficient.
Updatable View
Updatable in MySQL refers to the ability of executing UPDATE and DELETE queries in the
database view.
Objective: Create a view for employees, using the employee table, and update the record
for the employee named Roy.
Updatable View: Example
QUERY
Step 2: Update the role name of Roy using the following code
QUERY
UPDATE Role_Name_After_Appraisal
SET Role_Name = "Lead Data Scientist“
WHERE
Emp_Name = "Roy";
Updatable View: Example
Step 3: Use the select view command as shown below to view the changes
Output:
QUERY
Updatable in MySQL refers to the ability of executing UPDATE and DELETE queries in the
Is an optional clause database view. Specifies the level of checking
when data is inserted or updated
through a view
• If specified, every row that is inserted or updated through the view must conform to
the definition of the view.
• If it is not specified, insert and update operations that are performed on the view are
not checked for conformance to view the definition.
Creating Views Using WITH CHECK OPTION: Example
Problem Statement: You are the junior DB administrator in your organization, and your
Manger has asked you to create a view that displays the Lead Data Scientist role from the
employee in
Updatable table created
MySQL earlier.
refers to theThe viewofmust
ability only allow
executing the addition
UPDATE of employee
and DELETE queries inwith
the
the Lead designation. Any other designation
databaseentered
view. must prompt an error.
Objective: Create a view using the WITH CHECK OPTION to avoid addition of other
designations.
Creating Views Using WITH CHECK OPTION: Example
Step 1: Create a view using the WITH CHECK OPTION to avoid addition of other
designations.
Updatable in MySQL refers to the ability of executing UPDATE and DELETE queries in the
database view.
QUERY
DELIMITER &&
CREATE OR REPLACE VIEW Lead_DS AS SELECT Emp_ID,
Emp_Name, Role_name, Dept, Experience
FROM Emp_Table
WHERE Role_name LIKE "%Lead“
WITH CHECK OPTION;
END &&
Creating Views Using WITH CHECK OPTION: Example
Step 2: Insert a record of an employee whose designation is not Lead Data Scientist.
QUERY
Output:
When you insert the above values, you get the error message shown above.
Creating Views Using WITH CASCADED CHECK OPTION
This clause specifies that every row A row cannot be retrieved through the
that is inserted or updated through view if it does not conform to the
a view must conform to the definition of view.
definition of the view.
If the keyword CASCADED is not specified with the WITH CHECK OPTION, then it is by default
taken as CASCADED.
Creating Views Using WITH CASCADED CHECK OPTION: Example
QUERY QUERY
CREATE TABLE T1 (C INT);
CREATE TABLE T1 (C INT); CREATE VIEW V2
CREATE VIEW V1 AS SELECT C AS
CREATE VIEW V1 AS SELECT C
SELECT C FROM V1
FROM
FROM T1 WHERE T1
C >10; WHERE C >10; WITH CASCADED CHECK OPTION;
INSERT INTO V1 (C) VALUES (5); INSERT INTO V2(C) VALUES (5);
INSERT INTO V1 (C) VALUES (5);
Output:
Creating Views Using WITH CASCADED CHECK OPTION: Example
CREATE VIEW V3
QUERY
AS
CREATE VIEW V3
AS SELECT C
SELECT C QUERY
FROM V2 FROM V2
WHERE C < 20; INSERT INTO V3(C) VALUES (30);
WHERE C < 20;
INSERT INTO V3(C) VALUES (8); INSERT INTO V3(C) VALUES (30);
INSERT INTO V3(C) VALUES (8);
Output:
Creating Views Using WITH LOCAL CHECK OPTION
WITH LOCAL CHECK OPTION clause is same as WITH CASCADED CHECK OPTION clause, except
that you can update a row in such a way that it cannot be retrieved through the view.
This clause specifies that every row that is inserted or updated through a view must
conform to the definition of the view.
This occurs when the view is directly or indirectly dependent on a view that is defined without a
WITH CHECK OPTION.
Creating Views Using WITH LOCAL CHECK OPTION: Example
QUERY QUERY
ALTER VIEW V2 AS INSERT INTO V2(C) VALUES (5);
SELECT C
ALTER VIEW V2 AS
FROM V1
WITH LOCAL CHECK SELECT
OPTION; C
FROM V1 QUERY
For views using WITH LOCAL CHECK OPTION, MySQL checks the rules of views that have a WITH
LOCAL CHECK OPTION and a WITH CASCADED CHECK OPTION.
Show Views
In MySQL, views are treated as tables with the type as VIEW. To list or show all the views in the
selected database, you need to use the SHOW FULL TABLES command.
This clause specifies that every row that is inserted or updated through a view must
SYNTAX
conform to the definition of the view.
Duration: 15 minutes
Problem Statement: Design a VIEW in MySQL which displays the employee’s name, location,
and project name from two different tables: data_scientist and project.
Assisted Practice: Views One
Steps to be performed:
1. Create a database with a suitable name and then create a table named data_scientist with
multiple columns named emp_code, name, location, time, and designation.
TABLE CREATION:
CREATE TABLE `data_scientist`(
`emp_code` int NOT NULL,
`name` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
`time` int NOT NULL,
`designation` varchar(45) NOT NULL,
PRIMARY KEY (`emp_code`));
Assisted Practice: Views One
VALUE INSERTION:
3. Create a table named project with multiple columns named emp_code, project_name, and
project_status.
TABLE CREATION:
VALUE INSERTION:
5. Write a query for creating a VIEW named as display for displaying the desired contents of both the tables.
VIEW Creation:
Duration: 20 mins
Problem statement: As an SQL expert, you have been asked to analyze the customer purchase data preferably
using VIEWS so that the other concerned users only have access to the data they need, while protecting other
data in the same table.
Assisted Practice: Views Two
Steps to be performed:
Step 01: Create a table named “customer” containing the columns ORDER_ID, ORDER_DATE, CUST_ID,
PROD_ID, UNIT_QTY, and WEIGHT
CREATE
DROP TABLE IF EXISTS customer;
CREATE TABLE customer (
ORDER_ID INTEGER,
CUST_ID TEXT,
PROD_ID TEXT,
UNIT_QTY INT,
WEIGHT DOUBLE);
Assisted Practice: Views Two
Output:
Assisted Practice: Views Two
SQL Query
Output:
Assisted Practice: Views Two
Step 03: Write a query to create a VIEW using the customer table capturing the details of customers who
have purchased more than 2000 units
SQL Query
CREATE VIEW C1 AS
SELECT * FROM customer WHERE UNIT_QTY>2000;
Output:
Assisted Practice: Views Two
Step 04: Write a query to create a VIEW using the VIEW created in previous step with the columns CUST_ID
and UNIT_QTY and use CHECK OPTION to ensure records where the quantity is greater than 3000 are not
allowed
SQL Query
CREATE VIEW C2 AS
SELECT CUST_ID, UNIT_QTY FROM C1 WHERE UNIT_QTY<=3000
WITH CASCADED CHECK OPTION;
Output:
Assisted Practice: Views Two
Step 05: Write an insert query to add a record value to the VIEW created in step 04, with CUST_ID and
UNIT_QTY values. Keep the UNIT_QTY values at 1000, which violates the view's criteria, which only allows
values more than 2000 and less than or equal to 3000.
Output:
Assisted Practice: Views Two
Step 06: Write an insert query to add a record value to the VIEW created in step 04, with CUST_ID and
UNIT_QTY values. Keep the UNIT_QTY values at 3500, which violates the view's criteria, which only allows
values more than 2000 and less than or equal to 3000.
Output:
Knowledge Check
Knowledge
Check
Which of the following commands is used to display all the views?
1
A. SHOW VIEWS
B. DISPLAY VIEWS
A. SHOW VIEWS
B. DISPLAY VIEWS
A. DISPLAY
B. FILTER
C. INDEX
D. DROP
Knowledge
Check
What cannot be done on a view?
2
A. DISPLAY
B. FILTER
C. INDEX
D. DROP
A. One table
B. Many tables
C. Another view
A. One table
B. Many tables
C. Another view
Views can be generated using a single table, multiple tables, or an existing view.
Knowledge
Check Which view option ensures that all UPDATE and INSERT satisfy the condition(s)
4 specified in the view definition?
A. UNCHECK
B. WITH CHECK
C. CHECK
D. WITH
Knowledge
Check Which view option ensures that all UPDATE and INSERT satisfy the condition(s)
4 specified in the view definition?
A. UNCHECK
B. WITH CHECK
C. CHECK
D. WITH
B. To create a view, a user must have the appropriate system privilege according to the specific
implementation.
D. We can update a view if it has multiple database relations in the FROM clause.
Knowledge
Check
5 Which of the following statements is false about views?
B. To create a view, a user must have the appropriate system privilege according to the specific
implementation.
D. We can update a view if it has multiple database relations in the FROM clause.
We can only update a view if the FROM clause has a single database relation.
Knowledge
Check
Can we insert and delete rows in a view?
6
A. Yes
B. No
A. Yes
B. No
Problem statement:
As an analyst of a port inspection team at a freight company, you’ve been asked to
perform analyses using VIEWS.
Objective:
To analyze the transportation of orders of various quantities across different ports
Lesson-End Project: Freight Company Analysis
Tasks to be performed:
Step 03: Create a VIEW and name it FR_GROUND and use it to display the record
count of the FreightRates table for the orders transported via GROUND
Step 04: Create a VIEW, name it FR_AIR, and use it to display the record count of the
FreightRates table for the orders transported via AIR
Lesson-End Project: Freight Company Analysis
Tasks to be performed:
Step 05: Create a VIEW and name it FR_V1, with mode_dsc and the average rate for
each type of value in the mode_dsc column
Step 06: Alter the VIEW FR_V1 by replacing the column mode_dsc with carrier
Step 08: Create a VIEW with the carrier and mode_dsc columns using WITH CHECK
option to make sure that mode_dsc accepts no entry other than AIR or GROUND
Key Takeaways