Using IF Exists function in postgreSQL pgadmin3 (syntax error ,SQL state: 42601 Character: 1)
<p>I am trying to execute an SQL statement in pgadmin3 that do the following:  </p>

<p>If a student with a specific name and age already exists then get the <code>student_id</code> else insert a new record with the specified name and age and then get the created <code>student_id</code></p>

<p>I have tried this code: </p>

<pre><code> IF EXISTS (SELECT 1 FROM main.student WHERE studentname='hhh' and  studentage=15) 
   BEGIN
       SELECT student_id FROM main.student WHERE studentname='hhh' and   studentage=15
  END
 ELSE
   BEGIN
 INSERT INTO main.student(studentname,studentage) VALUES('hhh',15)
   END;
   END IF; 
</code></pre>

<p>But I am always getting this error:</p>

<blockquote>
  <p>syntax error at or near "IF"
  SQL state: 42601
  Character: 1</p>
</blockquote>

<p>Can you please tell me what I am doing wrong. Also how can I get the student_id after the insert statement?</p>