Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Using SQL COUNT

Reading time 1 min
Published Aug 9, 2017
Updated Oct 11, 2019

SQL COUNT: Main Tips

  • This function returns the amount of rows that satisfy the defined criteria.
  • COUNT(DISTINCT) is only supported by Microsoft SQL Server and ORACLE.

Syntax of SQL COUNT

COUNT(col_name)

Returns the amount of values (excluding NULL values) in the defined column:

Example
SELECT COUNT(col_name) FROM tbl_name

COUNT(*)

Returns the total amount of data records in the table:

Example
SELECT COUNT(*) FROM tbl_name

COUNT(DISTINCT col_name)

Brings back the amount of values that are distinct (counting duplicate values as one value) from a defined column:

Example
SELECT COUNT(DISTINCT col_name) FROM tbl_name

Demo Database

Below is a section of the customer_orders table – we'll use it as a demo database in our examples:

id customer_id employee_id
20408 2 7
85471 37 3
75864 77 8

SQL COUNT Examples

COUNT(col_name)

In the code example below the statement calculated the amount of orders from a particular customer:

Example
SELECT COUNT(ID) AS OrderFromCustomers FROM customer_orders WHERE customer_id = 2;

COUNT(*)

Here we calculate the full amount of orders:

Example
SELECT COUNT(DISTINCT customer_id) AS NumberOfCustomer FROM customer_orders;

COUNT(DISTINCT col_name)

The following query will return the amount of unique customers:

Example
SELECT COUNT(DISTINCT ID) AS NumberOfCustomer FROM Orders;