Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

COUNT to Count Records

Author: Sophia

what's covered
This tutorial explores using the COUNT function to count records in two parts:
  1. Getting Started
  2. Counting Distinct Values

1. Getting Started

There are times when we may need to count the number of records or rows that fit certain criteria or parameters. The COUNT function can help. Recall that with the SELECT clause, the * option returns all rows. If we pass the * in the COUNT function, it will return the total number of rows that fit the criteria.

If we looked at a basic query to find the number of customers, the query would look like the following:


SELECT * 
FROM customer;

Not all databases will return a specific row count in the result set, but PostgreSQL does:

COUNT Example 1

Using COUNT(*) in the query, however, would work on all databases:


SELECT COUNT(*) 
FROM customer;

COUNT Example 2

Instead of passing in the * to count all rows, you can also add the column name in the table to count the number of rows that contain non-NULL values in that column. For example, if we’re looking for the number of customers that have a value for the company, it would look like this:


SELECT COUNT(company) 
FROM customer;

COUNT Example 3

We can verify this by checking for the companies that don’t have a null value:


SELECT company 
FROM customer
WHERE company IS NOT null;

COUNT Verification with IS NOT Null Example

As another example, we could look at the count of the state column, which does contain some null values.


SELECT COUNT(state) 
FROM customer;

COUNT(state) Example


2. Counting Distinct Values

If we look more closely at the state column, we notice some repeating items:


SELECT state 
FROM customer
WHERE state IS NOT NULL
ORDER BY state;

COUNT States Repeating

For example, CA is repeated. There may be times when you want to find a count of all of the unique occurrences using the DISTINCT keyword. It would look like the following:


SELECT COUNT (DISTINCT state) 
FROM customer;

COUNT (DISTINCT) Example

As a final example, perhaps we want to identify how many of our employees are supporting customers using the support_rep_id. We can use the following query using the COUNT function to do so:


SELECT COUNT(DISTINCT support_rep_id) 
FROM customer;

COUNT (DISTINCT) Example 2


Video Transcript

try it
Your turn! Open the SQL tool by clicking on the LAUNCH DATABASE button below. Then enter in one of the examples above and see how it works. Next, try your own choices for which columns you want the query to provide.

summary
The COUNT function allows us to count the number of rows given a set of filters or the number of non-NULL values in a column.

Source: Authored by Vincent Tran