Database Management System (DBMS) / SQL(STRUCTURED QUERY LANGUAGE)

REPLACE vs INSERT

πŸ“Œ Base Table (used for all examples)

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT,
    grade VARCHAR(2),
    section CHAR(1)
);

INSERT INTO students (id, name, age, grade, section) VALUES
(1, 'Anya', 17, 'A', 'A'),
(2, 'Raj', 18, 'B', 'B');

We will use this same table for all commands below.


βž• INSERT β€” Add New Rows Only

The INSERT command adds new rows.

❗ If the primary key already exists β†’ it throws an error.

Example

INSERT INTO students (id, name, age, grade, section)
VALUES (3, 'Swastika', 17, 'B', 'C');

βœ”οΈ Adds a new third row
❌ Fails if id = 3 already exists


πŸ” REPLACE β€” Insert or Replace Row

REPLACE will:

➑️ insert if the primary key is new
➑️ delete + insert if primary key already exists

Example

REPLACE INTO students (id, name, age, grade, section)
VALUES (1, 'Swasti', 17, 'A', 'C');

βœ”οΈ If id = 1 exists β†’ old row removed
βœ”οΈ new row inserted

⚠️ ALL old row values get wiped


⚠️ Important Notes

  • REPLACE is NOT like UPDATE

  • It is delete + new insert

  • Missing columns = old values lost

  • Auto-increment values can skip


βœ… Summary Table

Feature

INSERT

REPLACE

Adds new row

βœ…

βœ…

Fails if key exists

βœ…

❌

Deletes old row

❌

βœ…

Updates values safely

❌

❌

Risk level

Low

High


🧠 Which to Use?

βœ”οΈ Use INSERT when adding new records
βœ”οΈ Use REPLACE only when overwriting is intended
βœ”οΈ For safe overwrite β†’ use this (MySQL):

INSERT INTO students (id, name, age, grade, section)
VALUES (1, 'Anya', 17, 'A', 'A')
ON DUPLICATE KEY UPDATE
name='Anya', age=17, grade='A', section='A';

βœ”οΈ Updates only given fields
βœ”οΈ Doesn’t delete entire row