Exact count of all rows in MySQL database?


To exactly count all rows, you need to use the aggregate function COUNT(*). The syntax is as follows −

select count(*) as anyAliasName from yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

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

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into CountAllRowsDemo values(1,'John',23);
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountAllRowsDemo values(101,'Carol',21);
Query OK, 1 row affected (0.17 sec)
mysql> insert into CountAllRowsDemo values(201,'Sam',24);
Query OK, 1 row affected (0.13 sec)
mysql> insert into CountAllRowsDemo values(106,'Mike',26);
Query OK, 1 row affected (0.22 sec)
mysql> insert into CountAllRowsDemo values(290,'Bob',25);
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountAllRowsDemo values(500,'David',27);
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountAllRowsDemo values(500,'David',27);
Query OK, 1 row affected (0.19 sec)
mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL);
Query OK, 1 row affected (0.23 sec)
mysql> insert into CountAllRowsDemo values(NULL,NULL,NULL);
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from CountAllRowsDemo;

The following is the output −

+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
|    1 | John  | 23   |
|  101 | Carol | 21   |
|  201 | Sam   | 24   |
|  106 | Mike  | 26   |
|  290 | Bob   | 25   |
|  500 | David | 27   |
|  500 | David | 27   |
| NULL | NULL  | NULL |
| NULL | NULL  | NULL |
+------+-------+------+
9 rows in set (0.00 sec)

Here is how you can count an exact number of rows in the table using aggregate function count(*).

The query is as follows −

mysql> select count(*) as TotalNumberOfRows from CountAllRowsDemo;

The following is the output with the count of rows −

+-------------------+
| TotalNumberOfRows |
+-------------------+
|                 9 |
+-------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements