Data Manipulation Language (DML) in SQL
DML (Data Manipulation Language) in SQL is used to manage and modify data stored in databases. It includes essential commands like `INSERT`, `UPDATE`, `DELETE`, and `SELECT`.
DML Commands in SQL
DML commands allow you to interact with data stored in database tables:
- INSERT: Adds new records to a table.
- UPDATE: Modifies data of existing records in a table.
- DELETE: Removes specific records from a table.
- SELECT: Retrieves data from one or more tables, allowing you to filter and sort the results.
Next, we'll explain each of these commands with practical examples.
INSERT: Adding Data to a Table
The `INSERT` command is used to add new records to a table. For example, to add a new employee to the `employees` table:
INSERT INTO employees (name, position, salary)
VALUES ('Juan Pérez', 'Developer', 60000);
UPDATE: Modifying Existing Records
The `UPDATE` command is used to modify data in existing records. For example, to update an employee's salary:
UPDATE employees
SET salary = 65000
WHERE name = 'Juan Pérez';
This command modifies "Juan Pérez"'s salary to 65,000.
DELETE: Removing Records
To remove records from a table, use the `DELETE` command. For example, to remove an employee's record:
DELETE FROM employees
WHERE name = 'Juan Pérez';
This command deletes "Juan Pérez"'s record from the `employees` table.
Using WHERE with DML
The `WHERE` clause is very important when using `UPDATE` and `DELETE` to avoid accidentally affecting all records in a table. It's always recommended to use `WHERE` to specify the condition:
-- Update salary only for developers
UPDATE employees
SET salary = salary + 5000
WHERE position = 'Developer';
-- Delete employees without an assigned position
DELETE FROM employees
WHERE position IS NULL;