#5253·diesel

Cannot filter by an outer column inside EXCEPT

Author: sergio-fferreiraCreated Sep 25, 2026Updated Sep 26, 2026
Labelsbughole in api

Rust Version

1.98.1

Diesel Version

2.3.13

Diesel Features

postgres

Database Version

PostgreSQL 18.6

Operating System Version

CachyOS

What happened?

The following query does not compile:

rust
let entity_ids = vec![1, 2, 3, 4];

incidents::table.select(incidents::id).filter(not(exists(
    entities::table
        .select(entities::id)
        .filter(entities::id.eq_any(entity_ids))
        .except_all(
            alerts::table
                .inner_join(alerts_entities::table)
                .filter(alerts::incident_id.eq(incidents::id)) // compiles if I remove this line
                .select(alerts_entities::entity_id),
        ),
)));

It is a conversion attempt from the following query in PostgreSQL:

sql
WITH incoming(entity_id) AS (
    VALUES (1), (2), (3), (4)
)
SELECT i.id
FROM incidents i
WHERE NOT EXISTS (
    (
        SELECT entity_id
        FROM incoming

        EXCEPT

        SELECT ae.entity_id
        FROM alerts a
        JOIN alerts_entities ae ON ae.alert_id = a.id
        WHERE a.incident_id = i.id
    )

    -- The remaining of the query is not necessary to reproduce the error

    -- UNION ALL

    -- (
    --     SELECT ae.entity_id
    --     FROM alerts a
    --     JOIN alerts_entities ae ON ae.alert_id = a.id
    --     WHERE a.incident_id = i.id

    --     EXCEPT

    --     SELECT entity_id
    --     FROM incoming
    -- )
)

What did you expect to happen?

The query should compile.

Additional details

No response

Steps to reproduce

SQL statements (should return id=1)

sql
CREATE TABLE incidents (
    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);

CREATE TABLE alerts (
    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    incident_id INTEGER NOT NULL REFERENCES incidents(id)
);

CREATE TABLE entities (
    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);

CREATE TABLE alerts_entities (
    alert_id INTEGER NOT NULL REFERENCES alerts(id),
    entity_id INTEGER NOT NULL REFERENCES entities(id),
    PRIMARY KEY (alert_id, entity_id)
);

INSERT INTO incidents DEFAULT VALUES;
INSERT INTO incidents DEFAULT VALUES;

INSERT INTO alerts (incident_id)
VALUES
    (1),
    (1),
    (2),
    (2);

INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;
INSERT INTO entities DEFAULT VALUES;

INSERT INTO alerts_entities (alert_id, entity_id)
VALUES
    (1, 1),
    (1, 2),
    (2, 3),
    (2, 4),
    (3, 5),
    (3, 6),
    (4, 7),
    (4, 8);

WITH incoming(entity_id) AS (
    VALUES (1), (2), (3), (4)
)
SELECT i.id
FROM incidents i
WHERE NOT EXISTS (
    (
        SELECT entity_id
        FROM incoming

        EXCEPT

        SELECT ae.entity_id
        FROM alerts a
        JOIN alerts_entities ae ON ae.alert_id = a.id
        WHERE a.incident_id = i.id
    )

    --UNION ALL

    --(
    --    SELECT ae.entity_id
    --    FROM alerts a
    --    JOIN alerts_entities ae ON ae.alert_id = a.id
    --    WHERE a.incident_id = i.id

    --    EXCEPT

    --    SELECT entity_id
    --    FROM incoming
    --)
)

schema.rs

// @generated automatically by Diesel CLI.

diesel::table! {
    alerts (id) {
        id -> Int4,
        incident_id -> Int4,
    }
}

diesel::table! {
    alerts_entities (alert_id, entity_id) {
        alert_id -> Int4,
        entity_id -> Int4,
    }
}

diesel::table! {
    entities (id) {
        id -> Int4,
    }
}

diesel::table! {
    incidents (id) {
        id -> Int4,
    }
}

diesel::joinable!(alerts -> incidents (incident_id));
diesel::joinable!(alerts_entities -> alerts (alert_id));
diesel::joinable!(alerts_entities -> entities (entity_id));

diesel::allow_tables_to_appear_in_same_query!(alerts, alerts_entities, entities, incidents,);

Compile time error

    Checking diesel-bug v0.1.0 (...)
error[E0271]: type mismatch resolving `<JoinOn<Join<table, table, Inner>, Grouped<Eq<Nullable<alert_id>, Nullable<id>>>> as AppearsInFromClause<table>>::Count == Once`
  --> src/main.rs:31:17
   |
30 |               .except_all(
   |                ---------- required by a bound introduced by this call
31 | /                 alerts::table
32 | |                     .inner_join(alerts_entities::table)
33 | |                     .filter(alerts::incident_id.eq(incidents::id))
34 | |                     .select(alerts_entities::entity_id),
   | |_______________________________________________________^ expected `Once`, found `Never`
   |
note: required for `incidents::columns::id` to implement `AppearsOnTable<JoinOn<Join<table, table, Inner>, Grouped<Eq<Nullable<alert_id>, Nullable<id>>>>>`
  --> src/schema.rs:25:9
   |
25 |         id -> Int4,
   |         ^^
   = note: associated types for the current `impl` cannot be restricted in `where` clauses
   = note: 2 redundant requirements hidden
   = note: required for `diesel::expression::grouped::Grouped<diesel::expression::operators::Eq<alerts::columns::incident_id, incidents::columns::id>>` to implement `AppearsOnTable<JoinOn<Join<table, table, Inner>, Grouped<Eq<Nullable<alert_id>, Nullable<id>>>>>`
   = note: required for `WhereClause<Grouped<Eq<incident_id, id>>>` to implement `ValidWhereClause<FromClause<JoinOn<Join<table, table, Inner>, Grouped<Eq<Nullable<alert_id>, Nullable<id>>>>>>`
   = note: required for `SelectStatement<FromClause<JoinOn<Join<table, table, Inner>, Grouped<Eq<Nullable<...>, ...>>>>, ..., ..., ...>` to implement `Query`
note: required by a bound in `except_all`
  --> .../.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/diesel-2.3.13/src/query_dsl/combine_dsl.rs:72:22
   |
70 |     fn except_all<Rhs>(self, rhs: Rhs) -> dsl::ExceptAll<Self, Rhs>
   |        ---------- required by a bound in this associated function
71 |     where
72 |         Rhs: AsQuery<SqlType = <Self::Query as Query>::SqlType>;
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CombineDsl::except_all`
   = note: the full name for the type has been written to '.../target/debug/deps/diesel_bug-471ce0d4c8568649.long-type-2600212281272657912.txt'
   = note: consider using `--verbose` to print the full type name to the console
   = note: this error originates in the macro `diesel::table` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0271`.

Checklist

  • I have already looked over the issue tracker and the discussion forum for similar possible closed issues.

  • This issue can be reproduced on Rust's stable channel. (Please submit the issue in the Rust issue tracker instead if that's not the case)

  • This issue can be reproduced without requiring a third party crate