top of page
Writer's pictureSheba Alice Prathab

A Complete Guide to SQL Operations: Inserting, Updating, Deleting - Rows, Dropping and Truncating -Tables


In the world of databases, SQL (Structured Query Language) is essential for performing various operations that allow users to manage their data effectively. These operations include inserting new records, updating existing records, deleting data, and managing tables. To make these concepts more relatable, we will draw comparisons with real-life scenarios, focusing on an example table called AmazonOrders. It's important to note that this example is hypothetical and serves solely to enhance our understanding of SQL operations, as actual implementations of Amazon's databases may differ significantly.


Table Structure: AmazonOrders


Let’s start with the structure of the AmazonOrders table, which will store information about customer orders.


CREATE TABLE AmazonOrders ( 
order_id INT PRIMARY KEY, 
customer_name VARCHAR(100) NOT NULL, 
product_name VARCHAR(100) NOT NULL, 
quantity INT, 
order_date DATE, 
total_amount DECIMAL(10, 2) DEFAULT 0.00, 
delivery_status VARCHAR(20) DEFAULT 'Pending',
delivery_address VARCHAR(255) DEFAULT '<<Enter your Home Address>>',  
delivery_notes VARCHAR(255) 
);

This table contains the following columns:

  1. order_id: A unique identifier for each order.

  2. customer_name: The name of the customer placing the order.

  3. product_name: The name of the product being ordered.

  4. quantity: The number of units ordered.

  5. order_date: The date the order was placed.

  6. total_amount: The total price of the order.

  7. delivery_status: The current status of the order (e.g., Pending, Shipped, Delivered).


Inserting Records into the Table


Imagine you're a customer placing multiple orders on Amazon. Each time you place an order, a new row is inserted for every product into Amazon's order database, capturing the details of your transaction. For example, if you buy 2 laptops, 2 pens, and 1 lipstick, depending on how the database and business logic handle order details and aggregation, the system can either:


  • Insert multiple entries: one row for each individual item (resulting in 5 separate rows — 2 rows for laptops, 2 rows for pens, and 1 row for lipstick).


INSERT INTO AmazonOrders (
order_id, customer_name, product_name, quantity, order_date, total_amount, delivery_status) VALUES 
(106, 'Jane Doe', 'Laptop', 1, '2024-10-08', 1200.00, 'Pending'), 
(106, 'Jane Doe', 'Laptop', 1, '2024-10-08', 1200.00, 'Pending'), 
(106, 'Jane Doe', 'Pen', 1, '2024-10-08', 2.00, 'Pending'), 
(106, 'Jane Doe', 'Pen', 1, '2024-10-08', 2.00, 'Pending'), 
(106, 'Jane Doe', 'Lipstick', 1, '2024-10-08', 15.00, 'Pending');

  • Insert a single entry per product: summing the quantities into one row for each product (e.g., 1 row for laptops with quantity 2, 1 row for pens with quantity 2, and 1 row for lipstick with quantity 1).


INSERT INTO AmazonOrders (order_id, customer_name, product_name, quantity, order_date, total_amount, delivery_status) VALUES 
(106, 'Jane Doe', 'Laptop', 2, '2024-10-08', 2400.00, 'Pending'), 
(106, 'Jane Doe', 'Pen', 2, '2024-10-08', 4.00, 'Pending'), 
(106, 'Jane Doe', 'Lipstick', 1, '2024-10-08', 15.00, 'Shipped');

Explanation


  • The INSERT INTO statement specifies the target table and the columns where values will be inserted. It's crucial to match the order of the columns with their respective values.


  • The VALUES clause contains the data to be inserted, with each value corresponding to the respective column. Values must be of compatible data types (e.g., strings in single quotes, numbers without quotes).


  • Multiple Rows Insertion: You can insert multiple rows in a single INSERT statement by separating sets of values with commas, ensuring each set of values matches the specified columns.


Key Considerations:


  1. Single Quotes for Values: In SQL, single quotes (' ') are used to denote string values such as names, dates, and text-based columns. For example, 'Jane Doe', 'Shipped'.


  2. Double Quotes for Identifiers: Double quotes (" ") are typically used for object identifiers, such as column names or table names, especially when they contain special characters or reserved words. However, most SQL implementations prefer that column names are not enclosed unless necessary.


  3. Correct Information: Just as you must provide accurate details when placing an order, ensure the columns and values in your INSERT statement are correct.


  4. Defaults: If you skip certain columns that have default values (like delivery_status), the database will use these defaults, similar to a store automatically assigning the order status to "Pending."


  5. NULL Values: If any column is not specified and does not have a default value, it will be set to NULL. Think of this as forgetting to specify something in your order, resulting in a blank space on your invoice.



