Get boolean result whether table exists or not using CASE WHEN in MySQL


For this, you can use INFORMATION_SCHEMA.TABLES and find the table you want to search. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.71 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-------+
|   Id | Name  |
+------+-------+
|  101 | Chris |
|  102 | David |
+------+-------+
2 rows in set (0.00 sec)

Here is the query to check whether the table exists or not −

mysql> select max(case when table_name = 'DemoTable' then 'Yes the table
exist(TRUE)' else 'No(FALSE)' end) AS isTableExists
   -> from information_schema.tables;

This will produce the following output −

+-------------------------------+
| isTableExists                 |
+-------------------------------+
| Yes the table exist(TRUE)     |
+-------------------------------+
1 row in set (0.52 sec)

Updated on: 13-Dec-2019

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements