How to Count Database Table Values With SQL COUNT

Count records in a table, limited by specific criteria

What to Know

  • Calculate number of records in a table: Type SELECT COUNT(*) [Enter] FROM table name;
  • Identify number of unique values in a column: Type SELECT COUNT(DISTINCT column name) [Enter] FROM table name;
  • Number of records matching criteria: Type SELECT COUNT(*) [Enter] FROM table name [Enter] WHERE column name <, =, or > number;

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

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

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. To calculate the number of items in a product table, use the following query:

FROM product;

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

Counting Unique Values in a Column

Use the COUNT function to identify the number of unique values in a column. In the example, to identify the number of different suppliers whose products appear in the produce department, execute the following query:

FROM product;

This query returns the number of distinct values found in the SupplierID column. In this case, the answer is three, representing rows 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:

FROM product
WHERE UnitsInStock < 50;

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

The COUNT clause is 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.

Was this page helpful?