Syntax error Check if table exists in MySQL and display the warning if it exists?

Check if table exists in MySQL and display the warning if it exists?



To check if table exists, use the following syntax −

CREATE TABLE IF NOT EXISTS yourTableName
(
   yourColumnName1 dataType,
   .
   .
   .
   .
   N
);

Here, we will try to create a table that already exists and then it will produce a warning message “Table already exists”. Let us first create a table. This table already exists −

mysql> CREATE TABLE IF NOT EXISTS DemoTable
   (
   Id int
   );
Query OK, 0 rows affected, 1 warning (0.06 sec)

The warning message is as follows −

mysql> show warnings;

Output

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

If table does not already exist, then it will get created −

mysql> CREATE TABLE IF NOT EXISTS DemoTable2
   (
   Id int
   );
Query OK, 0 rows affected (0.71 sec)
Updated on: 2019-07-30T22:30:26+05:30

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements