PostgreSQL COUNT Function

Your store has 8 orders, but only 4 used a coupon. The PostgreSQL count function tells you both: count(*) counts rows and count(coupon) counts non-NULL values, each as a bigint.

The catch: with GROUP BY, a state with no orders doesn’t come back as 0. It doesn’t come back at all.

The seven examples below cover NULLs, HAVING, FILTER, window counts and a 2-million-row table. Tested on PostgreSQL 18.6 for Windows.

COUNT Function Syntax

Here is the syntax:

count ( * ) → bigint
count ( "any" ) → bigint
ArgumentRequiredWhat it means
*EitherCounts every row, NULLs included.
"any"EitherOne expression; NULLs skipped. DISTINCT counts unique values.

Return value: a bigint, and 0 (never NULL) when no rows come in.

Availability: every supported release. FILTER on aggregates needs PostgreSQL 9.4 or later.

When to Use the COUNT Function

Use COUNT when you need to:

  • show orders per state on a dashboard
  • check how many rows a DELETE will touch
  • count unique coupon codes
  • flag busy groups with the PostgreSQL HAVING clause

Every example uses this orders table from a small US store. Run it once:

CREATE TABLE orders (
  order_id int PRIMARY KEY,
  state    char(2),
  coupon   varchar(10),
  total    numeric(8,2)
);
INSERT INTO orders VALUES
 (1001, 'OH', 'SAVE10',   54.00),
 (1002, 'TX', NULL,      120.50),
 (1003, 'OH', 'SAVE10',   32.99),
 (1004, 'CA', NULL,       89.00),
 (1005, 'TX', 'FREESHIP', 15.25),
 (1006, 'OH', NULL,       61.40),
 (1007, 'CA', 'SAVE10',  240.00),
 (1008, 'NY', NULL,       18.75);

Example 1: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)

Let’s start with all three forms. I want total rows, rows with a coupon, and distinct codes:

SELECT count(*)               AS all_rows,
       count(coupon)          AS with_coupon,
       count(DISTINCT coupon) AS coupon_codes
FROM orders;

Output:

 all_rows | with_coupon | coupon_codes 
----------+-------------+--------------
        8 |           4 |            2
(1 row)
PostgreSQL count(*), count(coupon) and count(DISTINCT coupon) returning 8, 4 and 2
Three different counts.

That returns 8, 4 and 2.

count(coupon) skipped the four NULL coupons. DISTINCT then folded three SAVE10 rows into one.

Example 2: Count Rows per Group with GROUP BY and HAVING

The goal is states with at least 2 orders:

SELECT state, count(*) AS orders
FROM orders
GROUP BY state
HAVING count(*) >= 2
ORDER BY orders DESC, state;

Output:

 state | orders 
-------+--------
 OH    |      3
 CA    |      2
 TX    |      2
(3 rows)

That gives 3 rows. NY had one order, so HAVING dropped it.

HAVING filters groups after counting. I have a separate guide on PostgreSQL GROUP BY.

Example 3: Count with a Condition Using FILTER (WHERE)

Say you need orders of $50 or more per state, next to the total:

SELECT state,
       count(*) AS orders,
       count(*) FILTER (WHERE total >= 50) AS big,
       sum(CASE WHEN total >= 50 THEN 1 ELSE 0 END) AS big_case
FROM orders
GROUP BY state
ORDER BY state;

Output:

 state | orders | big | big_case 
-------+--------+-----+----------
 CA    |      2 |   2 |        2
 NY    |      1 |   0 |        0
 OH    |      3 |   2 |        2
 TX    |      2 |   1 |        1
(4 rows)
PostgreSQL count(*) FILTER (WHERE total >= 50) matching SUM(CASE ...) for every state
FILTER matches SUM(CASE).

For OH, that returns 3 orders and 2 big ones, from both methods.

FILTER feeds count only the matching rows, while the PostgreSQL CASE version also runs on MySQL and SQL Server.

