Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop SQL script execution for PostgreSQL?

Tags:

sql

postgresql

There is DDL script in PostgreSQL that creates tables.

For example, if first table exists, How to stop SQL script execution for PostgreSQL (within script)?

like image 232
Paul Verest Avatar asked Aug 10 '26 07:08

Paul Verest


1 Answers

If you want to abort a script based on a condition you can do that using a DO block that raises an error:

do
$$
declare 
  l_count integer;
begin

  select count(*)
     into l_count
  from information_schema.tables
  where table_name = 'foobar'
    and table_schema = 'public';

  if (l_count > 0) then 
     raise exception 'Table foobar already exists!';
  end if;
end;
$$

This requires that your SQL client will abort a script if an error occurs.


Another option is to change your script such that it doesn't do anything if the table already exists by using create table if not exists .....

But that depends on what exactly you are trying to achieve.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!