DML - Managing Retail Data
Advanced INSERT, UPDATE, and DELETE
In a global retail operation, data is never static. Every second, inventory levels fluctuate, prices are adjusted for promotions, and outdated records are purged. This is the realm of Data Manipulation Language (DML).
While basic inserts are simple, professional database engineers must handle complexity: How do we update prices for thousands of items at once? How do we handle duplicate entries without crashing the system? This chapter covers the advanced "Actions" that keep the retail engine running.
The Power of Bulk Operations
Efficiency is critical in high-volume retail. When seeding a new store with 10,000 products, sending 10,000 INSERT commands would be slow and resource-heavy. SQL allows us to insert multiple rows in a single statement, drastically reducing network overhead.
Furthermore, the ON CONFLICT (Upsert) clause allows us to decide what happens if a record already exists. Instead of an error, we can choose to update the existing record, ensuring our inventory levels stay accurate without duplicates.
INSERT INTO staff (id, name, role)VALUES (101, 'Alice', 'Manager'), (102, 'Bob', 'Clerk')ON CONFLICT (id) DO NOTHING;Dynamic Updates with Joins
Often, the data you want to change depends on information in another table. For example, you might want to increase the price of all items supplied by "GlobalVogue Corp".
In PostgreSQL, you can use the FROM clause in an UPDATE statement to "Join" tables. This allows for highly targeted mass-updates based on complex business rules across your entire schema.
UPDATE pricesSET amount = amount * 1.05FROM suppliersWHERE prices.supplier_id = suppliers.idAND suppliers.rating > 4.5;Precision Deletion & Purging
The DELETE command must be used with extreme caution. In a retail database, we rarely delete "everything". Instead, we use precise WHERE clauses to remove temporary session data, cancelled orders, or expired promotional codes.
Pro Tip: Always run a SELECT with the same WHERE clause before running a DELETE to verify exactly which rows will be removed!
DELETE FROM promo_codesWHERE expiry_date < '2025-01-01'AND usage_count = 0;Practice Questions
Question 1
Which clause allows an INSERT to perform an 'Upsert' (Update if exists)?
Question 2
What is a major advantage of a multi-row INSERT over multiple single-row INSERTS?
Question 3
What happens if you omit the WHERE clause in a DELETE statement?
Question 4
In PostgreSQL, which keyword allows you to bring in data from another table during an UPDATE?
Question 5
What is the result of using 'ON CONFLICT DO NOTHING'?