SQL Views

What is a View?

A view is a virtual table based on a SQL query.

It does not store data but shows results from underlying tables.

Creating a View

CREATE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 50000;

Using a View

SELECT * FROM high_salary_employees;

Updating a View

CREATE OR REPLACE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 60000;

Dropping a View

DROP VIEW high_salary_employees;

Views with Joins

CREATE VIEW employee_departments AS
SELECT e.name, d.department_name
FROM employees e
JOIN departments d
ON e.department_id = d.id;

Full Example

CREATE VIEW employee_summary AS
SELECT name, salary
FROM employees;

SELECT * FROM employee_summary;

Why Views are Important

  • Simplify complex queries
  • Reuse query logic
  • Improve readability
  • Enhance data security

Common Mistakes

  • Thinking views store data
  • Not updating views when data changes
  • Overusing views unnecessarily

Practice

Create a view and query it.

CREATE VIEW my_view AS
SELECT * FROM table_name;

SELECT * FROM my_view;

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic