Basic Data Insertion
In this step, we'll learn how to insert data into MySQL tables using the INSERT statement. We'll start with simple single-row insertions and then move on to multiple-row insertions.
First, let's connect to MySQL:
sudo mysql -u root
Once connected, select the store database:
USE store;
Single Row Insertion
Let's start by inserting a single product into our products table:
INSERT INTO products (name, price, description)
VALUES ('Coffee Maker', 49.99, 'A 12-cup drip coffee maker with programmable timer');
Let's break down this command:
INSERT INTO products
: Specifies the table we're inserting into
(name, price, description)
: Lists the columns we're providing values for
VALUES (...)
: Specifies the actual values to insert
Note that we didn't include:
id
: It's auto-incrementing, so MySQL handles it automatically
created_at
: It has a default value of the current timestamp
To verify our insertion, we can select the data:
SELECT * FROM products;
You should see output like this:
+----+--------------+--------+----------------------------------------------------+---------------------+
| id | name | price | description | created_at |
+----+--------------+--------+----------------------------------------------------+---------------------+
| 1 | Coffee Maker | 49.99 | A 12-cup drip coffee maker with programmable timer | 2024-11-07 09:12:06 |
+----+--------------+--------+----------------------------------------------------+---------------------+
Multiple Row Insertion
Now, let's insert multiple products at once. This is more efficient than inserting rows one at a time:
INSERT INTO products (name, price, description) VALUES
('Toaster', 29.99, '2-slice toaster with multiple browning settings'),
('Blender', 79.99, 'High-speed blender for smoothies and soups'),
('Microwave', 129.99, '1000-watt microwave with digital controls');
This command follows the same structure as single-row insertion but includes multiple value sets separated by commas.
Let's verify our insertions:
SELECT * FROM products;
You should see output like this:
+----+--------------+--------+----------------------------------------------------+---------------------+
| id | name | price | description | created_at |
+----+--------------+--------+----------------------------------------------------+---------------------+
| 1 | Coffee Maker | 49.99 | A 12-cup drip coffee maker with programmable timer | 2024-11-07 09:12:06 |
| 2 | Toaster | 29.99 | 2-slice toaster with multiple browning settings | 2024-11-07 09:12:16 |
| 3 | Blender | 79.99 | High-speed blender for smoothies and soups | 2024-11-07 09:12:16 |
| 4 | Microwave | 129.99 | 1000-watt microwave with digital controls | 2024-11-07 09:12:16 |
+----+--------------+--------+----------------------------------------------------+---------------------+