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.
Definition: The DML Core
Section titled “Definition: The DML Core”INSERT: Adds new rows to a table.UPDATE: Modifies existing values in a table.DELETE: Removes specific rows from a table.TRUNCATE: Removes all rows from a table (extremely fast).
Context: The Dangerous WHERE
Section titled “Context: The Dangerous WHERE”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.
-- DANGER: This makes everyone's salary zero!UPDATE Employees SET Salary = 0;Detailed Explanation: Syntax
Section titled “Detailed Explanation: Syntax”1. INSERT
Section titled “1. INSERT”You should always specify the columns you are inserting into.
INSERT INTO Products (Name, Price)VALUES ('New Phone', 999.99), ('Old Phone', 499.99);2. UPDATE
Section titled “2. UPDATE”UPDATE ProductsSET Price = Price * 0.9WHERE Category = 'Electronics';3. DELETE vs. TRUNCATE
Section titled “3. DELETE vs. TRUNCATE”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.
Example: Managing a Shopping Cart
Section titled “Example: Managing a Shopping Cart”Step 1: Add an item
Section titled “Step 1: Add an item”INSERT INTO Cart (UserID, ProductID, Qty) VALUES (1, 101, 1);
Step 2: Increase quantity
Section titled “Step 2: Increase quantity”UPDATE Cart SET Qty = Qty + 1 WHERE UserID = 1 AND ProductID = 101;
Step 3: Remove item
Section titled “Step 3: Remove item”DELETE FROM Cart WHERE UserID = 1 AND ProductID = 101;
Under the Hood: MVCC and WAL
Section titled “Under the Hood: MVCC and WAL”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.
2. Write-Ahead Logging (WAL)
Section titled “2. Write-Ahead Logging (WAL)”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.
3. Identity and Auto-Increment
Section titled “3. Identity and Auto-Increment”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.