← Back to Chapters

MySQL Views

?️ MySQL Views

? Quick Overview

A view in MySQL is a virtual table defined by a SELECT query. It behaves like a table (rows & columns) but does not store data itself — it shows the result set produced by its underlying query whenever accessed.

? Key Concepts

  • Virtual table: A view is defined by a query; the data comes from base tables.
  • Encapsulation: Simplifies complex queries and encapsulates business logic.
  • Security: Restrict access to sensitive columns by exposing a view instead of the full table.
  • Performance: Views can simplify queries but complex views may impact performance.

? Syntax / Theory

? View Syntax
-- CREATE VIEW syntax: define a virtual table from a SELECT
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

? Code Examples

? Create a simple view
-- Create a view showing employees aged 18 or older
CREATE VIEW EmployeeView AS
SELECT Name, Age, Salary
FROM Employees
WHERE Age >= 18;
? Query the view
-- Query the view just like a table to retrieve its rows
SELECT * FROM EmployeeView;
? Create a view joining two tables
-- Combine employees with their department names
CREATE VIEW EmpDept AS
SELECT e.Id, e.Name, d.DepartmentName, e.Salary
FROM Employees e
JOIN Departments d ON e.DepartmentId = d.Id;

? Explanation

  • CREATE VIEW: Defines the view name and the SELECT that produces its rows.
  • The view does not persist data — it runs the SELECT when you query the view.
  • Useful for simplifying repeated queries, enforcing column-level access, and presenting derived datasets.

Live Output (conceptual)

When you run SELECT * FROM EmployeeView; MySQL executes the view's SELECT and returns the resulting rows. The view acts as a read-only lens over your underlying tables (unless it's an updatable view).

? Use Cases

  • Reporting layers: provide simplified datasets to BI tools.
  • Security: provide limited columns to certain roles.
  • Compatibility: abstract schema changes from application queries by updating the view instead of app code.

? Tips & Best Practices

  • Use views to hide sensitive columns (e.g., exclude SSN from a view for most users).
  • Keep view logic simple for performance — avoid heavy aggregation or nested views when possible.
  • Index base tables appropriately; views themselves don't have indexes (unless materialized by other means).
  • Test query plans for critical views to spot performance bottlenecks.

? Try It Yourself

  • Create a view that joins Employees and Departments showing employee name and department.
  • Create a restricted view exposing only Name and DepartmentName for regular users.
  • Experiment: convert a SELECT with GROUP BY into a view and compare performance vs running the SELECT directly.