Filling the Shelves (DML)

Filling the Shelves (DML)
In the previous lesson, we used DDL to build the empty shelves. Now, it's time to open the store. We need to put the bread out, update prices when there's inflation, and throw away expired milk.
To do all this, we use DML (Data Manipulation Language). If DDL were the hammers and drills, DML are the delivery trucks and our own hands organizing the store.
1. Putting Products In: INSERT
The delivery truck is here! Doña Pepa just received Whole Wheat Bread and Milk. To put this information into our Products table, we use the INSERT command.
sql-- Adding Whole Wheat Bread INSERT INTO Products (name, price, stock) VALUES ('Whole Wheat Bread', 1.50, 50); -- Adding Milk INSERT INTO Products (name, price, stock) VALUES ('Whole Milk', 0.90, 30);
(Note: Did you notice we didn't include id_product? Because we set it to AUTO_INCREMENT when we built the shelf, the database will automatically assign 1 to the Bread and 2 to the Milk).
Also, our first customer just walked in, let's register him:
sqlINSERT INTO Customers (name, phone) VALUES ('Juan García', '555-1234');
2. Changing Price Tags: UPDATE
Oh no! Inflation has hit and Doña Pepa needs to raise the price of Milk from $0.90 to $1.20.
To update data, we use UPDATE. But BE CAREFUL! Imagine Doña Pepa tells her assistant: "Raise the price to $1.20". The assistant might go and put a $1.20 price tag on EVERYTHING in the store. To avoid this, we must specify WHICH product will get its price changed using WHERE.
sqlUPDATE Products SET price = 1.20 WHERE id_product = 2; -- 2 is the ID for Milk
🚨 DANGER - The UPDATE without WHERE Meme: If you ever forget to put the
WHEREclause, you will change the price of EVERY product in the store to $1.20. It is the most famous rookie mistake in the database world. Always use WHERE!
3. Throwing Away the Expired: DELETE
Suppose Doña Pepa decided to stop selling Whole Wheat Bread because it expires too quickly. To remove a record from the box, we use DELETE.
Just like with UPDATE, we must always use WHERE.
sqlDELETE FROM Products WHERE id_product = 1; -- 1 is the ID for Bread
(Same warning: A DELETE FROM Products; without a WHERE would empty the entire shelf).
4. Registering a Sale (Using the Foreign Key)
Juan (Customer 1) just bought Milk (Product 2). Let's write down this sale in our "digital notebook" (the Sales table).
Remember that in the Keys lesson, we learned that we don't write names, only IDs.
sqlINSERT INTO Sales (id_customer, id_product) VALUES (1, 2);
And we're done! We just created a connection bridge. The sale knows exactly who bought and what they bought, taking up the least amount of space possible.
In the next lesson, we will look at some important theory: What happens if we try to delete a customer who already has registered sales? We will organize the chaos with Normalization!
