Table of Contents
ToggleUnderstanding the SQL COUNT() Function with Examples
The COUNT() function in SQL is used to get the total number of rows that match a specified condition. It is very helpful in counting the number of records or rows in a table based on certain criteria.
The general syntax for the COUNT() function is as follows:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
You can also use COUNT(*) to count all rows in a table.
Suppose we have a table called Products and we want to count the total number of rows (products) in the table.
SELECT COUNT(*)
FROM Products;
If you want to count how many products have a ProductName listed, excluding null values:
SELECT COUNT(ProductName)
FROM Products;
For example, we want to find the number of products where the price is greater than ₹500:
SELECT COUNT(ProductID)
FROM Products
WHERE Price > 500;
To count distinct prices (ignoring duplicates), use the DISTINCT keyword:
SELECT COUNT(DISTINCT Price)
FROM Products;
To count the number of products in each category, use the GROUP BY clause:
SELECT COUNT(*) AS [Number of Products], CategoryID
FROM Products
GROUP BY CategoryID;
