DML (Data Manipulation Language) changes the data inside tables: INSERT, UPDATE, DELETE. Every try-it below starts from a fresh copy of the college database, so experiment freely.
INSERT - add rows#
Columns you leave out get their DEFAULT value, or NULL.
INSERT INTO table VALUES (...) without a column list depends on the exact column order of the table - it breaks silently if someone adds or reorders columns. Name the columns in application code.
INSERT ... SELECT#
Insert the result of a query - useful for archiving or building summary tables:
UPDATE - change existing rows#
UPDATE table SET column1 = value1, column2 = value2 WHERE condition;
UPDATE से मौजूदा data बदलते हैं और DELETE से rows हटाते हैं। WHERE लिखना कभी न भूलें - बिना WHERE के UPDATE पूरी table की हर row बदल देगा और DELETE पूरी table खाली कर देगा। Safe तरीका: पहले उसी WHERE के साथ SELECT चलाकर देखें कि कौन-सी rows प्रभावित होंगी।
UPDATE with a subquery#
DELETE - remove rows#
Professional habit: before every UPDATE or DELETE, run a SELECT with the same WHERE clause and check the rows. Many companies also use soft deletes - an is_active or deleted_at column - instead of really deleting data.
Upsert - insert or update#
When a row may already exist, an upsert inserts it or updates the existing one:
This syntax works in SQLite and PostgreSQL. MySQL uses INSERT ... ON DUPLICATE KEY UPDATE, SQL Server and Oracle use MERGE.
Transactions#
A transaction groups several statements into one unit of work: either all of them take effect, or none do. The classic example is a fee transfer: debit one account, credit another - both or neither.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 5000 WHERE id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE id = 2;
COMMIT; -- make it permanent
-- or ROLLBACK; -- undo everything since BEGIN
ACID - what transactions guarantee#
| Property | Meaning |
|---|---|
| Atomicity | all-or-nothing: a failure in the middle undoes the whole transaction |
| Consistency | the database moves from one valid state to another (constraints always hold) |
| Isolation | concurrent transactions do not see each other's half-finished work |
| Durability | once committed, changes survive crashes and power cuts |
SAVEPOINT name and ROLLBACK TO name let you undo just part of a transaction.
Summary#
INSERT INTO t (cols) VALUES (...), several rows at once, orINSERT ... SELECT.UPDATE t SET ... WHERE ...andDELETE FROM t WHERE ...- always check the WHERE first.- Upserts (
ON CONFLICT ... DO UPDATE) insert or update. - Transactions (
BEGIN→COMMIT/ROLLBACK) make multi-step changes all-or-nothing (ACID).