SQL COUNT()Function
The COUNT() function in SQL is used to return the number of rows that match a specified condition. It can be used with SELECT statements to count rows in a table, including duplicate values and NULLs.
Here’s a basic syntax of the COUNT() function:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Examples:
1. Counting all rows in a table
Suppose we have a table called employees:
| id | name | department |
|---|---|---|
| 1 | Alice | HR |
| 2 | Bob | IT |
| 3 | Charlie | HR |
| 4 | David | Finance |
| 5 | Eve | IT |
To count the total number of rows in the employees table, we can use:
SELECT COUNT(*) FROM employees;
Output:
| COUNT(*) |
|---|
| 5 |
2. Counting rows with a specific condition
To count the number of employees in the IT department:
SELECT COUNT(*) FROM employees WHERE department = 'IT';
Output:
| COUNT(*) |
|---|
| 2 |
3. Counting distinct values
To count the number of distinct departments:
SELECT COUNT(DISTINCT department) FROM employees;
Output:
| COUNT(DISTINCT department) |
|---|
| 3 |
4. Counting non-NULL values in a column
To count the number of non-NULL values in the department column:
SELECT COUNT(department) FROM employees;
Output:
| COUNT(department) |
|---|
| 5 |
This function is useful for generating reports and obtaining statistical data about the data in your database.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
