I have the table as like below.
CREATE TABLE my.categories (id bigint, parent_id bigint, name varchar(128));
INSERT INTO my.categories (id, parent_id, name)
If I get you, this is what you need.
First, with the folowing query you can get all the parent ids:
WITH RECURSIVE t(id, parentlist) AS (
SELECT id, ARRAY[]::bigint[] FROM my.categories WHERE parent_id IS NULL
UNION
SELECT my.categories.id, my.categories.parent_id || t.parentlist
FROM my.categories
JOIN t ON categories.parent_id = t.id
) SELECT * FROM t
-- outputs:
-- id | parentlist
-- ----+------------
-- 1 | {}
-- 2 | {1}
-- 3 | {1}
-- 4 | {2,1}
-- 5 | {2,1}
-- 6 | {3,1}
If you want to get a record of the parents of one id you just need to change the query like:
WITH RECURSIVE t(id, parentlist) AS (
SELECT id, ARRAY[]::bigint[] FROM my.categories WHERE parent_id IS NULL
UNION
SELECT my.categories.id, my.categories.parent_id || t.parentlist
FROM my.categories
JOIN t ON categories.parent_id = t.id
) SELECT unnest(parentlist) as parents_ids FROM t WHERE id=6;
-- outputs:
-- parents_ids
-- -----------
-- 3
-- 1
Note that the last query does not output the "current" id (6).