✏️ Explanatory Question

What is a view and what are its advantages?

👁 12 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

70

What is a view and what are its advantages?

Level: Advanced — Views simplify complex queries and add a security layer over your tables.

A view is a virtual table based on the result of a stored SELECT query. It does not store data itself (unlike a real table) — instead, it dynamically pulls data from the underlying "base" tables each time it is queried.

Key point: A view is essentially a saved query with a name. You query it just like a table, but it always reflects the current data in the underlying tables.

Advantages of Views

  • Simplicity: Hide complex joins/logic behind a simple name.
  • Security: Expose only specific columns/rows, hiding sensitive data.
  • Abstraction: Underlying table structure can change without breaking apps.
  • Reusability: Reuse the same logic across many queries and reports.
  • Consistency: Everyone uses the same definition of "active customers", etc.

View vs Table

Aspect View Table
Stores data? No (virtual) Yes (physical)
Based on A SELECT query Actual storage
Always current? Yes (live data) Yes
Storage cost Minimal (definition only) Full data storage

Updatable vs Non-Updatable Views

Some views allow INSERT/UPDATE/DELETE that flow through to the base table. A view is not updatable if it contains: aggregate functions, GROUP BY, DISTINCT, UNION, or subqueries in the SELECT list.

Quick Example

-- Create a view that hides complexity and sensitive columns
CREATE VIEW active_employees AS
SELECT e.emp_id, e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id
WHERE e.status = 'Active';

-- Query it just like a table
SELECT * FROM active_employees WHERE dept_name = 'Engineering';

-- Updatable view (simple, no aggregates)
CREATE VIEW kolkata_emps AS
SELECT emp_id, name, salary FROM employees WHERE city = 'Kolkata'
WITH CHECK OPTION;   -- prevents inserts/updates that break the WHERE

-- WITH CHECK OPTION ensures new rows still match city = 'Kolkata'
UPDATE kolkata_emps SET salary = salary + 1000 WHERE emp_id = 1;

-- Drop a view
DROP VIEW active_employees;
WITH CHECK OPTION: This clause ensures that any data modified through the view still satisfies the view's WHERE condition — preventing rows from "disappearing" out of the view after an update.
Interviewer tip: The one-liner they want — "A view is a virtual table based on a stored SELECT query. It doesn't store data but simplifies complex queries, adds a security layer, and provides abstraction over the base tables."