SQL Query to Count the Number of Rows in a Table
In this article, we are going to write an SQL query to count the number of rows in a table. For is we will be making use of the count() function of SQL. For this article, we will be making use of the Microsoft SQL Server as our database.
Let’s do the same by building a table inside the database and counting its rows. We will first create a database called “geeks” and then create an “Employee” table in this database and will execute our query on that table.
Creating a Database :
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Using Database :
We have the following Employee table in our geeks database :
CREATE TABLE geeks( id int(20) , name varchar(200));
You can use the below statement to query the description of the created table:
EXEC sp_columns employees;
Adding Data to Table:
Use the below statement to add data to the Employee table:
INSERT INTO geeks(id,name) values(1,'nikhil'); INSERT INTO geeks(id,name) values(2,'kartik');
SQL Query to Count Number of Rows:
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
Syntax: SELECT COUNT(colmn_name) from table_name;
Using ‘ * ‘ we get all the rows as shown below:
SELECT * FROM geeks;
This will result in the below image:
The table we will be operating has 2 rows. So let’s feed in the query to get the no. of rows a specific column(say, id)as:
SELECT COUNT(id) from geeks;
We can even change the display name for displaying count:
SELECT COUNT(id) as id_count FROM geeks