Views & Virtual Tables

Views & Virtual Tables in MySQL: A View is a stored, named SQL query that behaves conceptually like a virtual table.

A View is a stored, named SQL query that behaves conceptually like a virtual table. A view does not physically duplicate data on disk; whenever you query a view, MySQL dynamically executes the underlying query definition and presents the formatted results.


1. Why Use Views in Production?

  1. Security & Column Masking: Expose public customer information while completely hiding confidential columns like passwords, social security numbers, or profit margins.
  2. Query Simplification: Encapsulate complex 5-table joins with nested CASE statements behind a clean, simple table name that analytics teams can easily query.
  3. Data Consistency: Ensure all dashboard queries use identical calculations for key metrics (like Daily Active Users or Customer Lifetime Value).

2. Creating and Querying Views

-- Create a view that combines users with their aggregated spending metrics
CREATE VIEW v_customer_summary AS
SELECT 
  u.id AS customer_id,
  u.username,
  u.email,
  COUNT(o.id) AS total_orders,
  COALESCE(SUM(o.amount), 0) AS lifetime_value,
  MAX(o.order_date) AS latest_order_date
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.username, u.email;

-- Now, query the view as if it were a physical table:
SELECT username, lifetime_value 
FROM v_customer_summary 
WHERE lifetime_value >= 1000.00
ORDER BY lifetime_value DESC;

Managing Views:

-- Modify an existing view definition
CREATE OR REPLACE VIEW v_customer_summary AS ...;

-- Remove a view
DROP VIEW IF EXISTS v_customer_summary;

3. Updatable Views & WITH CHECK OPTION

Under certain strict conditions, you can run INSERT or UPDATE statements directly on a View! For a view to be updatable, it must have a 1-to-1 relationship with the underlying table (no JOIN, GROUP BY, HAVING, or UNION).

The WITH CHECK OPTION prevents updates that would cause rows to disappear from the view:

CREATE VIEW v_active_users AS
SELECT id, username, email, status
FROM users
WHERE status = 'active'
WITH CHECK OPTION;

-- ✅ Permitted: Keeps status 'active'
UPDATE v_active_users SET email = 'new@example.com' WHERE id = 1;

-- ❌ REJECTED by CHECK OPTION: Attempting to change status to 'banned' fails!
UPDATE v_active_users SET status = 'banned' WHERE id = 1;

4. Common Table Expressions (CTEs)

Introduced in MySQL 8.0, Common Table Expressions (CTEs) are temporary, named result sets defined within the scope of a single query using the WITH clause. They are far cleaner and more readable than messy subqueries.

Standard (Non-Recursive) CTE:

WITH RegionalRevenue AS (
  SELECT region, SUM(amount) AS total_sales
  FROM sales
  GROUP BY region
)
SELECT region, total_sales
FROM RegionalRevenue
WHERE total_sales > (SELECT AVG(total_sales) FROM RegionalRevenue);

Recursive CTEs: Traversing Hierarchical Trees

Recursive CTEs repeatedly execute themselves to traverse nested hierarchies like organizational charts, category trees, or social networks:

-- Traverses an employee-manager hierarchy to find the entire reporting chain
WITH RECURSIVE OrgChart AS (
  -- Anchor Member: Start with the CEO (manager_id IS NULL)
  SELECT id, name, manager_id, 1 AS depth
  FROM employees
  WHERE manager_id IS NULL
  
  UNION ALL
  
  -- Recursive Member: Join employees to their managers in the CTE
  SELECT e.id, e.name, e.manager_id, oc.depth + 1
  FROM employees e
  INNER JOIN OrgChart oc ON e.manager_id = oc.id
)
SELECT depth, name FROM OrgChart ORDER BY depth, name;