COUNT Star Versus COUNT Column

COUNT(*) counts every row while COUNT(col) skips NULLs — so they disagree on sparse columns, and COUNT(DISTINCT col) collapses repeats before skipping NULLs.

SqlData Integrity

Code

snippet
SELECT
    COUNT(*)                       AS rows_in_table,
    COUNT(note)                    AS rows_with_note,
    -- 每行都有 id:COUNT(id) 与 COUNT(*) 相同
    COUNT(id)                      AS rows_with_id,
    COUNT(DISTINCT team_id)        AS distinct_teams,
    -- NULL 不进 DISTINCT:NULL 完全不计入(既不去重也不计数),重复非空值才只算一次
    COUNT(DISTINCT note)           AS distinct_notes,
    -- FILTER 让一个聚合只统计满足条件的行
    COUNT(*) FILTER (WHERE team_id = 1) AS team_one_rows
FROM feedback;

-- 同样的差异在行级也成立:COUNT 永远是聚合函数,
-- 行级判空要写 note IS NOT NULL,COUNT(note) 的跳过只发生在聚合内部
SELECT COUNT(*) AS rows_with_note_rowlevel
FROM feedback
WHERE note IS NOT NULL;

How the snippet works

SELECT statements share the script, touching feedback.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the feedback table.

Statements that matter

SELECT COUNT(*) AS rows_with_note_rowlevel
FROM feedback
WHERE note IS NOT NULL;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`feedback`.