Check how many rows are in a MySQL database table?


To know how many rows are in a ySQL database table, you need to use aggregate function COUNT(*).

The syntax is as follows

SELECT COUNT(*) FROM yourTableName;

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

mysql> create table CountRowsDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(20)
   - > );
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountRowsDemo(Name) values('Sam');
Query OK, 1 row affected (0.25 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values('Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountRowsDemo(Name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.09 sec)
mysql> insert into CountRowsDemo(Name) values('Carol');
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 CountRowsDemo;

The following is the output

+----+-------+
| Id | Name  |
+----+-------+
|  1 | NULL  |
|  2 | Sam   |
|  3 | NULL  |
|  4 | Mike  |
|  5 | David |
|  6 | NULL  |
|  7 | NULL  |
|  8 | Carol |
+----+-------+
8 rows in set (0.00 sec)

Now let us run the following query to count rows from a table

mysql> select count(*) AS TotalRows from CountRowsDemo;

The following is the output

+-----------+
| TotalRows |
+-----------+
|         8 |
+-----------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

990 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements