Check if a table is empty or not in MySQL using EXISTS

MySQLMySQLi Database

The following is the syntax to check whether a table is empty or not using MySQL EXISTS −

SELECT EXISTS(SELECT 1 FROM yourTableName);

Example

First, let us create a table. The query to create a table is as follows −

mysql> create table ReturnDemo
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.79 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into ReturnDemo values(100,'Larry');
Query OK, 1 row affected (0.18 sec)
mysql> insert into ReturnDemo values(101,'Bob');
Query OK, 1 row affected (0.28 sec)
mysql> insert into ReturnDemo values(102,'Sam');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from ReturnDemo;

Output

+------+-------+
| Id   | Name |
+------+-------+
|  100 | Larry |
|  101 |   Bob |
|  102 |   Sam |
+------+-------+
3 rows in set (0.00 sec)

Here is the query to check if MySQL table is empty or not −

mysql> select exists(select 1 from ReturnDemo) AS Output;

Output

+--------+
| Output |
+--------+
|      1 |
+--------+
1 row in set (0.00 sec)

The output 1 tells that the MySQL table isn’t empty.

raja
Published on 19-Mar-2019 08:02:37
Advertisements