PostgreSQL 9.3: IF NOT EXISTS

12,758
DO
$do$
BEGIN
IF NOT EXISTS (SELECT * from INFORMATION_SCHEMA.Tables WHERE Table_name = 'test') THEN

    RAISE INFO 'Not exists';

else

    RAISE INFO 'Exists';

end if;
end;
$do$

You should surround your postgresql statements with block

Share:
12,758
MAK
Author by

MAK

Database Developer (Microsoft SQL Server and PostgreSQL).

Updated on July 04, 2022

Comments

  • MAK
    MAK almost 2 years

    I want to check whether the table exists or not in the database.

    IF NOT EXISTS (SELECT * from INFORMATION_SCHEMA.Tables WHERE Table_name = 'test') THEN
    
        RAISE INFO 'Not exists';
    
    else
    
        RAISE INFO 'Exists';
    
    end if;
    

    Getting an error:

    ERROR:  syntax error at or near "IF"
    
  • thepurpleowl
    thepurpleowl over 4 years
    why this works?