Example 4: Show a Total Next to Each Row with COUNT(*) OVER ()

Next, a window count. I want each Ohio order next to the total:

SELECT order_id, state,
       count(*) OVER () AS all_orders
FROM orders
WHERE state = 'OH'
ORDER BY order_id;

Output:

 order_id | state | all_orders 
----------+-------+------------
     1001 | OH    |          3
     1003 | OH    |          3
     1006 | OH    |          3
(3 rows)
PostgreSQL count(*) OVER () returning all_orders 3 on each Ohio row
OVER () keeps each row.

Every row shows all_orders 3; add PARTITION BY state for per-state counts.

OVER () counts rows left after WHERE without collapsing them. Run the SELECT again without the WHERE and you should see 8. See also PostgreSQL ROW_NUMBER.

Example 5: Why Does COUNT Return 0 but GROUP BY Return No Rows?

No orders came from Washington. The goal is to see both behaviors:

SELECT count(*) AS wa_orders, pg_typeof(count(*)) AS type
FROM orders WHERE state = 'WA';

SELECT state, count(*) AS orders
FROM orders WHERE state = 'WA'
GROUP BY state;

Output:

 wa_orders |  type  
-----------+--------
         0 | bigint
(1 row)

 state | orders 
-------+--------
(0 rows)
PostgreSQL count(*) returning 0 of type bigint, then GROUP BY state returning 0 rows
0, then no row.

The first query returns 0, typed bigint. The second returns no row.

No input rows means no group to report. Unlike PostgreSQL SUM, count never returns NULL.

Example 6: Count Distinct Pairs of Columns

I want distinct state and coupon pairs. This fails:

\set VERBOSITY terse
SELECT count(DISTINCT state, coupon) FROM orders;

Output:

psql:count-distinct-two-columns-error.sql:2: ERROR:  function count(character, character varying) does not exist at character 8

Wrap the columns in a row constructor instead:

SELECT count(DISTINCT (state, coupon)) AS pairs
FROM orders;

Output:

 pairs 
-------
     7
(1 row)

That returns 7 pairs from 8 rows.

Only (OH, SAVE10) repeats. A pair like (TX, NULL) is a non-NULL row value, so it still counts.

Example 7: Count Rows in a Big Table Fast

Last, page_views has 2 million rows. I want the exact count and the planner’s estimate:

\timing on
SELECT count(*) AS exact FROM page_views;
SELECT reltuples::bigint AS estimate
FROM pg_class WHERE relname = 'page_views';

Output:

  exact  
---------
 2000000
(1 row)

Time: 143.016 ms
 estimate 
----------
  2000000
(1 row)

Time: 7.240 ms

Both show 2000000, but check the Time lines.

Why slow? Under MVCC each row must be checked as visible to your snapshot, so there’s no stored counter. reltuples is only refreshed by VACUUM, ANALYZE and some DDL; see PostgreSQL ANALYZE.

Tips & Common Mistakes

  • count(DISTINCT a, b) fails with function count(character, character varying) does not exist. Use (a, b).
  • count isn’t allowed in a WHERE clause; filter counts in HAVING.
  • Need 0 for missing groups? LEFT JOIN from a list of states.

Wrapping Up

Copy Example 1 for NULLs, Example 3 for conditions and Example 7 for big tables.

Next step: browse the complete list of PostgreSQL functions or the PostgreSQL 18 aggregate functions docs.

A few more counting and aggregate guides:

Frequently Asked Questions

Is COUNT(1) faster than COUNT(*) in PostgreSQL?

No. count(1) returns the same number but checks the constant for NULL on every row; count(*) checks nothing.

Can an index make COUNT(*) faster in PostgreSQL?

Sometimes. An index-only scan skips only pages marked all-visible in the visibility map, which VACUUM sets.

How do I count rows in every PostgreSQL table?

Query n_live_tup in pg_stat_user_tables. It’s an estimate.