Sub topic 1
What a View Is and Why It Exists
Prerequisites
You should be comfortable with SELECT queries that use WHERE, ORDER BY and GROUP BY, joining tables with JOIN, and creating tables with CREATE TABLE and INSERT. The examples use the employees and departments tables from the tutorial's sample schema.
What a view is and why it exists
A view is a named query stored in the database. You select from it as if it were a table, but it holds no rows of its own. Each time you query it, the database runs the stored query and returns the result. A base table stores data. A view stores a definition.
Views exist for three main reasons. They hide complex joins, they give a stable name to a query that many people reuse, and they can limit which columns or rows a user sees.
Creating and querying your first view
Create a view with CREATE VIEW, a name, and a SELECT query:
CREATE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;
SELECT * FROM employee_directory WHERE department = 'Engineering';The second statement reads the view like a table. The database expands the view into its join, applies the filter, and returns the matching rows.
Naming the columns of a view
The view's column names come from the SELECT list. In the join above, both tables have a name column, so the alias AS department gives the second one a distinct name. You can also set the names explicitly with a column list after the view name:
CREATE VIEW employee_summary (employee_id, employee_name, monthly_salary) AS
SELECT id, name, salary / 12
FROM employees;Explicit names matter when the query contains expressions such as salary / 12. Without a name, the database assigns one, and that name varies between systems.
Using views to simplify and abstract queries
Suppose many reports need the employee-and-department join. Without a view, each report repeats the JOIN. With a view, the join lives in one place. If the join logic changes, you update the view once, and every query that uses it follows.
Views also hide details. Callers select department without knowing which tables supply it. You can later restructure the tables and keep the view's output stable for existing queries, as long as you update the view definition to match.
Exercise
Using employee_directory, write a query that returns only the names of employees in the 'Sales' department.
Show answer
SELECT name FROM employee_directory WHERE department = 'Sales';