Data manipulation
✅ What is Data Manipulation?
Data Manipulation refers to adding, updating, deleting, and retrieving data from database tables.
In SQL, Data Manipulation Language (DML) provides commands that allow users to manage the data stored in tables.
🎯 Key SQL DML Commands:
SELECT
Retrieve data from one or more tables.
INSERT
Add new records into a table.
UPDATE
Modify existing records in a table.
DELETE
Remove records from a table.
📊 Detailed Explanation with Examples:
1. SELECT - Retrieve Data
Use SELECT to query data from tables.
Retrieves first and last names of all employees.
✅ Add conditions:
Fetch employees in the IT department.
2. INSERT - Add New Data
Use INSERT INTO to add new records.
Adds a new employee to the employees table.
🚨 Note: Make sure to respect data types and constraints like NOT NULL or UNIQUE when inserting.
3. UPDATE - Modify Existing Data
Use UPDATE to change existing records.
Updates salary for employee with
ID = 10
.
⚠️ Warning: Without WHERE
, it will update all rows in the table. Always use WHERE carefully.
4. DELETE - Remove Data
Use DELETE to remove rows from a table.
Deletes employee record with
ID = 10
.
⚠️ Warning: Like UPDATE, avoid running DELETE without a WHERE
clause unless you intend to delete all records.
⚙️ Combined Example (Full Data Manipulation Workflow):
📦 Use Cases of Data Manipulation:
Add new employee
INSERT
Update salary for specific department
UPDATE
Delete terminated employee record
DELETE
List all employees in specific department
SELECT
with WHERE
🏷️ Common Clauses with DML Commands:
WHERE
Filter rows for action
DELETE FROM employees WHERE id = 10;
ORDER BY
Sort the output
SELECT * FROM employees ORDER BY salary;
LIMIT
Limit number of rows returned
SELECT * FROM employees LIMIT 5;
SET
Define column updates in UPDATE
UPDATE employees SET salary = 60000;
✅ Good Practices for Data Manipulation:
Always use
WHERE
withUPDATE
andDELETE
to avoid affecting unintended rows.Test queries with
SELECT
before running destructive actions.Use transactions (
BEGIN
,COMMIT
,ROLLBACK
) for critical operations to ensure safe execution.Backup important tables before large-scale updates/deletes.
Check constraints (like foreign keys, NOT NULL) to avoid insertion errors.
⚙️ Transactions for Safe Data Manipulation:
🔑 Summary of DML Commands:
SELECT
SELECT col1, col2 FROM table WHERE condition;
INSERT
INSERT INTO table (col1, col2) VALUES (val1, val2);
UPDATE
UPDATE table SET col1 = val1 WHERE condition;
DELETE
DELETE FROM table WHERE condition;
Last updated