0

I am experimenting with postgres and can't get this simple query to work:

drop table mytable if (select count(*) from mytable)<50 ;

This gives error:

ERROR:  syntax error at or near "if"
LINE 1: drop table tablename if (select count(*) from mytable)<50 ;

How do you alter/drop tables in postgres for a given condition?

goelakash
  • 2,502
  • 4
  • 40
  • 56
  • 1
    Postgres doesn't support a `WHERE` or `IF` clause on `DROP TABLE`: http://www.postgresql.org/docs/current/static/sql-droptable.html. – Gordon Linoff Mar 21 '16 at 18:42
  • 1
    Why do you want to? But to answer your question put the `drop` AFTER the `if`. And start reading the documentation before asking strangers on the internet. – D Stanley Mar 21 '16 at 18:42

1 Answers1

0

Creating dynamic SQL works for this (See answer) -

do
$$
declare
  l_count integer;
begin
  select count(*)
     into l_count
  from pg_class c
    join pg_namespace nsp on c.relnamespace = nsp.oid
  where c.relname = 'mytable' 
    and nsp.nspname = 'public';
  if l_count < 50 then 
    execute 'drop table mytable';
  end if;
end;
$$
Community
  • 1
  • 1
goelakash
  • 2,502
  • 4
  • 40
  • 56