SQL VIEW
A VIEW is a virtual table based on the result of a SQL query. It doesnโt store data itself, but shows data dynamically from underlying tables โ great for simplifying complex queries or restricting access.
๐น Basic Syntax
-- Create a view
CREATE VIEW active_employees AS
SELECT id, name, department
FROM employees
WHERE status = 'active';
-- Query the view like a table
SELECT * FROM active_employees;
-- Update a view (if supported)
CREATE OR REPLACE VIEW active_employees AS
SELECT id, name, department, hire_date
FROM employees
WHERE status = 'active';
๐น Dropping a View
-- Drop the view
DROP VIEW active_employees;
๐น Key Uses
- Simplify complex queries
- Abstract logic for reusability
- Restrict access to specific data
- Enhance readability in reporting
๐ Note: Not all views are updatable. A view can only be updated if itโs based on a single table without group functions, DISTINCT, or joins.
๐ง Quick Recap
Key Point | Explanation |
---|---|
Definition | Virtual table based on a SELECT query |
Syntax | CREATE VIEW view_name AS SELECT... |
Usage | Used like a table in queries |
Benefits | Simplifies access, improves security |
Limitation | Not always updatable |
๐ก Use views to expose only whatโs needed โ perfect for clean, safe, reusable querying.