title: How to select specific rows in PostgreSQL query?
body: <p>I have written a query to get the 'reason_code' and 'app_count' for top five rows from result set and sum of remaining app_count under name 'others'.</p>
  
  <p>Here what I have tried:</p>
  
  <pre><code>(SELECT a.app_pgm_rsnd_rsn_cd, a.denied_app_count
  FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
  FROM app_pgm_choice, ead_case 
  where app_pgm_sts= 'DN'
  AND app_pgm_req_dt &gt;= '20150101'
  AND app_pgm_req_dt &lt;= '20150130'
  AND EAD_CS_APP_NUM =  APP_PGM_NUM
  AND EAD_CS_SEND_CNTY_ID = '19'
  AND EAD_CS_TRAN_STS = 'PE'
  GROUP BY app_pgm_rsnd_rsn_cd
  ORDER BY denied_app_count desc) a
  WHERE ROWNUM &lt;=5 )
  
  UNION ALL
  
  (SELECT 'OTHERS' as app_pgm_rsnd_rsn_cd, SUM(b.denied_app_count) as    denied_app_count
  FROM (SELECT app_pgm_rsnd_rsn_cd ,COUNT(1) as denied_app_count
  FROM app_pgm_choice, ead_case 
  where app_pgm_sts= 'DN'
  AND app_pgm_req_dt &gt;= '20150101'
  AND app_pgm_req_dt &lt;= '20150130'
  AND EAD_CS_APP_NUM =  APP_PGM_NUM
  AND EAD_CS_SEND_CNTY_ID = '19'
  AND EAD_CS_TRAN_STS = 'PE'
  GROUP BY app_pgm_rsnd_rsn_cd
  ORDER BY denied_app_count desc) b
  WHERE ROWNUM &gt;=5 )
  </code></pre>
  
  <p>But when I run this query it shows following error message:</p>
  
  <blockquote>
    <p>ERROR:  column "rownum" does not exist
       LINE 13: WHERE ROWNUM &lt;=5 )
                 ^</p>
    
    <p>********** Error **********</p>
    
    <p>ERROR: column "rownum" does not exist
      SQL state: 42703
      Character: 397</p>
  </blockquote>
  
  <p>What is option for ROWNUM variable?</p>