Skip to content

Modifying Data

Data Manipulation Language (DML) allows you to change the data inside your tables. While SELECT is for reading, INSERT, UPDATE, and DELETE are for writing.

  1. INSERT: Adds new rows to a table.
  2. UPDATE: Modifies existing values in a table.
  3. DELETE: Removes specific rows from a table.
  4. TRUNCATE: Removes all rows from a table (extremely fast).

When running UPDATE or DELETE, the WHERE clause is your only protection. If you omit it, the command applies to every single row in the table.

Missing WHERE
-- DANGER: This makes everyone's salary zero!
UPDATE Employees SET Salary = 0;

You should always specify the columns you are inserting into.

Bulk Insert
INSERT INTO Products (Name, Price)
VALUES ('New Phone', 999.99), ('Old Phone', 499.99);
Batch Update
UPDATE Products
SET Price = Price * 0.9
WHERE Category = 'Electronics';
  • DELETE: A row-by-row operation. It checks constraints, triggers, and logs every single deletion.
  • TRUNCATE: A DDL operation. It simply “de-allocates” the data pages on the disk. It is near-instant even on billions of rows, but it cannot be rolled back in some databases and ignores most triggers.

INSERT INTO Cart (UserID, ProductID, Qty) VALUES (1, 101, 1);

UPDATE Cart SET Qty = Qty + 1 WHERE UserID = 1 AND ProductID = 101;

DELETE FROM Cart WHERE UserID = 1 AND ProductID = 101;

What happens physically when you UPDATE a row?

1. Multi-Version Concurrency Control (MVCC)

Section titled “1. Multi-Version Concurrency Control (MVCC)”

In databases like PostgreSQL, an UPDATE doesn’t actually overwrite the old data. Instead, it:

  • Marks the old row as “dead.”
  • Inserts a completely new version of the row with the updated values. The database later cleans up these dead rows using a process called Vacuum.

Before any change is made to the actual table data on disk, the database writes the change to a Log File (WAL). This ensures that if the power goes out mid-update, the database can “replay” the log to recover the data.

Most tables use an “Identity” column for the Primary Key. When you INSERT, you don’t provide a value; the database generates the next number (1, 2, 3…) automatically.