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
ALTER VIEW view_name AS
SELECT column1, column 2
FROM table_name
WHERE condition;
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
Updatable in MySQL refers to the ability of executing UPDATE and DELETE queries in the
database view.
Problem Statement: You are a junior DB administrator in your organization. After appraisals, your
designation has been changed to Lead Data Scientist. Your Manager has asked you to update the role
change in the created 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
• 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 table created
earlier. The view must only allow the addition of employee with the Lead designation. Any other
designation entered 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.
QUERY
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
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
Output:
Creating Views Using WITH CASCADED CHECK OPTION: Example
QUERY
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
INSERT INTO V2(C) VALUES (5);
QUERY
ALTER VIEW V2 AS
SELECT C ALTER VIEW V2 AS
FROM V1
SELECT
WITH LOCAL CHECK OPTION; C 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.
SYNTAX
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:
VALUE INSERTION:
3. Create a table named project with multiple columns named emp_code, project_name and
project_status.
TABLE CREATION:
VALUE INSERTION:
INSERT INTO `sys`.`project` (`emp_code`, `project_name`, `project_status`) VALUES ('01', 'C++', 'DONE');
INSERT INTO `sys`.`project` (`emp_code`, `project_name`, `project_status`) VALUES ('02', 'C', 'DONE');
INSERT INTO `sys`.`project` (`emp_code`, `project_name`, `project_status`) VALUES ('03', 'JAVA', 'DONE');
INSERT INTO `sys`.`project` (`emp_code`, `project_name`, `project_status`) VALUES ('04', 'MySQL', 'DONE');
INSERT INTO `sys`.`project` (`emp_code`, `project_name`, `project_status`) VALUES ('05', 'Python', 'DONE');
Assisted Practice: Views One
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
Views are virtual tables in MySQL. The creation of indexes on a view is not possible. However, they
can be used for the views that are processed using the merge algorithm.
Knowledge
Check
A view can be created for _____________
3
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) specified
4 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) specified
4 in the view definition?
A. UNCHECK
B. WITH CHECK
C. CHECK
D. WITH
The purpose of the WITH CHECK OPTION is to ensure that all the UPDATE and INSERT satisfy the
condition(s) specified in the view definition.
Knowledge
Check
Which of the following statements is false about views?
5
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
Which of the following statements is false about views?
5
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 01: Upload the FreightRates.csv dataset to the lab
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
SQL views are created by selecting fields from one or more tables.
The WITH CHECK OPTION specifies the level of checking when data
is entered or modified using a view.