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;
Learn SQL
Introduction
Syntax
Data Types
Server Data Types
Commands
Commands List
Wildcards
Constraints
Aggregate Functions
Date Functions
Date Format
Injection
SQL Server Hosting
Views
Auto-incrementation
SQL Operators
AS
AND & OR
IN
BETWEEN
WHERE
GROUP BY
HAVING
ORDER BY
LIKE
NOT
NOT EQUAL
UNION
NULL
NOT NULL
DEFAULT
UNIQUE
FOREIGN KEY
PRIMARY KEY
CHECK
Indexes
ALTER TABLE
CREATE DATABASE
CREATE TABLE
DELETE
DROP
INSERT INTO SELECT
INSERT INTO
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
UPDATE
FULL OUTER JOIN
INNER JOIN
JOIN
LEFT JOIN
RIGHT JOIN
AVG()
COUNT
FIRST
LAST
MAX
MIN()
SUM()
LEN
UCASE
MID
NOW
ROUND
FORMAT
LOWER
CONVERT
ISNULL