Welcome to our SQL Views Tutorial! In this lesson, we'll explore what SQL Views are, why they are useful, and how to create them. By the end, you'll be able to create your own views and use them to simplify complex database queries. 💡
A SQL View is a virtual table based on the result-set of an SQL SELECT statement that does not modify the data but only retrieves it. It is a named SELECT statement that is stored in a database and can be used like a table. 📝
Let's create a simple view. For this example, we'll assume we have a employees table with columns id, first_name, last_name, and department_id.
-- Create the employees table
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT
);
-- Insert some data
INSERT INTO employees (id, first_name, last_name, department_id)
VALUES
(1, 'John', 'Doe', 101),
(2, 'Jane', 'Smith', 102),
(3, 'Alice', 'Johnson', 103);Now, let's create a view that shows the names and departments of all employees.
-- Create the view
CREATE VIEW employee_dept AS
SELECT first_name, last_name, department_id, (SELECT department_name FROM departments WHERE departments.id = employees.department_id) AS department_name
FROM employees;In this view, we're selecting the first_name, last_name, and department_id from the employees table, and we're also joining the departments table to get the department names.
You can now use the employee_dept view like a regular table:
-- Query the view
SELECT * FROM employee_dept;What is a SQL View?
SQL views can be updated, deleted, and indexed, and you can create views based on other views. Let's create an updated view that includes the employee salaries.
-- Create a salaries table
CREATE TABLE salaries (
id INT PRIMARY KEY,
employee_id INT,
salary DECIMAL(10, 2)
);
-- Insert some data
INSERT INTO salaries (id, employee_id, salary)
VALUES
(1, 1, 50000),
(2, 2, 60000),
(3, 3, 55000);
-- Create a view that includes the salary
CREATE VIEW employee_dept_salary AS
SELECT employee_dept.*, salaries.salary
FROM employee_dept
JOIN salaries ON employee_dept.id = salaries.employee_id;Now, you can use the employee_dept_salary view to get the names, departments, and salaries of all employees.
What does a SQL View do?
That's it for our SQL Views Introduction! In the next lessons, we'll dive deeper into SQL Views, covering topics like updating views, deleting views, indexing views, and more. Stay tuned! 💡
In this lesson, we learned what SQL Views are, why they are useful, and how to create them. We created a simple view and an updated view, and we discussed their applications in real projects. 📝
What are SQL Views used for?