cathulhu
cathulhu

Reputation: 657

"Update if table exists" in one statement - how?

I have a problem with SQL statement which is a part of long transaction.

UPDATE tab_1 LEFT JOIN tab_2 ON tab_1.id = tab_2.tab_1_id SET tab_1.something = 42 WHERE tab1.id = tab_2.tab_1_id;

Everything is simple and works fine as long as tab_1 and tab_2 exist in database, which is obvious. ;-)

The problem is that the transaction have to be commited on 4 different servers, and tab_2 is "dynamic" table, which may exist in specific db / db schema, or not...

If tab_2 don't exists, database threw exception and the whole transaction is not commited. What I want is to continue anyway (just update 0 rows)!

I have tried something like this:

UPDATE [all the same as above] WHERE tab1.id = tab_2.tab_1_id AND EXISTS (select 1 from pg_class where relname='tab_2');

...but it's still wrong, since "exception-check" is made before "where" condition (it's the same table we want to use in join..).

Is there any way to do this with "pure" SQL? :)

Something like: LEFT JOIN tab_2 IF tab_2 EXISTS (and if not - do nothing, return null, etc.?)

I know there is a way to do this in pl/pgsql procedure. The second possibility is to create table if not exists, before the statement..

But maybe there is some kind of simple and elegant way to do this in one statement? :)

DBMS: PostgreSQL 9.2

Upvotes: 4

Views: 12220

Answers (1)

dan1111
dan1111

Reputation: 6566

I don't think an UPDATE statement that succeeds even if a table doesn't exist is simple and elegant. I think it is strange and confusing.

Why not just include a conditional that checks whether that table exists, and only perform the update if it exists? It would be a lot clearer.

Another option would be to create a view that points to tab_2 if it exists, or points to an empty table otherwise. This could be helpful if you have a lot of queries like this, and you don't want to change them all.

Update: Here is what a condition would look like (has to be within a function or a BEGIN...END block):

IF EXISTS (select 1 from pg_class where relname='tab_2') THEN 
   UPDATE...
END IF;

Depending on the details of Postgresql, this still might fail compilation if it sees a table that doesn't exist in the UPDATE statement (I'm not a Postgresql user). In that case, you would need to create a view that points to tab_2 if it exists, and an empty table if it doesn't exist..

Upvotes: 3

Related Questions