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 NULL
s.
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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.