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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables or CTEs does it reference?
- `feedback`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.