REPLACE

This lesson discusses the REPLACE clause.

We'll cover the following

REPLACE

REPLACE is much like the INSERT statement with one key difference: we can’t insert a row if a table already contains a row with the same primary key. However, REPLACE allows us the convenience of adding a row with the same primary key as an existing row in the table. Under the hood, REPLACE deletes the row and then adds the new row thereby maintaining the primary key constraint at all times. Sure, we can also use the UPDATE clause to achieve the same effect. However, REPLACE can be useful in automated scripts where it is not known ahead of time if a particular table already contains a particular primary key. If it doesn’t, the replacement behaves like an insertion, otherwise, it deletes and writes in the new row with the same primary key.

REPLACE INTO table (col1, col2, … coln)

VALUES (val1, val2, … valn)

WHERE <condition>

Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy and paste the command ./DataJek/Lessons/38lesson.sh and wait for the MySQL prompt to start-up.

Get hands-on with 1400+ tech skills courses.