All Things Techie With Huge, Unstructured, Intuitive Leaps

mysql REPLACE INTO Keyword

I don't bother with the fancy stuff, but I have a coder that works for me who does.  I usually work and write from first principles so that those that follow me can fix my code easily.  However there are convenience methods, and one of my coders recently used the mysql REPLACE INTO keyword, so I thought that I would document it.

Suppose that you wanted to replace an entire row of data while keeping the same primary key identifier.  The way that you would do this normally would be like this:

DELETE FROM myTable WHERE myPrimaryKey = 1;
INSERT INTO myTable(
  myPrimaryKey,
  myColumn1,
  myColumn2
) VALUES (
  1,
  'value1',
  'value2'
);

To do the same thing as above, the REPLACE INTO convenience method works like this:

REPLACE INTO myTable (
  myPrimaryKey,
  myColumn1,
  myColumn2
) VALUES (
  1,
  'value1',
  'value2'
);

Hopes this helps someone.

No comments:

Post a Comment