0

I have an sql statement that looks like this:

delete from survey_results sr
left outer join people p on p.id = sr.person_id
left outer join survey_result_sets srs on srs.id = sr.survey_result_set_id
left outer join survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);

but it gaves an syntax error:

ERROR:  syntax error at or near "left"
LINE 2: left outer join people p on p.id = sr.person_id

Why is that?

2 Answers 2

2

You can't use JOIN in DELETE statement in PostgreSQL. Instead use USING and put the second table there. Something like this should work

   delete from survey_results sr
using people p on p.id = sr.person_id
using  survey_result_sets srs on srs.id = sr.survey_result_set_id
using  survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);

You can refer this PostgreSQL-delete

Sign up to request clarification or add additional context in comments.

5 Comments

When I paste your code to my database console it returns me: ERROR: syntax error at or near "sr" LINE 1: delete sr
Hi @MateuszUrbański If you are using PostgreSQL then you cant use joins in the delete
Your code still gaves syntax error: ERROR: syntax error at or near "on" LINE 2: using people p on p.id = sr.person_id But when googling there are a lot of topics people using delete with joins in postgress.
You are right with this joins but I still can't make this query to work. Why this syntax error is causing?
USING can only be used once in a DELETE statement it's pretty much the same as the FROM clause in a SELECT statement
1

How about :

begin;
create temp table table_survey_result_pk on commit drop as select survey_result_pk from survey_results sr
left outer join people p on p.id = sr.person_id
left outer join survey_result_sets srs on srs.id = sr.survey_result_set_id
left outer join survey_schemas ss on ss.id = sr.survey_schema_id
where (sr.person_id is not null and p.id is null)
OR (srs.id is null)
OR (ss.id is null);
delete from survey_results t using table_survey_result_pk d on t.survey_result_pk = d.survey_result_pk;
commit;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.