// aggregates reference

SQL Server COUNT_BIG function

COUNT_BIG works exactly like COUNT but returns bigint. On SQL Server that matters for huge tables and for indexed views.

類別
Aggregates
Returns
bigint
In this category
50 of 52

語法

COUNT_BIG(* | [ALL | DISTINCT] expression)

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL Different name or syntax COUNT already returns bigint
MySQL Different name or syntax COUNT already returns BIGINT
SQLite Different name or syntax COUNT already returns a 64-bit integer
Oracle Different name or syntax COUNT returns NUMBER

範例

SQL Server

SELECT COUNT_BIG(*) AS n, SQL_VARIANT_PROPERTY(COUNT_BIG(*), 'BaseType') AS type_name
FROM (VALUES (1), (2), (NULL)) AS t(x);  -- 3, bigint

SQL Server

SELECT COUNT(x) AS non_null, COUNT_BIG(DISTINCT x) AS distinct_values
FROM (VALUES (1), (1), (NULL)) AS t(x);  -- 2, 1

小知識

  • COUNT(*) over more than 2,147,483,647 rows fails with an arithmetic overflow; COUNT_BIG(*) does not.
  • An indexed view that uses GROUP BY must include COUNT_BIG(*); COUNT(*) is not allowed there.
  • COUNT_BIG(col) skips NULLs and COUNT_BIG(DISTINCT col) counts distinct values, the same as COUNT.

Questions about COUNT_BIG

Do I need COUNT_BIG on PostgreSQL or MySQL?

No. Their COUNT already returns a 64-bit integer.

Is COUNT_BIG slower than COUNT?

No. The counting work is the same; only the result type differs.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.