How to check if a table exists in MySQL and create if it does not already exist?

MySQLMySQLi Database

If you try to create a table and the table name already exist then MySQL will give a warning message. Let us verify the concept.

Here, we are creating a table that already exist −

mysql> CREATE TABLE IF NOT EXISTS DemoTable
   (
   CustomerId int,
   CustomerName varchar(30),
   CustomerAge int
   );
Query OK, 0 rows affected, 1 warning (0.05 sec)

The table name DemoTable is already present. Let us check the warning message.

Following is the query −

mysql> show warnings;

This will produce the following output i.e. the warning message −

+-------+------+------------------------------------+
| Level | Code | Message                            |
+-------+------+------------------------------------+
| Note  | 1050 | Table 'demotable' already exists   |
+-------+------+------------------------------------+
1 row in set (0.00 sec)

Let us change the table name and create a table that does not already exist −

mysql> CREATE TABLE IF NOT EXISTS DemoTable2
   (
   CustomerId int,
   CustomerName varchar(20),
   CustomerAge int
   );
Query OK, 0 rows affected (0.56 sec)

Table created successfully above since it does not already exist.

Following is the query to insert records in the table using insert command −

mysql> insert into DemoTable2 values(101,'Chris',23);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(102,'Robert',24);
Query OK, 1 row affected (0.12 sec)

Following is the query to display records from the table using select command −

mysql> select *from DemoTable2;

This will produce the following output

+------------+--------------+-------------+
| CustomerId | CustomerName | CustomerAge |
+------------+--------------+-------------+
| 101        | Chris        | 23          |
| 102        | Robert       | 24          |
+------------+--------------+-------------+
2 rows in set (0.00 sec)
raja
Published on 26-Apr-2019 11:40:16
Advertisements