Search code examples
sqlpostgresqllimitsql-delete

Add LIMIT to query with LEFT JOIN and DELETE in PostgreSQL


I'm trying to delete data from a table that has about 12 million records, wanting to delete it in batches but you can't use LIMIT with DELETE in sql, I'm a bit stumped on how to get around it.

The query without LIMIT is:

DELETE FROM roster_validationtaskerror
USING roster_validationtaskerror AS rvte
LEFT JOIN roster_validationtask AS rvt ON rvt.id = rvte.parent_task_id
LEFT JOIN roster_validation AS rv ON rv.id = rvt.validation_id
WHERE rv.id = 10

How can I add a LIMIT to this query?

I've been trying to add subselect queries to allow for the LIMIT to be added within this and then a JOIN made after. I'm quite new to SQL so have not been able to figure out how to get this to work.


Solution

  • Try this:

    WITH r AS (
        SELECT rvte.id 
        FROM roster_validationtaskerror AS rvte
        JOIN roster_validationtask AS rvt ON rvt.id = rvte.parent_task_id
        JOIN roster_validation AS rv ON rv.id = rvt.validation_id
        WHERE rv.id = 10
        -- perhaps order by is needed if you want to delete not randomly selected rows
        LIMIT 10
    )
    DELETE FROM roster_validationtaskerror
    USING r
    WHERE r.id = roster_validationtaskerror.id