Languages
[Edit]
EN

MySQL - Create view if not exist

0 points
Created by:
Waleed-Gates
322

In this article, we would like to show you how to create a view if it doesn't already exist in MySQL.

Quick solution:

CREATE VIEW IF NOT EXISTS `view_name` AS
SELECT `column1`, `column2`, ...
FROM `table_name`
WHERE condition;

Practical example

To show how the CREATE VIEW IF NOT EXIST statement works, we will use the following table:

MySQL - example data used with CREATE VIEW IF NOT EXISTS statement
MySQL - example data used with CREATE VIEW IF NOT EXISTS statement

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will create a view that shows all users from Spain if it doesn't already exist.

Query:

CREATE VIEW IF NOT EXISTS `Spain Users` AS
SELECT `name`, `email`
FROM `users`
WHERE `country` = 'Spain';

To see the view created with the query above simply use:

SELECT * FROM `Spain Users`;

Result:

MySQL - View created by CREATE VIEW (HeidiSQL) 
MySQL - View created by CREATE VIEW (HeidiSQL)

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`email` VARCHAR(100) NOT NULL,
	`country` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

insert_data.sql file:

INSERT INTO `users`
	(`name`, `email`, `country`)
VALUES
	('Tom', 'tom01@email.com', 'Poland'),
	('Chris','chris123@email.com', 'Spain'),
	('Jack','jack32@email.com', 'Spain'),
   ('Kim','kim103@email.com', 'Vietnam'),
   ('Marco','marco942@email.com', 'Italy'),
	('Kate','kate227@email.com', 'Spain'),
	('Nam','nam393@email.com', 'Vietnam');

MySQL - Problems

MySQL - Create view if not exist
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join