Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update help

I have a really simple question, is it possible to update a table with new values using just one update statement.

Say for example I have a table with author, title, date, popularity. Now I got some new data which has author name, title corresponding new popularity. How do I update the table now in one statement. Note that author and title are not unique.

like image 559
Sainath Mallidi Avatar asked Jun 15 '26 16:06

Sainath Mallidi


1 Answers

You can do it in a single statement using Oracle's MERGE statement:

MERGE DestinationTable target
USING   (
        Select 'Briggs' Author, 'My Next Master' Title, 6 Popularity
        Union All Select 'Millis', 'Man up, Nut head', 3
        ) Z
        ON Z.Author = target.Author
            And Z.Title = target.Title
WHEN MATCHED THEN
    UPDATE SET target.Popularity = Z.Popularity
WHEN NOT MATCHED THEN
    Insert(Author, Title, Popularity) Values(Z.Author, Z.Title, Z.Popularity);

Oracle's MERGE statement

like image 68
Thomas Avatar answered Jun 18 '26 08:06

Thomas