01 · Before and afterThe pattern
BEGIN;
SELECT id FROM members WHERE workspace_id = $1 AND role = 'owner' FOR UPDATE; -- lock the set you count
SELECT count(*) FROM members WHERE workspace_id = $1 AND role = 'owner'; -- now stable
-- if count <= 1 and the target is an owner: ROLLBACK with an error
DELETE FROM members WHERE workspace_id = $1 AND user_id = $2;
COMMIT;02 · Run it on your appThe check
Can two people, clicking at the same time, remove every owner of a workspace in your app?
If the honest answer is no or not sure, this is worth a look before it reaches production.