Create a View from a SELECT Query
In this step, you will learn how to create a view in MySQL from a SELECT
query. A view is a virtual table based on the result-set of an SQL statement. Views are useful for simplifying complex queries, hiding data complexity, and providing a level of abstraction for data access.
First, let's connect to the MySQL server. Open a terminal in the LabEx VM. You should already be in the ~/project
directory.
mysql -u root -p
When prompted, enter the root password. If you haven't set a root password, just press Enter.
Now, let's create a database named company
.
CREATE DATABASE company;
Next, switch to the company
database.
USE company;
Let's create a simple table named employees
with some sample data.
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
salary DECIMAL(10, 2),
department VARCHAR(50)
);
INSERT INTO employees (id, first_name, last_name, salary, department) VALUES
(1, 'John', 'Doe', 60000.00, 'Sales'),
(2, 'Jane', 'Smith', 75000.00, 'Marketing'),
(3, 'Robert', 'Jones', 50000.00, 'Sales'),
(4, 'Emily', 'Brown', 80000.00, 'Engineering'),
(5, 'Michael', 'Davis', 65000.00, 'Marketing');
Now, let's create a view named sales_employees
that shows only the employees from the 'Sales' department.
CREATE VIEW sales_employees AS
SELECT id, first_name, last_name, salary
FROM employees
WHERE department = 'Sales';
This statement creates a view named sales_employees
. The view selects the id
, first_name
, last_name
, and salary
columns from the employees
table, but only for rows where the department
is 'Sales'.
To verify that the view has been created, you can describe it:
DESCRIBE sales_employees;
This command will show the structure of the sales_employees
view, similar to describing a table.
You can also query the view like a regular table:
SELECT * FROM sales_employees;
This will display all the employees in the Sales department, based on the data in the employees
table.
+------+------------+-----------+----------+
| id | first_name | last_name | salary |
+------+------------+-----------+----------+
| 1 | John | Doe | 60000.00 |
| 3 | Robert | Jones | 50000.00 |
+------+------------+-----------+----------+
2 rows in set (0.00 sec)
You have now successfully created a view from a SELECT
query.