2. Modifying Your Data: INSERT, UPDATE, and DELETE

 While the SELECT statement is essential for reading data from your database, the real work of data management involves changing it. The three foundational SQL commands for modifying data are INSERT, UPDATE, and DELETE. These are often referred to as Data Manipulation Language (DML) commands.

Let's use our simple sales database with the Customer, Product, and Sales tables to demonstrate how to use these powerful commands.


1. Adding New Data: The INSERT Statement

The INSERT command is used to add new rows (records) into a table.

A. Inserting Values for All Columns

If you provide a value for every column in the table, you can use the simpler syntax. The order of the values must match the order of the columns in the table definition.

  • To retrieve all columns (use the asterisk *):


INSERT INTO Product VALUES (104, 'Wireless Mouse', 25.00, 'Electronics');

  • To 


2. Changing Existing Data: The UPDATE Statement

The UPDATE command is used to modify existing records in a table. It is crucial to use the WHERE clause with UPDATE!

A. Updating a Single Row

To modify a specific item, you use the WHERE clause to target it, often by its primary key.

  • Action: Change the price of the product with ProductID = 101.


    Update Product SET Price=120.0 WHERE ProductID=101;

B. Updating Multiple Rows

You can modify several rows at once using a broader WHERE clause.

  • Action: Give everyone in the 'Houston' a new job title (assuming we had a job title column).


    Update Product SET Price=120.0 WHERE City = 'Huston';



3. Removing Data: The DELETE Statement

The DELETE command is used to remove one or more rows from a table. Like UPDATE, it is almost always paired with a WHERE clause.

A. Deleting a Specific Row

You target the row(s) you want to remove using a unique identifier.

  • Action: Remove the customer with CustomerID = 205.


    Delete from Customer where CustomerID = 205;

B. Deleting Multiple Rows

You can delete a group of records based on a common condition.


  • DELETE FROM Customer where Date < '2024/01/01';

    Action: Remove all sales transactions made before the year 2024.


These three commands (INSERT, UPDATE, and DELETE) are the backbone of data integrity. They allow you to maintain, clean, and evolve your datasets over time.



Comments

Popular Posts