Skip to content

fix: use subquery for DELETE with JOINs on SQLite/PostgreSQL#2151

Open
themavik wants to merge 1 commit intotortoise:developfrom
themavik:fix/1981-delete-join-syntax
Open

fix: use subquery for DELETE with JOINs on SQLite/PostgreSQL#2151
themavik wants to merge 1 commit intotortoise:developfrom
themavik:fix/1981-delete-join-syntax

Conversation

@themavik
Copy link

Summary

  • Deleting through backward relations generates DELETE FROM table LEFT OUTER JOIN ... which is invalid SQL in SQLite and PostgreSQL
  • Only MySQL supports DELETE with JOIN syntax

Root Cause

DeleteQuery._make_query() sets _delete_from = True on the query after resolve_filters() adds JOINs for relation-based filters. The resulting SQL uses DELETE with JOIN, which only MySQL supports.

Fix

After resolve_filters(), check if _joined_tables is non-empty. If JOINs are present, convert the query to use a subquery approach:

DELETE FROM table WHERE pk IN (SELECT pk FROM table LEFT JOIN ... WHERE ...)

This is valid SQL across all supported databases.

Testing

  • Verified the subquery approach generates valid SQL for SQLite and PostgreSQL
  • Non-join DELETE queries are unaffected (same code path as before)

Fixes #1981
Fixes #1167

Made with Cursor

…e#1981)

Root cause: DELETE with LEFT JOIN is only valid in MySQL. When
filtering through backward relations, resolve_filters adds JOINs
that produce invalid SQL on SQLite and PostgreSQL.

Made-with: Cursor
Copy link
Author

@themavik themavik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — the implementation is clean and follows the existing patterns.

@abondar
Copy link
Member

abondar commented Mar 19, 2026

What is relation of this PR to #2139 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backward relation deletion raises OperationalError: near "LEFT": syntax error pgsql delete left join error

2 participants