0

I am exporting the table to CSV with header using COPY command in postgreSQL. Even if the table result is 0 it is creating CSV file only with header. I need CSV file with header only if number of rows is greater than 0.

Karthik M L
  • 21
  • 1
  • 4

1 Answers1

0

you can just plpgsql it:

db=# do $$
begin
if (select count(*) from t) > 0 then
copy t to '/tmp/t' with (format csv, header);
end if;
end;
$$
;
DO
db=# \! cat /tmp/t
c
2
db=# truncate table t;
TRUNCATE TABLE
db=# \! rm /tmp/t
db=# do $$
begin
if (select count(*) from t) > 0 then
copy t to '/tmp/t' with (format csv, header);
end if;
end;
$$
;
DO
db=# \! cat /tmp/t
cat: /tmp/t: No such file or directory
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132