// aggregates reference

SQL COUNT function

Counts rows, or the non-null values of an expression, in a group. COUNT(*) and COUNT(column) give different answers as soon as the column holds a NULL.

類別
Aggregates
Returns
integer (int on SQL Server, bigint on PostgreSQL, NUMBER on Oracle)
In this category
1 of 52

語法

COUNT(*)
COUNT(expression)
COUNT(DISTINCT expression)

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

範例

Any engine

SELECT COUNT(*) FROM orders;

Any engine

SELECT COUNT(DISTINCT customer_id) AS customers
FROM orders;

PostgreSQL

SELECT COUNT(*) FILTER (WHERE shipped) AS shipped_orders
FROM orders;

小知識

  • COUNT(*) counts every row, including rows where every column is NULL; COUNT(column) counts only rows where that column is not NULL.
  • COUNT(DISTINCT expression) removes duplicates and NULLs before counting, so a column holding only NULLs counts as zero.
  • COUNT(*) FILTER (WHERE shipped) counts a subset on PostgreSQL and SQLite 3.30+. Elsewhere use COUNT(CASE WHEN shipped THEN 1 END), which counts only the rows where the CASE is not NULL.
  • On SQL Server COUNT returns int and errors past 2,147,483,647 rows; COUNT_BIG returns bigint.

Questions about COUNT

What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts every row in the group. COUNT(column) skips rows where column is NULL, so COUNT(email) is usually smaller than COUNT(*) on tables with missing addresses.

Does COUNT count NULL values?

No. COUNT of an expression counts only non-null values, and COUNT(DISTINCT ...) also removes duplicates first. Only COUNT(*) ignores what is inside the rows.

How do I count rows per group?

Add GROUP BY: SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id gives one row and one count per customer.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.