Create a table if it does not already exist and insert a record in the same query with MySQL

MySQLMySQLi Database

Use CREATE TABLE IF NOT EXISTS for this as shown in the below syntax −

create table if not exists yourTableName
   yourColumnName1 dataType,
   yourColumnName2 dataType,
   yourColumnName3 dataType,
as select yourValue1 as yourColumnName1 , yourValue2 as yourColumnName2 , yourValue3 as yourColumnName3,.............................N;

Let us first create a table and insert value if the table does not already exist −

mysql> create table if not exists DemoTable
   id int,
   FirstName varchar(20),
   LastName varchar(20)
as select 100 as id, 'John' as FirstName , 'Smith' as LastName;
Query OK, 1 row affected (0.65 sec)
Records: 1 Duplicates: 0 Warnings: 0

Let us now display the records −

mysql> select *from DemoTable;

This will produce the following output −

| id   | FirstName | LastName |
| 100  | John      | Smith    |
1 row in set (0.00 sec)
Published on 03-Oct-2019 11:27:21