UPDATE table_a a
SET is_active = NOT EXISTS (SELECT FROM table_b b WHERE b.id = a.id);
That's assuming both id
columns are NOT NULL
.
Else, rows with table_a.id IS NULL
are not updated at all in your original, because NULL
is neither IN
nor NOT IN
any set.
And if there are any NULL
values in table_b.id
none of your rows end up with a.is_active = TRUE
, since a.id NOT IN (SELECT id FROM TABLE_B)
is either FALSE
or NULL
but never TRUE
in that case. NOT IN
is infamous for this kind of "trap". Related:
This query with EXISTS
updates all rows. table_a.id IS NULL
results in is_active = TRUE
, just like for other IDs that are not found in table_b
, and NULL values in table_b.id
make no difference whatsoever.
EXISTS
is also attractive in particular if there can be (many) duplicate values in table_b.id
- better performance. table_b.id
should be indexed in any case.