Long term data query producing Error 500 (Internal Server Error)

As Coro already said, it is like a php memory issue. You can increase the limit by
changing memory_limit in /etc/php/7.3/cgi/php.ini and

sudo service lighttpd force-reload

Adjust to limit according to the amout of RAM you have.

See here for more details: