title: Postgresql query for getting n-level parent-child relation stored in a single table
body: <p>I have a table denoting parent-child relations. The relations can go n-level deep.</p>
  
  <p>I have created a sample table using the following query:</p>
  
  <pre><code>CREATE SEQUENCE relations_rel_id_seq
      INCREMENT BY 1
      NO MAXVALUE
      NO MINVALUE
      CACHE 1;
  CREATE TABLE relations(
      rel_id bigint DEFAULT nextval('relations_rel_id_seq'::regclass) NOT NULL PRIMARY KEY,
      rel_name text,
      rel_display text,
      rel_parent bigint
  );
  </code></pre>
  
  <p><a href="http://sqlfiddle.com/#!11/59319/1">SQLFiddle</a></p>
  
  <p>I need to query the table and display the parent-child relations hierarchically. I'm still not getting an idea regarding how to query n-level deep using sql query.</p>
  
  <p>For the sqlfiddle eg, the expected hierarchy of output:</p>
  
  <pre><code>rel1
      rel11
          rel111
          rel112
              rel1121
  rel2
      rel21
          rel211
          rel212
  </code></pre>
  
  <p><strong>N.B:</strong> The value n, in <code>n-level</code> is unknown.</p>
  
  <p><strong>DB Design:</strong></p>
  
  <blockquote>
    <p>Is there any better way such a relation can be expressed in the
    database for easy querying.?</p>
  </blockquote>