0

I have sql query that looks like this:

DELETE FROM survey_subjects WHERE id IN (
  SELECT ss.id FROM survey_subjects ss
    LEFT JOIN survey_instances si ON si.survey_subject_id = ss.id
    LEFT JOIN survey_packs sp ON si.survey_pack_id = sp.id
    LEFT JOIN school_packs scp ON sp.school_pack_id = scp.id
    LEFT JOIN survey_orders so ON scp.survey_order_id = so.id AND so.administration_id = <administration_id>
  WHERE ss.administration_id = <administration_id> AND si.id IS NULL
);

I was thinking how can I make this query more readable. I was thinking about using USING clause from PostgreSQL but it will not work for left joins. Is there any way to make it more readable?

1
  • using will of course work for left joins. But: using is only applicable if the join columns have the same name in both tables - which is clearly not the case for your tables. Commented Nov 3, 2015 at 14:51

1 Answer 1

2

I think you should simplify the logic to this:

DELETE FROM survey_subjects WHERE id IN (
  SELECT ss.id 
  FROM survey_subjects ss LEFT JOIN
       survey_instances si
       ON si.survey_subject_id = ss.id
  WHERE ss.administration_id = <administration_id> AND si.id IS NULL
);

The additional joins are not doing anything. They are not filtering the data (because the joins are left joins). They are not affecting either column in the WHERE clause, nor the column in the SELECT.

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

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.