Lecture 5 - View in MySQL
Dr Hung Tran and Dr Tran Duc Minh
DATCOM Lab, Faculty of Data Science and Artificial Intelligence
College of Technology
National Economics University, Vietnam
Email:
[email protected] Mobile: 086-646-4048
1
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
1 Introduction to MySQL VIEW
Definition of a VIEW: A VIEW in MySQL is a virtual table that provides a way to look at data from
one or more tables without directly querying those tables. It’s a stored query that you can treat like a
table.
• Analogy: Think of a VIEW as a saved filter or lens through which you can consistently see specific
data, like saving a search in an e-commerce site that shows only items of a particular brand and
price range.
• Key Points:
– Virtual Table: A VIEW does not contain data itself; it dynamically fetches data from the
underlying tables when queried.
– Non-Persistent: The data in a VIEW is not stored; it’s just the result of the query at the
time of execution.
Example: Suppose you frequently need to see a list of active customers (those who have placed an
order in the last year). Instead of writing the same query over and over, you can create a VIEW to
encapsulate this logic.
@DATCOM Lab 2
@DATCOM Lab
2 Creating a VIEW
Basic Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
FROM table_name
WHERE condition;
Detailed Example:
• Scenario: You have two tables, customers and orders. You want to create a VIEW that shows which customers have placed orders in the last 30 days.
CREATE VIEW recent_customer_orders AS
SELECT customers.customer_id, customers.customer_name, orders.order_id, orders.order_date
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_date > CURDATE() - INTERVAL 30 DAY;
Explanation: This VIEW, recent customer orders, filters data to show only those customers who placed orders in the last 30 days. It simplifies querying
for this specific information repeatedly.
3
Interactive Example:
• Exercise: Create a VIEW called high value customers that lists customers who have spent more than $10,000.
CREATE VIEW high_value_customers AS
SELECT customers.customer_id, customers.customer_name, SUM(orders.order_amount) AS total_spent
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_id
HAVING total_spent > 10000;
Discussion: How does this VIEW help in quickly identifying key customers? How would you use this in a business context?
3 Querying Data from a VIEW
Basic Syntax:
SELECT * FROM view_name;
Detailed Example:
@DATCOM Lab
• Using the recent customer orders VIEW:
SELECT * FROM recent_customer_orders;
Explanation: This retrieves all records from the recent customer orders VIEW, effectively running the underlying SELECT statement.
Advanced Example:
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
• Scenario: You want to see only the names of customers who placed an order on a specific date.
SELECT customer_name FROM recent_customer_orders
WHERE order_date = ’2024-08-01’;
Explanation: This query filters the data within the VIEW based on the order date, demonstrating how you can interact with a VIEW just like a regular
table.
4 Modifying a VIEW
ALTER VIEW Syntax: Sometimes you need to update the VIEW to include more information or change its logic.
ALTER VIEW view_name AS
4
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Detailed Example:
• Scenario: You realize you need to include the total amount of each order in the recent customer orders VIEW.
ALTER VIEW recent_customer_orders AS
SELECT customers.customer_id, customers.customer_name, orders.order_id, orders.order_date, orders.order_amount
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_date > CURDATE() - INTERVAL 30 DAY;
Explanation: The recent customer orders VIEW is now updated to include order amount. This change is reflected immediately whenever the VIEW is
queried.
Interactive Example:
• Exercise: Modify the high value customers VIEW to include the customer’s email address.
@DATCOM Lab
ALTER VIEW high_value_customers AS
SELECT customers.customer_id, customers.customer_name, customers.email, SUM(orders.order_amount) AS total_spent
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_id
HAVING total_spent > 10000;
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
Discussion: Why might it be important to include additional customer contact information in this VIEW?
5 Dropping a VIEW
Syntax: If a VIEW is no longer needed, you can drop it from the database.
DROP VIEW view_name;
Detailed Example:
• Scenario: The business decides that tracking recent customer orders is no longer relevant. Drop the recent customer orders VIEW.
DROP VIEW recent_customer_orders;
5
Explanation: This removes the recent customer orders VIEW from the database, meaning you can no longer query it.
Interactive Example:
• Exercise: Drop the high value customers VIEW.
DROP VIEW high_value_customers;
Discussion: What are the consequences of dropping a VIEW? How would you ensure that important VIEWS are not accidentally dropped?
6 Advantages of Using VIEWs
Simplicity:
• Example: A VIEW simplifies complex queries. Instead of rewriting a long query multiple times, you encapsulate it in a VIEW.
• Scenario: A company tracks employee hours across multiple projects. A VIEW employee hours could simplify reporting by summing hours per employee
across projects.
@DATCOM Lab
CREATE VIEW employee_hours AS
SELECT employee_id, SUM(hours_worked) AS total_hours
FROM project_hours
GROUP BY employee_id;
Data Security:
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
• Example: VIEWS can expose only necessary data to users, hiding sensitive information.
• Scenario: You could create a VIEW for customer service agents that only shows customer names and order statuses, hiding payment details.
CREATE VIEW customer_support_view AS
SELECT customer_name, order_id, order_status
FROM orders
WHERE order_status != ’Delivered’;
Reusability:
• Example: Once a VIEW is created, it can be used across different applications, reports, and users without duplicating SQL logic.
• Scenario: A VIEW that calculates monthly sales totals can be used by both the finance department and marketing team for their respective analyses.
6
CREATE VIEW monthly_sales_totals AS
SELECT MONTH(order_date) AS month, SUM(order_amount) AS total_sales
FROM orders
GROUP BY MONTH(order_date);
7 Limitations and Considerations
Performance:
• Example: Since VIEWS do not store data, querying a VIEW can be slower than querying a physical table, especially if the underlying query is complex.
• Scenario: If a VIEW involves multiple joins and aggregations, it might be better to use a materialized VIEW or store the result in a temporary table.
Updatability:
• Example: Not all VIEWS are updatable. Simple VIEWS based on a single table without aggregations are generally updatable, but complex VIEWS with
joins, subqueries, or aggregations are not.
• Scenario: A VIEW showing total sales per customer is not updatable because it aggregates data.
@DATCOM Lab
CREATE VIEW total_sales_per_customer AS
SELECT customer_id, SUM(order_amount) AS total_spent
FROM orders
GROUP BY customer_id;
Interactive Question: What might happen if you try to update this VIEW?
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
Dependency:
• Example: If the underlying table structure changes (e.g., a column is dropped), the VIEW may break.
• Scenario: If the orders table is altered to remove the order date column, the recent customer orders VIEW will no longer work.
Interactive Question: How would you handle changes to underlying tables that might affect your VIEWS?
8 Practical Examples and Use Cases
Example 1: Sales Reports:
• Scenario: Create a VIEW sales by region to summarize sales data by region for easy reporting.
7
CREATE VIEW sales_by_region AS
SELECT region, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY region;
Explanation: This VIEW provides a quick summary of total sales by region, useful for generating regional sales reports.
Interactive Example: How could you modify this VIEW to include a breakdown by product category?
Example 2: User Permissions:
• Scenario: Create a VIEW user data that allows users to see only their own data, ensuring privacy and security.
CREATE VIEW user_data AS
SELECT user_id, user_name, data
FROM data_table
WHERE user_id = CURRENT_USER();
Explanation: This VIEW ensures each user can only access their own data, enhancing security.
Interactive Example: How would you use this in a multi-tenant application where different companies use the same database?
@DATCOM Lab
9 Hands-On Exercise
Exercise 1: Create a VIEW for Employee Reports
• Task: Create a VIEW called employee departments that shows all employees and their respective department names.
CREATE VIEW employee_departments AS
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
SELECT employees.employee_id, employees.employee_name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;
Discussion: How does this VIEW simplify generating reports on employee departments? How would you extend it to include employee salaries?
Exercise 2: Modify a VIEW
• Task: Modify the employee departments VIEW to include the employee’s salary.
ALTER VIEW employee_departments AS
SELECT employees.employee_id, employees.employee_name, departments.department_name, employees.salary
FROM employees
JOIN departments ON employees.department_id = departments.department_id;
8
Discussion: What impact does this change have on the usefulness of the VIEW? How might you further enhance this VIEW?
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU
10 Summary
Key Points Recap:
• VIEWs Simplify Queries: They encapsulate complex logic, making it easier to work with and
reuse.
• VIEWs Enhance Security: By exposing only necessary data and hiding sensitive information.
• VIEWS Have Limitations: Performance considerations, updatability issues, and dependencies
on underlying table structures.
Final Thoughts: Encourage students to use VIEWS to streamline their SQL operations, improve
security, and make their queries more maintainable.
11 Q&A Session
Interactive Q&A:
• Invite students to ask questions about specific scenarios where they might use VIEWS.
• Pose questions such as:
– “How would you decide when to use a VIEW versus writing a direct query?”
– “Can you think of a scenario where a VIEW would be inappropriate?”
@DATCOM Lab 9