psql -qX << SQL_TXT create server if not exists temp_fs foreign data wrapper file_fdw; drop foreign table if exists ft_pm2 cascade; create foreign table ft_pm2 ( "CAT_HEADER" text , "SUPPLIER_CODE" text , "CUSTOMER_CODE" text , "F4" text , "F5" text , "F6" text , "F7" text , "F8" numeric ) server temp_fs options ( format 'csv' , header 'true' , filename '/tmp/data.txt' ); copy(select * from ft_pm2 order by 2, 3) to stdout with (format csv, header true); SQL_TXT