What is the most efficient way to check the presence of a row in a MySQL table?

MySQLMySQLi Database

The most efficient want to check the presence of a row, use the count():

select count(1) from yourTableName where yourCondition;

Let us first create a table:

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.73 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(110,'Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(120,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(130,'Carol');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(140,'David');
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable;

This will produce the following output

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 110  | Sam       |
| 120  | Mike      |
| 130  | Carol     |
| 140  | David     |
+------+-----------+
5 rows in set (0.00 sec)

Following is the query to check the presence of a row in a table. Here, we are checking for row with Id = 130:

mysql> select count(1) from DemoTable where Id=130;

This will produce the following output:

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

The above output tells that row is present.

NOTE: If you get 1 that means row is present otherwise the row isn’t present.
raja
Published on 29-Apr-2019 10:40:32
Advertisements