Optimizing postgresql maintenance statements on psql
The most pertinent advice I've seen is in this SO answer, but it seems the with clause has to be inside the SQL statement it's being called in.


Yes, you can use a modifying WITH, i.e. a CTE that deletes from one table and returns the id values to the rest of the query, so they can be used to delete from the second table:

WITH
  links_link_deleted AS
    ( DELETE FROM links_link
        WHERE submitted_on &gt;= timestamp'2016-07-23 01:00:00'
          AND submitted_on &lt; timestamp'2016-08-23 01:00:00'
      RETURNING id
    ) 
DELETE FROM links_publicreply
  WHERE submitted_on &gt;= timestamp '2016-07-23 01:01:00'
    AND submitted_on &lt; timestamp '2016-09-07 01:00:00'
    AND answer_to_id IN
        ( SELECT id
          FROM links_link_deleted
        )
 ;



  In other words, the following wouldn't work would it?


That would work but it would be two statements.