Computer >> Computer tutorials >  >> Programming >> MySQL

How to create a MySQL view?


To create a MySQL view, use CREATE VIEW as in the below syntax −

create view yourViewName as select * from yourTableName;

Let us first create a table −

mysql> create table DemoTable1802
     (
     StudentId int,
     StudentName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1802 values(101,'John');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1802 values(102,'Carol');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1802 values(103,'Sam');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1802;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | John        |
|       102 | Carol       |
|       103 | Sam         |
+-----------+-------------+
3 rows in set (0.00 sec)

Here is the query to create view −

mysql> create view view_DemoTable1802 as select * from DemoTable1802;
Query OK, 0 rows affected (0.00 sec)

Display all records from the view using select statement −

mysql> select * from view_DemoTable1802;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | John        |
|       102 | Carol       |
|       103 | Sam         |
+-----------+-------------+
3 rows in set (0.00 sec)