Modifying Data in SQL

Modifying Data in SQL – Insert, Update, and Delete Records Safely

In the previous blogs, we learned how to retrieve, filter, summarize, and join data. But databases aren’t just for reading – they’re also for modifying data. In this blog, we’ll explore how to safely insert, update, and delete records in SQL, while minimizing risks of mistakes.

1. Inserting Data with INSERT

The INSERT statement adds new records to a table.

Example: Adding a New Employee

INSERT INTO employees (first_name, last_name, department_id, salary)
VALUES ('Alice', 'Johnson', 2, 60000);
  • Adds a new employee named Alice in department 2 with a salary of 60,000.

  • Column order matters – values must match the specified columns.

Tip:

You can insert multiple rows in a single query:

INSERT INTO employees (first_name, last_name, department_id, salary)
VALUES
('Bob', 'Lee', 1, 55000),
('Clara', 'Ng', 3, 70000);

2. Updating Data with UPDATE

The UPDATE statement modifies existing records.

Always use a WHERE clause to avoid updating all rows accidentally.

Example: Give a Raise to a Specific Employee

UPDATE employees
SET salary = 65000
WHERE first_name = 'Alice' AND last_name = 'Johnson';
  • Updates only Alice Johnson’s salary.

Updating Multiple Rows

UPDATE employees
SET salary = salary * 1.10
WHERE department_id = 2;
  • Gives a 10% raise to all employees in department 2.

ELETE statement removes records from a table.

Like UPDATE, always use WHERE to avoid deleting everything.

Example: Remove an Employee

DELETE FROM employees
WHERE first_name = 'Bob' AND last_name = 'Lee';
  • Deletes Bob Lee from the table.

Deleting Multiple Rows

DELETE FROM employees
WHERE department_id = 3;
  • Deletes all employees in department 3.

4. Using Transactions for Safety

A transaction ensures that multiple operations are completed safely.

If something goes wrong, you can rollback changes.

BEGIN;

UPDATE employees
SET salary = salary * 1.10
WHERE department_id = 2;

DELETE FROM employees
WHERE department_id = 3;

COMMIT; -- Save changes
  • Use ROLLBACK; instead of COMMIT; if you want to cancel changes.

  • Transactions are essential in production databases to prevent accidental data loss.

Best Practices

  • Always backup data before bulk updates or deletes.

  • Use WHERE clauses carefully.

  • Prefer transactions for multiple operations.

  • Test queries on small datasets first.

Modifying data in SQL is powerful but requires caution.

With INSERT, UPDATE, and DELETE along with transactions, you can:

  • Add new records safely.

  • Update existing data efficiently.

  • Remove unwanted data without mistakes.


Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling