MySQL INSERT Row(s) Statement


MySQL INSERT ROW(s) Statement

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.


Syntax

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.

Example MySQL INSERT ROW(s) Statement

Let's look at some examples of the MySQL INSERT statement:

Step 1: Using the Database

USE mydatabase;

This query sets the context to the database named mydatabase.

MySQL USE DATABASE

Step 2: Creating a Table

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.

MySQL CREATE TABLE

Step 3: Inserting a Single Row

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.

MySQL INSERT ROW

Step 4: Inserting Multiple Rows

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.

MySQL INSERT MULTIPLE ROWS

Step 5: Verifying the Inserted Rows

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.

MySQL SELECT FROM TABLE

Conclusion

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.