Get least used id within another table
NOTE : This solution is in SQL SERVER

You can do this using while loop.

Here is the query that will do

DECLARE @cnt INT = 1

WHILE @cnt &gt; 0
BEGIN
   update TOP (1) account
  set account.proxy_id = (
      select top 1 proxy.id
      from proxy order by (
        select count(account.id)
        from account
        where account.proxy_id = proxy.id and account.enabled = 1
      )
  ) where account.proxy_id is null
   SET @cnt = (select count(id) from account where proxy_id is null and enabled = 1)
END;


In this query first we count all account for proxy.id in proxy table and select the proxy.id for lowest count.

Then we set that id to user who is enabled and does not have any proxy_id

UPDATE :

In POSTGRESQL you can achieve this by

DO $$DECLARE r int;
BEGIN
r=1;
    while r &gt; 0 
    LOOP
        update account set proxy_id = (
            select proxy.id from proxy order by (
                select count(account.id)
                from account
                where account.proxy_id = proxy.id and account.enabled = '1'
            ) limit 1
        ) where id = (
                select id
                from account
                where proxy_id is null and enabled ='1'
                order by id limit 1
        );
        r = (select count(id) from account where proxy_id is null and enabled ='1');
    END LOOP;
END$$;