To create a view only if it does not already exist, you can use the following syntax −
CREATE OR REPLACE VIEW yourViewName AS SELECT *FROM yourTableName;
To understand the above syntax, let us create a table.
The query to create a table is as follows −
mysql> create table createViewDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command.
The query is as follows −
mysql> insert into createViewDemo(Name) values('John'); Query OK, 1 row affected (0.22 sec) mysql> insert into createViewDemo(Name) values('Carol'); Query OK, 1 row affected (0.15 sec) mysql> insert into createViewDemo(Name) values('Bob'); Query OK, 1 row affected (0.15 sec) mysql> insert into createViewDemo(Name) values('Sam'); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement.
The query is as follows −
mysql> select *from createViewDemo;
Here is the output −
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | +----+-------+ 4 rows in set (0.00 sec)
Here is the query to create a view only if it does not already exist −
mysql> CREATE OR REPLACE VIEW New_ViewDemo AS select *from createViewDemo; Query OK, 0 rows affected (0.13 sec)
Let us check the records of view.
The query is as follows −
mysql> select *from New_ViewDemo;
The following is The output −
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | +----+-------+ 4 rows in set (0.02 sec)