I am trying to execute an SQL statement in pgadmin3 that do the following:
If a student with a specific name and age already exists then get the student_id else insert a new record with the specified name and age and then get the created student_id
I have tried this 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;
But I am always getting this error:
syntax error at or near "IF" SQL state: 42601 Character: 1
Can you please tell me what I am doing wrong. Also how can I get the student_id after the insert statement?
Some points you need to consider:
IFstatement, you need to useTHENBEGIN/END;at the end of each statementAlso if you are running an ad-hoc statement, you need to run it within
DOcommandFor the last part of your question, you can return the id you are inserting