← Back to Chapters

MySQL VIEW

? MySQL VIEW

? Quick Overview

A MySQL VIEW is a virtual table that consists of a stored query. It allows you to represent the result of a SELECT query as a table, simplifying complex queries and presenting data in a more understandable form. Views are useful for hiding the complexity of the underlying data structure while providing a simple interface for querying.

? Key Concepts

  • Views are virtual tables based on SELECT queries
  • They do not store data physically
  • They simplify and secure data access

⚙️ Syntax & Theory

The CREATE VIEW statement stores a SELECT query under a name. Once created, it can be queried like a normal table.

? View Code Example
-- General syntax for creating a view
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;

? Code Examples

? View Code Example
-- Creating a view for Sales department employees
CREATE VIEW employee_view AS
SELECT first_name, last_name, email
FROM employees
WHERE department = 'Sales';

? Using a View

? View Code Example
-- Querying data from a view like a table
SELECT * FROM employee_view;

✏️ Updating Data Through a View

? View Code Example
-- Updating underlying table data through a simple view
UPDATE employee_view
SET email = 'new_email@example.com'
WHERE first_name = 'John';

?️ Dropping a View

? View Code Example
-- Removing an existing view
DROP VIEW employee_view;

? Live Output / Explanation

Views always reflect the current data in the underlying tables. When the base table changes, the view output changes automatically.

? Interactive Explanation

Think of a view as a saved SQL filter. Instead of writing complex joins repeatedly, you query a clean, reusable virtual table.

? Use Cases

  • Simplifying complex queries
  • Restricting access to sensitive columns
  • Creating reusable data representations
  • Improving query readability

✅ Tips & Best Practices

  • Use views to encapsulate complex logic
  • Keep views simple for better performance
  • Index underlying tables properly
  • Avoid updating views with joins or aggregates

? Try It Yourself

  • Create a view with a WHERE clause
  • Query and update data using the view
  • Drop a view and recreate it with changes
  • Build a view combining customer and order data
  • Create a department-wise average salary view