Data Manipulation Language (DML): Mutating Records ✍️
While DDL commands (CREATE, ALTER) define the structure of our database, DML (Data Manipulation Language) commands manage the actual data inside:
INSERT: Add brand new rows of data.UPDATE: Modify existing data in one or more rows.DELETE: Remove specific rows from a table.
Because DML commands modify active production data, mastering their safety patterns is crucial to prevent catastrophic data loss!
1. Inserting Data with INSERT INTO 📥
Pattern A: Inserting with Explicit Column Names (Recommended!)
Always list the column names explicitly. This protects your code from breaking if columns are reordered in the table schema:
INSERT INTO users (username, email, age, role)VALUES ('aarav_s', 'aarav@example.com', 22, 'ADMIN');If a column has an auto-incrementing PRIMARY KEY (like SERIAL or AUTO_INCREMENT) or a DEFAULT value, you can omit it—the DBMS handles it automatically.
Pattern B: Inserting Multiple Rows in a Single Query ⚡
Instead of sending 100 individual network roundtrips to the database, you can insert multiple rows in a single batch statement:
INSERT INTO users (username, email, age)VALUES ('rahul_s', 'rahul@example.com', 24), ('priya_p', 'priya@example.com', 21), ('amit_v', 'amit@example.com', 27);Pattern C: Inserting Data from Another Query (INSERT INTO ... SELECT)
You can populate a table using the output of a SELECT query:
INSERT INTO archived_orders (order_id, user_id, amount)SELECT order_id, user_id, amountFROM ordersWHERE order_date < '2023-01-01';2. Modifying Data with UPDATE 🔄
To change data in existing rows, use the UPDATE statement with SET:
UPDATE usersSET email = 'aarav.new@example.com', age = 23WHERE id = 1;You can also use existing column values in mathematical updates:
-- Give every engineer a 10% salary bump:UPDATE employeesSET salary = salary * 1.10WHERE department = 'Engineering';3. 🚨 The Nightmare Bug: UPDATE Without a WHERE Clause 💥
Look at this innocent-looking query:
-- ⚠️ CATASTROPHIC BUG:UPDATE usersSET is_active = FALSE;What happened?
Because the WHERE clause was omitted, the database engine diligently updated EVERY SINGLE ROW IN THE ENTIRE TABLE! Every user account in your application was just deactivated.
🛡️ Golden Rule of Updating Data:
Always write the
WHEREclause FIRST, or run aSELECTquery with the exact sameWHEREcondition to verify which rows will be affected before executing theUPDATE!
4. Deleting Data with DELETE FROM 🗑️
To remove specific records from a table, use DELETE FROM:
-- Delete a specific inactive user:DELETE FROM usersWHERE id = 4;-- Delete cancelled orders older than 30 days:DELETE FROM ordersWHERE status = 'CANCELLED' AND order_date < CURRENT_DATE - INTERVAL '30 days';🚨 The Companion Nightmare: DELETE Without a WHERE Clause:
-- ⚠️ DISASTER: Wipes out every single row in the table!DELETE FROM users;Just like UPDATE, omitting WHERE from a DELETE deletes all records in the table.
DELETE vs TRUNCATE Comparison:
| Feature | DELETE FROM table; | TRUNCATE TABLE; |
|---|---|---|
| Can use WHERE? | ✅ Yes (WHERE id = 5) | ❌ No (all rows wiped) |
| Speed on 10M rows | 🐢 Slow (logs every row deletion) | ⚡ Instant (deallocates disk pages) |
| Resets auto-increment ID? | ❌ No (next ID continues from max) | ✅ Yes (resets serial sequence to 1) |
| Transaction Rollback | ✅ Easily rolled back in transactions | Dialect-dependent (often DDL auto-commit) |
5. Returning Mutated Data with RETURNING (PostgreSQL / SQLite) 🎁
Often, when you insert a row, you immediately need the newly generated id or timestamp to send back to your frontend API.
Instead of running an immediate second SELECT query, modern SQL engines support the RETURNING clause:
INSERT INTO users (username, email, age)VALUES ('ananya_k', 'ananya@example.com', 20)RETURNING id, created_at;Result:
┌────┬────────────────────────────┐
│ id │ created_at │
├────┼────────────────────────────┤
│ 42 │ 2026-10-17 18:50:00.123456 │
└────┴────────────────────────────┘
You can even use RETURNING with UPDATE or DELETE to see which records were modified or deleted!
6. Introduction to ACID Transactions 🔒
What happens if you are building a banking app where User A transfers ₹1,000 to User B?
This requires two separate DML updates:
- Deduct ₹1,000 from User A:
UPDATE accounts SET balance = balance - 1000 WHERE id = 1; - Add ₹1,000 to User B:
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
What if the server crashes or loses power between step 1 and step 2?
User A lost ₹1,000, but User B never received it! ₹1,000 vanished into thin air.
To prevent this nightmare, SQL provides Transactions:
BEGIN TRANSACTION; -- Start the atomic boundaryUPDATE accounts SET balance = balance - 1000 WHERE id = 1;UPDATE accounts SET balance = balance + 1000 WHERE id = 2;COMMIT; -- Permanently save ONLY if BOTH statements succeeded!If anything fails in between, you execute ROLLBACK;, and the database reverts to its exact state prior to the transaction as if nothing happened!
The ACID Guarantee:
- A (Atomicity): All-or-nothing (either all operations succeed, or none do).
- C (Consistency): All data integrity constraints are strictly preserved.
- I (Isolation): Concurrent transactions cannot interfere with each other.
- D (Durability): Once committed, data is permanently written to non-volatile disk.
Flashcard Checkpoint 🎴
What happens if you execute an UPDATE or DELETE statement without a WHERE clause?
What does the 'A' (Atomicity) in ACID transactions mean?