Snowflake snippets

How to perform and INSERT/UPDATE on match/unmatch in Snowflake

Let's start making a Food table:

CREATE TABLE Food(
	Code varchar(50) NOT NULL PRIMARY KEY,
	Grp varchar(100) NULL,
	Quantity int NOT NULL,
	Color nvarchar(50) NULL
);
INSERT INTO Food
  (Code, Grp, Quantity,Color)
VALUES
  ('Apple', 'Fruit', 44, 'red'),
  ('Apple', 'Fruit', 1, 'yellow'),
  ('Pineapple', 'Fruit', 14, 'brown'),
  ('Apple', 'Fruit', 12, 'red'),
  ('Banana', 'Fruit', 1, 'yellow'),
  ('Tomatoes', 'Vegetables', 8, 'red'),
  ('Cucumbers', 'Vegetables', 3, 'green');
Snowflake snippet 13

and another (temporary) table Food_tmp:

CREATE TEMPORARY TABLE Food_tmp(
	Code varchar(50) NOT NULL PRIMARY KEY,
	Grp varchar(100) NULL,
	Quantity int NOT NULL,
	Color nvarchar(50) NULL
);
INSERT INTO Food_tmp
  (Code, Grp, Quantity, Color)
VALUES
  ('Watermelon', 'Fruit', 100, 'multi'),
  ('Banana', 'Fruit', 21, 'green');
Snowflake snippet 14

Now, suppoe we want to insert the rows if they are new (looking at the Code column) or update the relative values. For this activity we can use the following:

MERGE INTO Food T USING (
    SELECT T.Code AS T_ID, S.*
    FROM (
        SELECT Code FROM Food 
    ) T
    FULL OUTER JOIN Food_tmp S 
    ON T.Code = S.Code
) S ON S.T_ID = T.Code 
WHEN MATCHED AND T.Code=S.Code THEN UPDATE SET Grp=S.Grp, Quantity=S.Quantity, Color=S.Color
WHEN NOT MATCHED THEN INSERT VALUES (S.Code, S.Grp, S.Quantity, S.Color);
Snowflake snippet 15

Snowflake snippet 16

Back to Snowflake cookbook page