Finding the first parent (manager) of an employee that makes twice as much in a self-referencing table? Example you have the following table

CREATE TABLE emp (id,name,salary,manager)
AS
  VALUES
    ( 1  , 'james' ,  10000 , null ),
    ( 2  , 'alex'  ,   5000 , 1 ),
    ( 3  , 'Alice' ,   4500 , 1 ),
    ( 4  , 'Jone'  ,   3000 , 3 ),
    ( 5  , 'Omar'  ,   2200 , 2 );


Anyone who is a manager of your manager is also your indirect manager so Omar has Alex and James as indirect managers. I need a query that will get me the first indirect manager who has twice salary or more than the employee.

So result should be:

ID | Manager
1  | null
2  | 1
3  | 1
4  | 1
5  | 2
This is a query you can try. Sure it can be simplified but is a good start I think.
The key is to traverse all the managers chain recursively retaining salary information in order to compare later.

with recursive t1 as ( -- Traverse emps all the way up in the manager chain
  select id, name, salary, manager, salary indsalary, manager indirect, 1 as level
  from emp 
  union all
    select t1.id, t1.name, t1.salary, e.manager, e.salary, t1.manager, t1.level + 1
    from emp e, t1 
    where t1.manager = e.id
)
, t2 as ( -- Check salary condition
  select *
  from t1
  where  indsalary &gt;= 2 * salary
)
, t3 as ( -- get the row numbers 
  select t2.*, row_number() over (partition by id order by level) rn  
  from t2
)
, t4 as ( -- retain only first row per emp
  select * from t3
  where rn = 1
)
-- Add emps that has no manager or don't fullfill the salary condition
select e.id, t4.indirect manager
from emp e
left join t4
  on (e.id = t4.id);


Result:

 id | manager 
----+---------
  1 |  [null]
  2 |       1
  3 |       1
  4 |       1
  5 |       2
(5 rows)