Updating Records in the Table


Imagine you are a customer who wants to modify an existing order on Amazon. For instance, you might want to update the delivery address or add notes for the driver. This action requires executing an UPDATE statement in the database to reflect the changes.


When you update the delivery address and add notes for the driver for an order with order_id 106, the SQL code generated in the background would look something like this:


UPDATE AmazonOrders 
SET delivery_address = '123 New Street, Springfield, IL', 
delivery_notes = 'Leave at the front door' 
WHERE order_id = 106;

Explanation


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


  • SET Clause: This clause specifies the columns you want to update and their new values. In this case, we are updating the delivery_address and adding notes to delivery_notes.


  • WHERE Clause: This condition ensures that only the record with order_id 106 is updated. Without this clause, all records in the AmazonOrders table would be modified, which is not desired.


Key Considerations


  1. Accurate Conditions: Make sure your WHERE clause accurately identifies the record(s) to be updated. Failing to specify the condition correctly may lead to unintended updates across multiple rows.

  2. Single Quotes for Values: Use single quotes (' ') for string values being set in the UPDATE statement, such as the new address and delivery notes. For example, '123 New Street, Springfield, IL'.


  3. Data Type Compatibility: Ensure that the values you are inserting in the UPDATE statement are compatible with the column data types in the database. For instance, setting a string value in an integer field would lead to an error.



Deleting Records from the Table


Imagine you are a customer who wants to remove a stored address from your Amazon profile because you’ve changed to a new address and no longer want the old one linked.


So, When you remove a stored address from your Amazon profile, the database executes a DELETE query to remove the corresponding row from the UserAddresses table. Given that the address_id is auto-generated for each address, the SQL command would typically look like this:


DELETE FROM UserAddresses 
WHERE address = '12345 New Street, Springfield, IL' 
AND address_id = 1;

Explanation


  1. DELETE Statement: The DELETE statement is used to remove existing records from a table.


  2. WHERE Clause: This clause specifies the conditions that must be met for the deletion to occur. In this case, you are checking both the address and the address id to ensure that only the specific address you want to delete is removed.


Key Considerations


  • Accurate Conditions: Ensure your WHERE clause accurately identifies the record to be deleted. If the conditions are not precise, unintended records may be deleted.


  • Single Quotes for Values: Use single quotes (' ') for string values being set in the DELETE statement, such as the address you want to remove.



Dropping a Table in the Database


Imagine you are a customer who wants to completely remove a custom wish list from your Amazon profile. This wish list may contain various items you've added over time.


When you delete a custom wish list, a DROP query is executed to permanently remove the entire table from the database. Assuming the table is named CustomWishList, the SQL command would look like this:


DROP TABLE CustomWishList;

Explanation


The DROP statement is used to completely remove a database object, such as a table, from the database.


Key Considerations


  • Permanent Removal: Using the DROP statement will permanently delete the entire table, including all data, structure, indexes, and any associated constraints. Once dropped, this action cannot be undone.


  • No WHERE Clause: Unlike the DELETE statement, the DROP statement does not require a WHERE clause because it removes the entire table without conditions. This means you will lose all the data related to that wish list.



Truncating a Table in the Database


Imagine you are a customer on Amazon who eagerly awaits special promotions for festive occasions like Christmas or Black Friday. You take advantage of various discounts and offers that Amazon provides during these special days. However, once the promotions end, Amazon needs to manage the backend data efficiently.


To clear out all the expired promotional offers from the PromotionalOffers table (assuming the table name) after the holiday season ends, Amazon can execute a TRUNCATE query. This quickly removes all records while keeping the table structure intact, ready for the next promotional event. The SQL code for this action would look like the following:


TRUNCATE TABLE PromotionalOffers;

Explanation


  • TRUNCATE Statement: The TRUNCATE statement is used to remove all records from a table quickly without logging individual deletions.


  • Table Structure Retained: Unlike DROP, which removes the entire table and its structure, TRUNCATE retains the table's structure, making it easy to reuse for future promotions.


Key Considerations


  • Cannot Use WHERE Clause: The TRUNCATE statement does not permit a WHERE clause, meaning it will remove all records unconditionally, which is useful for bulk deletion.


  • Cannot Rollback: Once a table is truncated, the action cannot be rolled back in most database systems. This requires careful consideration to ensure that all data is ready to be permanently removed.



As you continue your journey into SQL, remember the importance of accuracy in your queries and the implications of your actions on the database. With practice, these concepts will become easy to grasp, empowering you to manipulate and manage data confidently. Whether you're inserting new orders, updating customer information, or performing deletions, mastering these SQL operations is a vital step toward becoming proficient in database management.


Happy querying!

36 views
bottom of page