Part 69 Merge in SQL Server

Text version of the video
csharp-video-tutorials.blogspo...
Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our KZread channel. Hope you can help.
/ @aarvikitchen5572
Slides
csharp-video-tutorials.blogspo...
All SQL Server Text Articles
csharp-video-tutorials.blogspo...
All SQL Server Slides
csharp-video-tutorials.blogspo...
All Dot Net and SQL Server Tutorials in English
kzread.info...
All Dot Net and SQL Server Tutorials in Arabic
/ kudvenkatarabic
What is the use of MERGE statement in SQL Server
Merge statement introduced in SQL Server 2008 allows us to perform Inserts, Updates and Deletes in one statement. This means we no longer have to use multiple statements for performing Insert, Update and Delete. With merge statement we require 2 tables
1. Source Table - Contains the changes that needs to be applied to the target table
2. Target Table - The table that require changes (Inserts, Updates and Deletes)
The merge statement joins the target table to the source table by using a common column in both the tables. Based on how the rows match up as a result of the join, we can then perform insert, update, and delete on the target table.
Merge statement syntax
MERGE [TARGET] AS T
USING [SOURCE] AS S
ON [JOIN_CONDITIONS]
WHEN MATCHED THEN
[UPDATE STATEMENT]
WHEN NOT MATCHED BY TARGET THEN
[INSERT STATEMENT]
WHEN NOT MATCHED BY SOURCE THEN
[DELETE STATEMENT]
Example 1 : In the example below, INSERT, UPDATE and DELETE are all performed in one statement
1. When matching rows are found, StudentTarget table is UPDATED (i.e WHEN MATCHED)
2. When the rows are present in StudentSource table but not in StudentTarget table those rows are INSERTED into StudentTarget table (i.e WHEN NOT MATCHED BY TARGET)
3. When the rows are present in StudentTarget table but not in StudentSource table those rows are DELETED from StudentTarget table (i.e WHEN NOT MATCHED BY SOURCE)
Create table StudentSource
(
ID int primary key,
Name nvarchar(20)
)
GO
Insert into StudentSource values (1, 'Mike')
Insert into StudentSource values (2, 'Sara')
GO
Create table StudentTarget
(
ID int primary key,
Name nvarchar(20)
)
GO
Insert into StudentTarget values (1, 'Mike M')
Insert into StudentTarget values (3, 'John')
GO
MERGE INTO StudentTarget AS T
USING StudentSource AS S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.NAME = S.NAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, NAME) VALUES(S.ID, S.NAME)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Please Note : Merge statement should end with a semicolon, otherwise you would get an error stating - A MERGE statement must be terminated by a semi-colon (;)
In real time we mostly perform INSERTS and UPDATES. The rows that are present in target table but not in source table are usually not deleted from the target table.
Example 2 : In the example below, only INSERT and UPDATE is performed. We are not deleting the rows that are present in the target table but not in the source table.
Truncate table StudentSource
Truncate table StudentTarget
GO
Insert into StudentSource values (1, 'Mike')
Insert into StudentSource values (2, 'Sara')
GO
Insert into StudentTarget values (1, 'Mike M')
Insert into StudentTarget values (3, 'John')
GO
MERGE INTO StudentTarget AS T
USING StudentSource AS S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.NAME = S.NAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, NAME) VALUES(S.ID, S.NAME);

