INSERT INTO table if a table exists in MySQL else implement CREATE TABLE and create the table

MySQLMySQLi Database

Here’s the syntax to check whether the table already exists using the CREATE TABLE IF NOT EXISTS −

create table if not exists yourTableName
(
   yourColumnName1 dataType,
   .
   .
   .
   .
   N
);
insert into yourTableName values(yourValue1,.......N);

Let us first create a table −

mysql> create table if not exists DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentSubject varchar(100)
);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentSubject) values('Java');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(StudentSubject) values('MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentSubject) values('C');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------------+
| StudentId | StudentSubject |
+-----------+----------------+
|         1 | Java           |
|         2 | MySQL          |
|         3 | C              |
+-----------+----------------+
3 rows in set (0.00 sec)
raja
Published on 26-Sep-2019 11:10:49
Advertisements