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.
Related on SQLly
- Conditional counts (COUNT IF) Snippet
- CTE basics: WITH … AS across dialects Dialect comparison
- Update from an aggregate on the same table Dialect comparison
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.