Hierarchy of tables based on foreign keys

with recursive getall as ( select distinct ac.*, ac.table_name||'; ' as hierarchy, 1 as _level from allconst ac where dep_table_name is null --and table_schema='...your_schema_in_db...' --optional if you need to narrow select --and table_name='...your_table_name...'...