Skip to content

aggr: count(*) reports 1 for entities with no matches #1709

Open

Description

@dimitri-yatsenko

Problem

A.aggr(B, ...) keeps every row of A by default, using a LEFT JOIN. For a row of A with no match, the left join supplies one row padded with NULLs, and COUNT(*) counts it. So A.aggr(B, n="count(*)") reports n = 1 for entities that have no matches.

The docstring example therefore shows 1, not 0, for subjects without sessions:

Subject.aggr(Session, n="count(*)")  # keeps all subjects, even those with 0 sessions

Reproduction

DataJoint 2.3.5.dev, MySQL 8.0, using the same two tables as #1708 (subject 2 has no sessions):

>>> Subject.aggr(Session, n="count(*)").to_dicts()
[{'subject_id': 1, 'n': 2}, {'subject_id': 2, 'n': 1}]   # should be 0
>>> Subject.aggr(Session, n="count(session)").to_dicts()
[{'subject_id': 1, 'n': 2}, {'subject_id': 2, 'n': 0}]   # correct

Proposal

Rewrite count(*) in an aggregation over a group B as a count of a column that is null only in the padding: B's own copy of a primary-key attribute, which is always non-null.

Two points need care:

  • Shared key attributes. With USING-style joins, the key attributes B shares with A are merged with A's values, so they are non-null even in the padded row. The count must reference B's own copy inside the subquery.
  • All of B's key shared with A. When A and B are one-to-one, B has no key attribute of its own to count. In that case, count a marker column (1 AS _present) added to B.

Apply the rewrite whenever rows are kept (the default). Applying it uniformly is also harmless for exclude_nonmatching=True and dj.U(...).aggr.

Other aggregates (sum, avg, min, max, count(col)) already ignore the padded row when they read columns only B has. If an aggregate reads a column shared with A, it sees A's value on the padded row; document this.

Tests

Activity

  1. added
    bugIndicates an unexpected problem or unintended behavior
    on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIndicates an unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions