Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using subquery in an update always requires subquery in a where clause?

Tags:

sql

informix

This is a common SQL query for me:

update table1 set col1 = (select col1 from table2 where table1.ID = table2.ID)
where exists (select 1 from table2 where table1.ID = table2.ID)

Is there any way to avoid having two nearly identical subqueries? This query is an obvious simplification but performance suffers and query is needlessly messy to read.

like image 253
Nezreli Avatar asked Oct 02 '22 20:10

Nezreli


1 Answers

Unfortunately Informix don't support the FROM clause at UPDATE statement. The way to workaround and you will get better results (performance) is change the UPDATE to MERGE statement.

This will work only if your database is version 11.50 or above

MERGE INTO table1 as t1
USING table2 as t2
   ON t1.ID = t2.ID
WHEN MATCHED THEN UPDATE set (t1.col1, t1.col2) = (t2.col1, t2.col2);

Check IBM Informix manual for more information

like image 94
ceinmart Avatar answered Oct 07 '22 17:10

ceinmart