How can I delete flow runs older than 30 days using GraphQL API to clean up database space in Prefect Server?

Here is an example script you can use:

import prefect
from datetime import datetime, timezone
client = prefect.Client()

flows = client.graphql(
    {
        'query': {
            'flow': {
                'id'
            }
        }
    }
)

for flow in flows['data']['flow']:
    flow_runs = client.graphql(
        {
        'query': {
            'flow (where: {id: {_eq: "'+flow['id']+'"}})':{
                'flow_runs':{
                    'id',
                    'name',
                    'start_time'
                }
            }
        }
        }   
    )
    for flow_run in flow_runs['data']['flow'][0]['flow_runs']:
        if flow_run['start_time']:
            if (datetime.now() - datetime.strptime(flow_run['start_time'], '%Y-%m-%dT%H:%M:%S.%f+00:00')).days > 30:
                print(flow_run['name'])
                client.graphql(
                    {
                        'mutation': {
                            'delete_flow_run(input: {flow_run_id: "'+flow_run['id']+'"})':{
                                'success',
                                'error'
                            }
                        }
                    }
                )

This was user-contributed - see this Github issue

For alternative solutions to clean up database space in your Server, check out this StackOverflow thread.