Пікірлер: 81

  • @prashantakarte563
    @prashantakarte5639 жыл бұрын

    Hi Venkat, I went through your complete series of SQL tutorial & I found it very much useful in my day to day work. I couldn't resist myself on commenting about your videos. They are really nice. Thanks for your efforts. I'm looking forward to see videos on QTP test automation tool. May god bless you!.. Thanks

  • @QuickZ_
    @QuickZ_4 жыл бұрын

    Once again you succeed to explain something where everyone else fails. Thank you!

  • @denvernaidoo
    @denvernaidoo5 жыл бұрын

    I found what I was looking for in the first 2 minutes of your video. Thank you for explaining so clearly.

  • @theraizadatalks14
    @theraizadatalks144 күн бұрын

    I'll always be grateful to you for creating this SQL playlist free for people like us. Thanks Venkat

  • @alturker9130
    @alturker91308 жыл бұрын

    I love you Venkat, I grew up with your videos when I was Jr. You are my hero!

  • @Csharp-video-tutorialsBlogspot

    @Csharp-video-tutorialsBlogspot

    8 жыл бұрын

    +al turker Thank you very much for taking time to give feedback. This means a lot. I am very glad you found the videos useful. Dot Net & SQL Server training videos for web developers kzread.infoplaylists?view=1&sort=dd You can order DVDs for offline viewing using the link below www.pragimtech.com/Order.aspx Code Samples & Slides are on my blog csharp-video-tutorials.blogspot.com Tips to effectively use our channel kzread.info/dash/bejne/q2tskq-wmLydYNY.html To receive email alerts, when new videos are uploaded, please subscribe to our channel kzread.info Please click that THUMBS UP button below the video, if you like the videos Thanks a million for sharing these resources with your friends Best Venkat

  • @tedbrick8752
    @tedbrick8752 Жыл бұрын

    Great great thanks for the great course, I spent dozens of hours learning not only SQL Server technologies but also technical English listening your course. The way of teaching is beautiful and amazing. Thanks for your efforts, thanks from Poland.

  • @yogev-drushimil2258
    @yogev-drushimil22582 жыл бұрын

    and again you did it, you took something I thought was complicated and manage to simplify it. genius ! Thank you.

  • @ShreyasKumar
    @ShreyasKumar9 жыл бұрын

    Hi venkat thanks for your tutorials. you made me to learn SQL with ease. Thank a lot :) cheers

  • @kanishmishra4716
    @kanishmishra47169 жыл бұрын

    Hello Venkat Sir, I m fan of your. Your way of explanation is awesome. Ty for your tutorials.

  • @vivekgondaliya
    @vivekgondaliya9 жыл бұрын

    Immensely helpful tutorial. Thanks for the upload. Keep up the good work. Thanks.

  • @krzysztofs8535
    @krzysztofs85357 жыл бұрын

    I love the style of your teaching. Excellent. Bravo !

  • @MaxQuagliotto
    @MaxQuagliotto8 жыл бұрын

    Very concise and helpful! All SQL Server example documentation should be this concise.

  • @wasimbader9170
    @wasimbader91708 жыл бұрын

    Thank you, its getting better and better.

  • @btulkas8199
    @btulkas81997 жыл бұрын

    Venkat, Thank you so much for this video, you answered a specific question I had about "when not matched by source"

  • @user-qf2xk1fg6e
    @user-qf2xk1fg6e3 жыл бұрын

    Thank you! If I saw your tutorials before, I wouldn't have so many troubles with SQL Server now. Gotta fix it just now! Thank you for your work! Subscription is from me.

  • @weiwei7700
    @weiwei77009 жыл бұрын

    Thanks a lot, Venkat. This series of videos are really informative and most importantly they are free. Thank you for your efforts making these videos, Thanks again, God bless you

  • @reddyabhik
    @reddyabhik3 жыл бұрын

    Excellent explanation with example on SQL Merge statement.

  • @tigoogoo
    @tigoogoo8 жыл бұрын

    these are the best tutorials on youtube. thank you!

  • @guotinghust
    @guotinghust9 жыл бұрын

    Thank you so much. The series of videos really help a lot!

  • @dbin805
    @dbin8058 жыл бұрын

    another clear and concise explanation. Thank you.

  • @ashok8846
    @ashok88466 жыл бұрын

    God bless you sir for the work you are doing for us without thinking of any gain

  • @avinashbasetty
    @avinashbasetty5 жыл бұрын

    Thank you venkat, it really helped me to understand the usage of merge query

  • @ga7853
    @ga78538 жыл бұрын

    This was great, and if you did not bring this subject "Merge" I would not know it in spite Of I was doing SQL for quiet sometime, So Thank you again and again.

  • @PuniKM
    @PuniKM4 жыл бұрын

    You are better than many textbooks

  • @Eisenhiem24
    @Eisenhiem249 жыл бұрын

    Amazing tutorial series...Thanks a ton....Cheers!!!!!!

  • @aliazad1118
    @aliazad11185 жыл бұрын

    Perfect and helpful as usual.

  • @tekilagerila2447
    @tekilagerila24479 жыл бұрын

    Fantastic..god job!

  • @MrIrrepressible
    @MrIrrepressible6 жыл бұрын

    another great tutorial Venkat. Excellent work as always

  • @rajeshd03
    @rajeshd035 жыл бұрын

    Amazing tutorials.. Thanks a lot ...!!!

  • @krismaly6300
    @krismaly63009 жыл бұрын

    Wow This is is a good functionality After OLTP work using this in nightly batch may be good. I enjoyed the video and recommend to others. One thing I observed that in this video that you mentioned the applicable version. My suggestion every time a video is made on what software version it is based is very important to audiences since lot of versions are jumping very fast. Thanks for educating the community and appreciate your volunteer-ship. Thanks a lot

  • @donaldoji6399
    @donaldoji63996 жыл бұрын

    dude, you are amazing! I am subscribing now

  • @sahi_beatz
    @sahi_beatz10 ай бұрын

    Simply Glorious Explanation.

  • @devarakondasankararao3802
    @devarakondasankararao38025 жыл бұрын

    Hi Venkat sir ,Thanks for your videos

  • @porsche606
    @porsche6063 жыл бұрын

    Amazing teacher! Thanks so much

  • @ecarlosbc
    @ecarlosbc9 жыл бұрын

    God bless you :D

  • @HAMZA-he9nd
    @HAMZA-he9nd9 жыл бұрын

    I like the way you explain

  • @rahulk4254
    @rahulk42543 жыл бұрын

    How simply explained. Thankyou for this tutorial

  • @krismaly6300
    @krismaly63009 жыл бұрын

    Revisiting. Thanks for educating the community Thanks a lot

  • @kishorkshirsagar2643

    @kishorkshirsagar2643

    5 жыл бұрын

    Very clean and clear explanation thank you

  • @robertgray6512
    @robertgray65123 жыл бұрын

    Well done!

  • @omkarsakhalkar4158
    @omkarsakhalkar41589 жыл бұрын

    Hi Venkant, Your videos are very helpfull. Can you please upload the videos on SSIS, SSRS and SSAS. Thank you Very Much.

  • @jtopu

    @jtopu

    9 жыл бұрын

    yes i agree with you ,would you pls make videos on SSIS, SSRS and SSAS.Thanks

  • @ADAMSIVES
    @ADAMSIVES8 жыл бұрын

    Excellent!

  • @shadowitself
    @shadowitself Жыл бұрын

    super condensed, super simple, just super :) thx

  • @Prem591
    @Prem5917 жыл бұрын

    great !, I don't have words to say

  • @noronhasanjay
    @noronhasanjay2 жыл бұрын

    Thank you very much. Very clear.

  • @mariokresnadi3471
    @mariokresnadi34713 жыл бұрын

    Very clear and concise explanation

  • @My_1981
    @My_19819 жыл бұрын

    Good explanation

  • @nehamegha3384
    @nehamegha3384 Жыл бұрын

    Thanks for the tutorial 🤗

  • @gemini1053
    @gemini10532 жыл бұрын

    Thank you!

  • @muhammadzarshid7628
    @muhammadzarshid76289 жыл бұрын

    tremendously doing nice effort.. could please sir upload Crystal Report videos...thank you

  • @huwpickrell1209
    @huwpickrell1209 Жыл бұрын

    Clearly explained

  • @FlyMintGreen
    @FlyMintGreen7 жыл бұрын

    finally i got the point, thanks!

  • @akshayshetye8718

    @akshayshetye8718

    7 жыл бұрын

    yeah!! me too..

  • @Mpenduloanswer
    @Mpenduloanswer Жыл бұрын

    well explained

  • @gracechan3039
    @gracechan30394 жыл бұрын

    5 years later, thank you very much.

  • @mumk
    @mumkАй бұрын

    at 1:10 is all I need, thank you!

  • @mshahzeb8926
    @mshahzeb89264 жыл бұрын

    hi vanket! i just want to say you from my heart "LOVE YOU". you are my hero !!!!!!!!!!!!!!!!!!!!!!

  • @NandhaKumar-ev9sj
    @NandhaKumar-ev9sj11 ай бұрын

    I got the below err // when i merge condition is having sometime 1 or 5more records it that the cause ?? The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

  • @entertainmentvideos8550
    @entertainmentvideos85509 жыл бұрын

    can uu upload the videos how to handle the large number of servers at a time its means about server handling

  • @Real28
    @Real28 Жыл бұрын

    Nice

  • @navneetthakur1118
    @navneetthakur11182 жыл бұрын

    Hi venkat, Can you please explain, why merge statement ends with semi-colon?

  • @cebabu
    @cebabu4 жыл бұрын

    Could you please suggest how to add new seed data/lookup data into two tables which has foreign key relationship. These tables already has some data. I want to add new lookup data to existing data. Please suggest. How to use Merge . Any other ways to setup lookup data

  • @jonkc3635
    @jonkc36356 жыл бұрын

    So, if I want to insert multiple rows into the our existing "target" table, we have to create another table? It seems like a waste of space, just to create an additional table to insert a few rows.

  • @jonkc3635

    @jonkc3635

    6 жыл бұрын

    oh, you can do this: MERGE INTO [Language] AS Target USING (VALUES (1, 'en', 'English'), (2, 'fr', 'French'), (3, 'zh', 'Chinese') ) AS .................

  • @vedantdesai6559
    @vedantdesai65592 жыл бұрын

    Hello Can we compare particular one column for merge ?

  • @kanagarajk3967
    @kanagarajk39675 ай бұрын

    I want to move tat deleted record(John) into a separate table and then delete it here . Is it possible?

  • @omaraissa318
    @omaraissa3184 жыл бұрын

    Precisely in this situation it's like Dropping Target and renaming Source to Target Name

  • @kasthuri2730
    @kasthuri27303 жыл бұрын

    Hello sir, please teach about how to merge two databases in sql server

  • @saikarthik4a9
    @saikarthik4a92 жыл бұрын

    What if we have 50 columns in source and target then how do we update all the columns?

  • @kashyapjain2018
    @kashyapjain20183 жыл бұрын

    Anyone after 2020?

  • @ionescuvictor1011
    @ionescuvictor10117 жыл бұрын

    but is it thread safe, that is the real question.

  • @sushmamc8904
    @sushmamc89042 жыл бұрын

    Hi Sir, how can we use this merge to update more than one column ? Please help

  • @ashishchinna9201

    @ashishchinna9201

    Жыл бұрын

    If your source is s, target is t and has columns (id, productname, price), then you can do the following Update Set t.prodcutname=s.productname, t.price=s.price This will update multiple columns in the target table with the corresponding source table values.

  • @shubhashish1994
    @shubhashish19948 ай бұрын

    3:52 By default value

  • @josephjoy7080
    @josephjoy70803 жыл бұрын

    learned Merge at tutorial nr 69 coincidence ? i think not

  • @gvn.kokilarao4872
    @gvn.kokilarao48722 жыл бұрын

    I am not liking the video