HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

"on duplicate key update" all the non-key fields mentioned in the insert

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
theupdateinsertallnonduplicatefieldsmentionedkey

Problem

How can I update the field values mentioned in the insert portion without listing them again in the on duplicate key update portion?

insert into tablename set keyname = 'keyvalue',
    fieldname = 'fieldvalue'
    . . .
    on duplicate key update
        updatecounter = updatecounter + 1
        fieldname = 'fieldvalue'
        . . .;

Solution

You can use the VALUES(column) function:

insert into tablename set keyname = 'keyvalue',
    fieldname = 'fieldvalue'
    . . .
    on duplicate key update
        updatecounter = updatecounter + 1,
        fieldname = VALUES(fieldname)
        . . .;


While the above method is still valid, it was deprecated in MySQL version 8.0.20 and subject to removal in the future. The new method to do this as explained in MySQL docs: INSERT ... ON DUPLICATE KEY UPDATE Statement is:

insert into tablename set keyname = 'keyvalue',
    fieldname = 'fieldvalue'
    . . .
    AS new        -- adding a table alias for the set
                  -- of values to be on inserted
    on duplicate key update
        updatecounter = updatecounter + 1,  -- refers to existing table value
        fieldname = new.fieldname           -- refers to above set
        . . .;

Code Snippets

insert into tablename set keyname = 'keyvalue',
    fieldname = 'fieldvalue'
    . . .
    on duplicate key update
        updatecounter = updatecounter + 1,
        fieldname = VALUES(fieldname)
        . . .;
insert into tablename set keyname = 'keyvalue',
    fieldname = 'fieldvalue'
    . . .
    AS new        -- adding a table alias for the set
                  -- of values to be on inserted
    on duplicate key update
        updatecounter = updatecounter + 1,  -- refers to existing table value
        fieldname = new.fieldname           -- refers to above set
        . . .;

Context

StackExchange Database Administrators Q#10336, answer score: 3

Revisions (0)

No revisions yet.