Inserting, Updating & Deleting Data in SQL (DML)

Introduction

Data Manipulation Language (DML) in SQL is used to manage data within tables. The three most important DML commands are:

  • INSERT INTO – Adds new records.

  • UPDATE – Modifies existing records.

  • DELETE – Removes records from a table.


1. Inserting Data (INSERT INTO)

The INSERT INTO statement is used to add new rows into a table.

Syntax:

sqlCopyEditINSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Example:

Consider a table named employees with columns: id, name, position, and salary.

sqlCopyEditINSERT INTO employees (id, name, position, salary)
VALUES (1, 'John Doe', 'Software Engineer', 70000);

If inserting values into all columns, you can skip the column names:

sqlCopyEditINSERT INTO employees
VALUES (2, 'Jane Smith', 'Data Analyst', 65000);

2. Updating Data (UPDATE)

The UPDATE statement is used to modify existing records in a table.

Syntax:

sqlCopyEditUPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Always use a WHERE condition to avoid updating all rows in the table.

Example:

Updating an employee’s salary:

sqlCopyEditUPDATE employees
SET salary = 75000
WHERE id = 1;

Updating multiple columns:

sqlCopyEditUPDATE employees
SET position = 'Senior Data Analyst', salary = 80000
WHERE name = 'Jane Smith';

3. Deleting Data (DELETE)

The DELETE statement removes records from a table.

Syntax:

sqlCopyEditDELETE FROM table_name
WHERE condition;

If you omit the WHERE clause, all records in the table will be deleted!

Example:

Deleting an employee record:

sqlCopyEditDELETE FROM employees
WHERE id = 2;

Deleting all employees with a specific position:

sqlCopyEditDELETE FROM employees
WHERE position = 'Intern';

4. Deleting All Data (TRUNCATE) vs. DELETE

  • DELETE removes specific rows based on a condition.

  • TRUNCATE TABLE removes all rows from a table but keeps the table structure.

sqlCopyEditTRUNCATE TABLE employees;

TRUNCATE is faster than DELETE but cannot be rolled back in some databases.


Conclusion

  • Use INSERT INTO to add data.

  • Use UPDATE to modify existing data (always use WHERE).

  • Use DELETE to remove specific records.

  • Use TRUNCATE to remove all records quickly.