1

I would like to check if a table is empty, and if it is, I would like drop it. I know this little function doesn't seem as a useful thing by itself, but I have a much longer function, so this is just the main part.

CREATE OR REPLACE FUNCTION public.cl_tbl(t_name character varying)
RETURNS void AS
$BODY$
DECLARE
    rownum int;
BEGIN
    SELECT COUNT(*) INTO rownum FROM format('myschema.%I',t_name);
    IF rownum = 0 then
        EXECUTE format('DROP TABLE myschema.%I',t_name);
    END IF;
    RETURN;
END;
$BODY$
 LANGUAGE plpgsql VOLATILE

My problem is, that the line

SELECT COUNT(*) INTO rownum FROM format('myschema.%I',t_name);

doesn't returns 0 if the table is empty, instead it returns 1 as the number of rows of the selection.

    | count(bigint)
--------------------
 1  |       0

I've tried this as well:

rownum := SELECT COUNT(*) FROM format('myschema.%I',t_name);

but the result is the same. How could I pass the real number of the rows of a given table?

2 Answers 2

4

You can use EXISTS() - SELECT EXISTS(SELECT * FROM table_name).

CREATE OR REPLACE FUNCTION public.cl_tbl(t_name character varying)
RETURNS void AS
$BODY$
DECLARE
    x BOOLEAN;
BEGIN
    EXECUTE format('select exists (select * from myschema.%I) t', t_name) INTO x;
    IF x = False then
        EXECUTE format('DROP TABLE myschema.%I',t_name);
    END IF;
    RETURN;
END;
$BODY$
 LANGUAGE plpgsql VOLATILE
2
  • Thank you! I see what's happening here, but for some reason it doesn't do the job. I checked and the result of SELECT EXISTS( SELECT * FROM format('myschema.%I',t_name)) is False, so I don't know what's the poblem.
    – 588chm
    Commented Jun 9, 2020 at 8:26
  • 2
    You need to make the whole exists query dynamic: execute format('select exists (select * from %I) t', t_name) into x;
    – user330315
    Commented Jun 9, 2020 at 8:38
1

Try using EXECUTE:

CREATE OR REPLACE FUNCTION public.cl_tbl(t_name character varying)
RETURNS void AS
$BODY$
DECLARE
    rownum int;
BEGIN
    EXECUTE format('select count(*) from %I', t_name) into rownum;
    IF rownum = 0 then
        EXECUTE format('DROP TABLE %I',t_name);
    END IF;
    RETURN;
END;
$BODY$
 LANGUAGE plpgsql VOLATILE
;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.