Many moons ago, I posted a surprisingly popular answer on StackOverflow regarding how to write to CSV files using PostgreSQL. The answer, in a nutshell, is the COPY statement. But there’s a catch – PostgreSQL imposes strict security limitations on the use of this statement, which are best dealt with using another feature, the SECURITY DEFINER option to CREATE FUNCTION. Here, I will attempt to explain in more detail what these security restrictions are, and how to do what you want without simply disabling that security.

Continue reading