Concept Flow - REPLACE INTO behavior
Start REPLACE INTO
Check if row with same PRIMARY or UNIQUE key exists
Delete old
End REPLACE INTO
REPLACE INTO first checks if a row with the same key exists; if yes, it deletes it, then inserts the new row.
REPLACE INTO behavior (id, action) VALUES (1, 'run'); REPLACE INTO behavior (id, action) VALUES (2, 'jump'); REPLACE INTO behavior (id, action) VALUES (1, 'walk');
| Step | Query Executed | Check Existing Row | Action Taken | Table State After |
|---|---|---|---|---|
| 1 | REPLACE INTO behavior (id, action) VALUES (1, 'run') | No row with id=1 | Insert new row (id=1, action='run') | [{id:1, action:'run'}] |
| 2 | REPLACE INTO behavior (id, action) VALUES (2, 'jump') | No row with id=2 | Insert new row (id=2, action='jump') | [{id:1, action:'run'}, {id:2, action:'jump'}] |
| 3 | REPLACE INTO behavior (id, action) VALUES (1, 'walk') | Row with id=1 exists | Delete old row id=1, Insert new row (id=1, action='walk') | [{id:1, action:'walk'}, {id:2, action:'jump'}] |
| Table 'behavior' | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| Rows | [] | [{id:1, action:'run'}] | [{id:1, action:'run'}, {id:2, action:'jump'}] | [{id:1, action:'walk'}, {id:2, action:'jump'}] |
REPLACE INTO syntax: REPLACE INTO table (columns) VALUES (values); Behavior: - Checks for existing row with same PRIMARY/UNIQUE key - If exists, deletes old row - Inserts new row Use to insert or update rows in one command.