EN
MySQL - Create view
0 points
In this article, we would like to show you how to create a view in MySQL.
Quick solution:
xxxxxxxxxx
1
CREATE VIEW `view_name` AS
2
SELECT `column1`, `column2`, ...
3
FROM `table_name`
4
WHERE condition;
To show how the CREATE VIEW
statement works, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will create a view that shows all users from Spain.
Query:
xxxxxxxxxx
1
CREATE VIEW `Spain Users` AS
2
SELECT `name`, `email`
3
FROM `users`
4
WHERE `country` = 'Spain';
To see the view created with the query above simply use:
xxxxxxxxxx
1
SELECT * FROM `Spain Users`;
Result:

If you try to create view that already exist with CREATE VIEW
query you will get an error:

If you try to CREATE VIEW IF NOT EXISTS
you will get a warning instead:

Note:
Go to this article to see a practical example:
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`email` VARCHAR(100) NOT NULL,
5
`country` VARCHAR(15) NOT NULL,
6
PRIMARY KEY (`id`)
7
)
8
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `email`, `country`)
3
VALUES
4
('Tom', 'tom01@email.com', 'Poland'),
5
('Chris','chris123@email.com', 'Spain'),
6
('Jack','jack32@email.com', 'Spain'),
7
('Kim','kim103@email.com', 'Vietnam'),
8
('Marco','marco942@email.com', 'Italy'),
9
('Kate','kate227@email.com', 'Spain'),
10
('Nam','nam393@email.com', 'Vietnam');