TODAY I LEARNED

ON DUPLICATE KEY UPDATE

When you're doing an INSERT query, you could be trying to insert a row containing a primary key that already exists in the table. Instead of doing a previous query to see if the key exists or not, you could try ON DUPLICATE KEY UPDATE.

INSERT INTO table (
  field1, 
  field2
) 
VALUES (
  "foo", 
  "bar"
) 
ON DUPLICATE KEY UPDATE 
  field1="foo", 
  field2="bar"

Tweet

Learned by kevin-perez on Jul 6, 2021

Discover our latest blog posts
  • #sql
  • view raw
  • permalink
  • 2 likes
previous TIL next TIL
  • Log in
  • ?

    TIL is an open-source project by MagmaLabs that exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any MagmaLaber as well as selected friends of MagmaLabs. We hope you enjoy learning along with us.

    • /wearemagmalabs
  • statistics
  • search
  • Twitter