How to implement Count (*) as variable from MySQL to display the number of records in a table?


The alias name can be used as a variable name in MySQL as shown in the below syntax −

select count(*) AS anyAliasName from yourTableName;

Let us first create a table −

mysql> create table DemoTable695 (
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable695 values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable695 values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('Mike');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable695;

This will produce the following output -

+-----------+
| FirstName |
+-----------+
| Chris     |
| Robert    |
| David     |
| Mike      |
+-----------+
4 rows in set (0.00 sec)

Following is the query to consider count(*) as variable in MySQL −

mysql> select count(*) AS TOTAL_NO_OF_RECORDS from DemoTable695 ;

This will produce the following output -

+---------------------+
| TOTAL_NO_OF_RECORDS |
+---------------------+
| 4                   |
+---------------------+
1 row in set (0.02 sec)

Updated on: 21-Aug-2019

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements