Removing failed jobs records

Hi! I’ve created a job, which removes failed job’s executions records, when it’s amount is more that 5. E.g. - some job was executed 10 times and failed 7 times - so only 5 last failed executions are stored.

For these purposes I do select from the Job table for ids of jobs with Failed statename and then I do delete from this table supplying these ids. I am not sure that this is everything I need to properly remove redundant records.

I appreciate any help to compose proper delete statement.
Thank you.