Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL Query to Find the Number of Columns in a Table
Next article icon

SQL Query to Count the Number of Rows in a Table

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Counting rows in a database table is a fundamental operation in SQL that helps developers and analysts understand the size and structure of their datasets. Whether we're building reports, analyzing trends, or debugging data inconsistencies, the COUNT() function in SQL is an essential tool to streamline these tasks.

In this article, we will explore various ways to use the COUNT() function to count rows in SQL tables, with practical examples and clear explanations. By the end of this article, we'll be equipped with the knowledge to efficiently count rows in your database and make informed decisions.

How to Count the Number of Rows

In this example, we will create a demo database and table and then write an SQL query to get the total number of rows in that table. For this demonstration, we will create a students table and populate it with sample data.

Create the Students Table

CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
phone VARCHAR(20)
);


INSERT INTO students (id, name, email, phone)
VALUES
(1, 'Aman Chopra', '[email protected]', '123-456-7890'),
(2, 'Aditya Arpan', '[email protected]', '987-654-3210'),
(3, 'Shubham Thakur', '[email protected]', '555-555-5555'),
(4, 'Naveen tulasi', '[email protected]', '987-654-3210'),
(5, 'Varsha Choudhary', '[email protected]', '787-957-3657');

Select * FROM students;

Output

Demo Table
Student Table

Example 1: Counting the Number of Students in the Database

Let's look at the query to count the number of rows in a table in SQL using COUNT() function. This query returns the total number of rows, including any with NULL values. We can even change the display name for displaying count:

Query:

SELECT COUNT(id) FROM students;

Output

Total Number of Rows
Total Number of ROws

Example 2: Counting the Number of Student IDs in the Database

Aliases allow us to rename the column or result for better clarity in our output. The alias total_students provides a user-friendly label for the count result.

Query:

SELECT COUNT(id) AS id_count FROM students;

Output

IMG
Count Row with AS Output

Example 3: SQL Count the Rows with HAVING Clause 

We can use the HAVING clause in the SQL query to specify a condition for the COUNT function and also we can modify the code to only show the results for num_rows where the count is greater than 1. For example, to find phone numbers associated with more than one student:

Query:

SELECT phone, COUNT(*) AS num_rows
FROM students
GROUP BY phone
HAVING num_rows > 1;

Output

SQL Count the Rows with HAVING Clause Output
SQL Count the Rows with HAVING Clause 

Explanation:

  • The GROUP BY clause groups rows by the phone column.
  • The HAVING clause filters results to show only groups where the count is greater than 1.

Example 4: SQL Count the Rows with Order By Clause 

The ORDER BY clause is used to sort the results of a SQL query by one or more columns. When used in conjunction with the COUNT() function, the ORDER BY clause can be used to sort the results by the count of a particular column.

For example, let's say we have a student's table with columns id, name, email, and phone. We want to count the number of students in each phone and then sort the results in descending order by the count of students in each phone. We can use the following SQL query:

Query:

SELECT phone, COUNT(*) AS num_students
FROM students
GROUP BY phone
ORDER BY num_students ASC;

Output

Orderby_Output
Count Rows with Order By

Conclusion

The COUNT() function is a flexible and powerful feature in SQL that simplifies row counting and aggregation tasks. Whether we're analyzing trends, identifying duplicates, or summarizing data, this function provides actionable insights into our dataset. By combining COUNT() with clauses like HAVING and ORDER BY, we can perform advanced operations to refine our queries and extract valuable information. Mastering these techniques will enhance our ability to manage and analyze data effectively.


Next Article
SQL Query to Find the Number of Columns in a Table
author
nikhiltejatangella
Improve
Article Tags :
  • SQL
  • Databases
  • SQL-Query

Similar Reads

  • SQL Query to Find the Number of Columns in a Table
    SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. S
    4 min read
  • How to Count the Number of Rows of a Given SQLite Table using Python?
    In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if t
    2 min read
  • SQL Query to Find the Sum of all Values in a Column
    In SQL, calculating the sum of values in a column is a crucial task for performing data analysis and generating reports. The SUM() function helps to calculate the total sum of numeric values from a column, which is especially useful in scenarios like finding total sales, total employees, or total re
    5 min read
  • How to count the number of pages in a PDF file in Python
    In this article, we will see how can we count the total number of pages in a PDF file in Python, For this article there is no such prerequisite, we will use PyPDF2 library for this purpose. PyPDF2 is a free and open-source pure-Python PyPDF library capable of performing many tasks like splitting, me
    4 min read
  • SQL Query to Convert Rows to Columns in SQL Server
    In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we h
    2 min read
  • How to Get Counts of all Tables in a Schema in PL/SQL?
    In Database Management System, it is essential to retrieve the statistical information about tables with the schema. Whether it is for monitoring the database health, optimizing the performance, or simply understanding the data structures having access to row counts of the tables can be more valuabl
    5 min read
  • How to count rows in MySQL table in PHP ?
    PHP stands for hypertext preprocessor. MySQL is a database query language used to manage databases. In this article, we are going to discuss how to get the count of rows in a particular table present in the database using PHP and MySQL. Requirements: XAMPP Approach: By using PHP and MySQL, one can p
    3 min read
  • How to Select the nth Row in a SQL Server Database Table?
    In SQL Server databases, it's common to encounter scenarios where we need to retrieve a specific row, such as the nth row, from a table efficiently. Whether you're building a pagination feature for a web application or analyzing data, having the ability to select a particular row based on its positi
    3 min read
  • PL/SQL Query to List the Last 5 Rows of a Result Set
    Fetching or displaying the last five rows is a common task. Whether fetching trending topics or tracking a user's recent activity, fetching the last five rows will help in these situations. These are a few use cases we have discussed, there are many more. Product recommendation is crucial if you are
    5 min read
  • How to Select the Nth Row in a SQLite Database Table?
    In SQLite, selecting a specific row from a table can be a common requirement, especially when dealing with large datasets. In this article, we will explore different methods to select the nth row from a SQLite database table. Whether we're a beginner or an experienced developer understanding these m
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences