truncate function doesnt work in postgres

3.5k views Asked by At

I have created the following function to truncate bunch of tables starting with "irm_gtresult". There are no syntax errors in my function, but the function doesn't truncate the tables when I run it. What could be wrong here?

My Postgres db version is 8.4.

create or replace function br()
RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
row text;
BEGIN
 FOR row IN
select table_name from information_schema.tables where table_name ILIKE 'irm_gtresult%'
LOOP
EXECUTE 'TRUNCATE TABLE ' || row;
END LOOP;
END;
$$;

Call:

select br();
2

There are 2 answers

2
Erwin Brandstetter On BEST ANSWER

Your code is valid. I tested and it works for me in Postgres 9.4.
Using the outdated and unsupported version 8.4 (like you added) may be the problem. The version is just too old, consider upgrading to a current version.

However, I have a couple of suggestions:

  • Don't use key word row as variable name.
  • You don't need to loop, you can TRUNCATE all tables in a single command. Faster, shorter.
  • You may need to add CASCADE if there are dependencies. Be aware of the effect.

CREATE OR REPLACE FUNCTION br()
  RETURNS void AS
$func$
BEGIN
   EXECUTE (
      SELECT 'TRUNCATE TABLE '
          || string_agg(format('%I.%I', schemaname, tablename), ',')
          || ' CASCADE'
      FROM   pg_tables t
      WHERE  tablename ILIKE 'irm_gtresult%'
      AND    schemaname = 'public'
      -- AND tableowner = 'postgres'  -- optionaly restrict to one user
      );
END
$func$  LANGUAGE plpgsql;

Call:

SELECT br();

I am using the view pg_tables from the system catalog. You can as well use information_schema.tables like you did. Note the subtle differences:

Related answers with more explanation:

0
Oriol Mont i Creus On

To truncate in postgres you just have to use the TRUNC() function.

Example:

SELECT TRUNC(price, 0) AS truncated_price
FROM product;