SQL COUNT Function
The SQL COUNT()
function is an aggregate function used to count the number of rows in a result set or the number of non-NULL values in a column. It is commonly used to determine the number of records that meet certain criteria.
COUNT() Function
The COUNT()
function can be used in different ways, depending on what you need to count:
-- Count all rows in a table
SELECT COUNT(*) AS TotalRows
FROM table_name;
-- Count non-NULL values in a specific column
SELECT COUNT(column_name) AS NonNullValues
FROM table_name
WHERE condition;
Syntax
The basic syntax for using the COUNT()
function is:
SELECT COUNT(expression) AS Alias
FROM table_name
WHERE condition;
Examples
Here are some examples of using the COUNT()
function:
-- Count the total number of employees
SELECT COUNT(*) AS TotalEmployees
FROM Employees;
-- Count the number of employees with a specific job title
SELECT COUNT(JobTitle) AS NumberOfManagers
FROM Employees
WHERE JobTitle = 'Manager';
-- Count the number of orders placed by a customer
SELECT COUNT(OrderID) AS OrdersCount
FROM Orders
WHERE CustomerID = 'ALFKI';