The UPDATE statement is used to change existing rows in a table. In this lesson, you will see how new rows are added.
The INSERT statement adds a new row into a specified table. To use the INSERT statement you generally specify the data fields and their corresponding values for the row to insert. However, if values for every field are being provided then it is not necessary to specify the data fields. In this case, the values are added to the fields from left to right, beginning with the first field. If values for only some fields are being provided then the data fields are specified, unless the values are to go into the first fields as they appear in the row. The syntax for the INSERT statement is illustrated in the following SlideShow:
Here are two SQL INSERT statements to add items from a food cabinet into a refrigerator table, based on your explanation of the INSERT syntax:
First Form: Without Specifying Column Names
INSERT INTO refrigerator
VALUES ('Milk', 'Dairy', '2024-12-01', 1),
('Eggs', 'Dairy', '2024-11-25', 12),
('Strawberry Jam', 'Condiments', '2025-06-15', 1),
('Yogurt', 'Dairy', '2024-11-30', 1);
Second Form: With Column Names Specified
Assuming the refrigerator table has columns like `item_name`, `category`, `expiration_date`, and `quantity`:
INSERT INTO refrigerator (item_name, category, expiration_date, quantity)
VALUES ('Milk', 'Dairy', '2024-12-01', 1),
('Eggs', 'Dairy', '2024-11-25', 12),
('Strawberry Jam', 'Condiments', '2025-06-15', 1),
('Yogurt', 'Dairy', '2024-11-30', 1);
In these examples:
- item_name: The name of the food item.
- category: The category to which the item belongs.
- expiration_date: The date when the item expires.
- quantity: How much of the item there is.
When using the first form, you must ensure that the values are in the exact order of the columns as they are defined in the table, which can be error-prone if the table structure changes or if you're not certain about the column order. The second form is generally safer and more maintainable as it explicitly names the columns, making the SQL more readable and less prone to errors if the table structure changes.
In the next lesson, removing rows using the DELETE statement will be discussed.