COUNT() Function in MySQL (original) (raw)

Last Updated : 27 Mar, 2026

The COUNT() function in MySQL is an aggregate function used to count rows or values in a result set. It helps analyze how many records meet specific conditions in a query.

**Syntax:

COUNT(expression)

**expression: This can be a column name, *, or an expression

Working with the COUNT() Function

This section shows how COUNT() works using a sample table. It demonstrates counting total, non-NULL, and unique values. First, we will create a demo table on which the COUNT() function will be applied:

Screenshot-2026-03-27-144955

sales Table

Example 1: COUNT(*) Function

This example counts the total number of rows in the sales table. It includes all rows regardless of NULL values.

**Query:

SELECT COUNT(*) AS TotalRows FROM sales;

**Output:

Screenshot-2026-03-27-155652

Example 2: COUNT(expression) Function

This example counts the number of rows where the quantity column is not NULL. Only valid values are considered.

**Query:

SELECT COUNT(quantity) AS NonNullQuantities FROM sales;

**Output:

Screenshot-2026-03-27-155925

Example 3: COUNT(DISTINCT expression) Function

This example counts the number of unique product names in the sales table. Duplicate values are counted only once.

**Query:

SELECT COUNT(DISTINCT product_name) AS UniqueProducts FROM sales;

**Output:

Screenshot-2026-03-27-160208