How to Count Database Table Values With SQL COUNT

Close-Up Of Human Hand Counting Against White Background
Pongsak Tawansaeng / EyeEm / Getty Images

The queries element, an important part of Structured Query Language (SQL), retrieves data based on specific criteria from a relational database. This retrieval is accomplished using SQL queries via the COUNT function, which — when paired with a particular column of the database — can yield all sorts of information.

The SQL COUNT function is particularly useful because it allows you to count database records based on user-specified criteria. You can use it to count all the records in a table, count unique values in a column, or count the number of times records occur that meet certain criteria.

Northwind Database Example

The examples below are based on the commonly used Northwind database, which frequently ships with database products for use as a tutorial. Here's an excerpt from the database's Product table: 

ProductID ProductName SupplierID QuantityPerUnit UnitPrice UnitsInStock
1 Chai 1 10 boxes x 20 bags 18.00 39
2 Chang 1 24 - 12 oz bottles 19.00 17
3 Aniseed Syrup 1 12 - 550 ml bottles 10.00 13
4 Chef Anton's Cajun Seasoning 2 48 - 6 oz jars 22.00 53
5 Chef Anton's Gumbo Mix 2 36 boxes 21.35 0
6 Grandma's Boysenberry Spread 3 12 - 8 oz jars 25.00 120
7 Uncle Bob's Organic Dried Pears 3 12 - 1 lb pkgs. 30.00 15
Product Table

 

 

 

 

 

 

 

 

 

Counting Records in a Table

The most basic query is counting the number of records in the table. If you want to know the number of items that exist in a product table, use the following query:

SELECT COUNT(*)
FROM product;

This query returns the number of rows in the table. It's seven in this example.

Counting Unique Values in a Column

You can also use the COUNT function to identify the number of unique values in a column. In the example, if you want to identify the number of different suppliers whose products appear in the produce department, you could accomplish this using the following query:

SELECT COUNT(DISTINCT SupplierID)
FROM product;

This query returns the number of distinct values found in the SupplierID column. In this case, the answer is three, representing 1, 2, and 3.

Counting Records Matching Criteria

Combine the COUNT function with the WHERE clause to identify the number of records that match certain criteria. For example, suppose the department manager wants to get a sense of the stock levels in the department. The following query identifies the number of rows representing UnitsInStock less than 50 units:

SELECT COUNT(*)
FROM product
WHERE UnitsInStock < 50;

In this case, the query would return a value of four, representing Chai, Chang, Aniseed Syrup, and Uncle Bob's Organic Dried Pears.

The COUNT clause can be extremely valuable to database administrators who seek to summarize data to meet business requirements. With a little creativity, you can use the COUNT function for a wide variety of purposes.