title: PostgreSQL - Hierarchical List of All tables
body: <p>I need to list all table of my database (PostgreSQL) in hierarchical order.
  Thats mean: If the table "user" have a Foreign Key to table "role", then it must to come after the table "role" in the list.</p>
  
  <p>Something equivalent at to:</p>
  
  <pre><code>EXEC sp_msdependencies @intrans = 1 
  </code></pre>
  
  <p>In SQL Server.</p>
  
  <p>I tried that, but without success:
  </p>
  
  <pre><code>SELECT
      pt.table_name as tablename,
      string_agg(DISTINCT ccu.table_name, ',') AS reftable
  FROM information_schema.tables pt
  LEFT JOIN information_schema.columns c
      ON c.table_name = pt.table_name
  LEFT JOIN information_schema.table_constraints tc
      ON tc.table_name = pt.table_name AND tc.constraint_type = 'FOREIGN KEY'
  LEFT JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name AND kcu.column_name = c.column_name
  LEFT JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
  WHERE pt.table_schema = 'public'
  GROUP BY pt.table_name,pt.table_type
  ORDER BY pt.table_type DESC, COUNT(TRUE) ASC;
  </code></pre>