The essential factor in your calculation is scalability.
You can scale your database by creating a cluster or splitting out the queries from the commands.
You can scale your webserver by spinning up more instances and load balancing across them.
Usually it's much cheaper and easier to scale your webserver.
Therefore where you have a choice of where to run a function, try to run it on your webserver rather than the database.
Also, there is the question of how you deploy changes. Usually it's much easier to have two versions of your website than two versions of your database.
Therefore where you have business logic which is likely to change. Prefer putting it in your code.