The MySQL INSERT
statement is used to add new rows of data into a table. This statement is essential for populating tables with initial data or adding new records to existing tables.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
The INSERT
statement has the following components:
table_name
: The name of the table where the data will be inserted.column1, column2, column3, ...
: The columns in the table where the data will be inserted.value1, value2, value3, ...
: The values to be inserted into the specified columns.Let's look at some examples of the MySQL INSERT
statement:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a table to work with:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
This query creates a table named employees
with columns for id
, first_name
, last_name
, and email
.
Insert a single row into the table:
INSERT INTO employees (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com');
This query inserts a new row into the employees
table. The result will be that the employees
table now contains the new row with the specified values.
Insert multiple rows into the table:
INSERT INTO employees (first_name, last_name, email)
VALUES ('Jane', 'Smith', 'jane.smith@example.com'),
('Jim', 'Brown', 'jim.brown@example.com');
This query inserts multiple rows into the employees
table. The result will be that the employees
table now contains the new rows with the specified values.
To verify that the rows have been inserted, you can select all rows from the table:
SELECT *
FROM employees;
This query retrieves all rows from the employees
table. The result will show the inserted rows.
The MySQL INSERT
statement is a powerful tool for adding new rows of data into a table. Understanding how to use the INSERT
statement is essential for effective data management and manipulation in MySQL.