I have an postgres table in the below structure
I want to write a query which will Delete all the records from the table which are older than 90 days and is in COMPLETE status. if any row has a root_id or a parent_id and is OPEN, then the root_id and the parent_id rows should not be deleted. In the above tables, the row with id=1 should be deleted. Although, id=2 and id=3 are complete and older than 90 days, but since the id=4 has root_id and parent_id has 2 and 3, all the 3 rows (id=2,id=3 and id=4) should not be deleted.
I tried multiple ways with inner queries but I am not able to write a query for this scenario.
2
Answers
Translating your requirement into SQL, I get
Step by step – first identify record
id
-s that are parents or roots of records with ‘OPEN’ status and store them int
CTE, then delete those records that are ‘COMPLETE’, older than 90 days and whoseid
is not int
.ts = 'older than 90 days'
is illustrative.DB-fiddle demo