sqlsnowflake-cloud-data-platform

Snowflake update using left join


Created 4 tables in both SQL Server and Snowflake. Inserted these values.

INSERT INTO t1 (id, name, v) VALUES
(1, 'Name1_T1', 100),
(2, 'Name2_T1', 200),
(3, 'Name3_T1', 300),
(4, 'Name4_T1', 300),
(5, 'Name5_T1', 300);

INSERT INTO t2 (id, name, v) VALUES
(4, 'Name1_T2', 400),
(1, 'Name3_T2', 600); 


INSERT INTO t3 (id, name, v) VALUES
(4, 'Name3_T3', 900);


INSERT INTO t4 (id, name, v) VALUES
(2, 'Name3_T4', 1200); 

This is my SQL Server syntax:

update t1
set v = 0
from t1 table1
left outer join t2 table2
on table1.id = table2.id
left outer join t3 table3
on table2.id = table3.id
left outer join t4 table4
on table3.id = table4.id
where table1.id = 2;

This is in Snowflake

update t1
set v = 0
from t1 table1
left outer join t2 table2
on table1.id = table2.id
left outer join t3 table3
on table2.id = table3.id
left outer join t4 table4
on table3.id = table4.id
where table1.id = 2;

But SQL Server returns 1 row, snowflake returns 5. Is there any other way to get 1 row in snowflake.

SQL Server changes column v for id 2 to 0 in t1, But Snowflake makes all column v as 0 in all 5 ids in t1.


Solution

  • I tried the select with Left outer join and it returns only one rows, but the update with left outer join updates 5 rows.

    create  or replace table t1 (id varchar(10), name varchar(100), v number) ;
    create  or replace table t2 (id varchar(10), name varchar(100), v number) ;
    create  or replace   table t3 (id varchar(10), name varchar(100), v number) ;
    create  or replace   table t4 (id varchar(10), name varchar(100), v number) ;
    
    INSERT INTO t1 (id, name, v) VALUES
    (1, 'Name1_T1', 100),
    (2, 'Name2_T1', 200),
    (3, 'Name3_T1', 300),
    (4, 'Name4_T1', 300),
    (5, 'Name5_T1', 300);
    
    INSERT INTO t2 (id, name, v) VALUES
    (4, 'Name1_T2', 400),
    (1, 'Name3_T2', 600); 
    
    
    INSERT INTO t3 (id, name, v) VALUES
    (4, 'Name3_T3', 900);
    
    
    INSERT INTO t4 (id, name, v) VALUES
    (2, 'Name3_T4', 1200); 
        -- returns 1 row
        select table1.id,table1.* from 
          t1 table1
        left outer join t2 table2
        on table1.id = table2.id
        left outer join t3 table3
        on table2.id = table3.id
        left outer join t4 table4
        on table3.id = table4.id
        where table1.id = 2;
        
    
    --You can try with the (+) syntax for left outer join and it updates one row. 
       
         update t1 table1
        set v = 0
        from  t2 table2 , t3 table3
        ,t4 table4
        where table1.id = 2  and
        table1.id = table2.id(+) and
         table2.id = table3.id(+) and 
          table3.id = table4.id(+)
        ;
    

    enter image description here