The Wayback Machine - https://web.archive.org/web/20240826062937/https://www.geeksforgeeks.org/mysql-insert-multiple-rows/
Open In App

MySQL Insert Multiple Rows

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

MySQL is an open-source Relational Database Management System that stores data in rows and columns. MySQL is designed to be platform–independent, which means it can run on various operating systems, including Windows, Linux, macOS, and more. MySQL is scalable and can handle databases of varying sizes. It is suitable for small-scale applications as well as large-scale applications.

In this article, we will understand How to Insert Multiple Rows with different approaches and so on. Inserting multiple rows in a table reduces the number of queries which is efficient for the memory.

Here we will use different methods such as INSERT INTO VALUES, INSERT INTO SELECT, LOAD DATA INFIL, and Batch Inserts.

Creating a Table and Inserting Multiple Rows

Step 1: Creating a Table

We can create a table by using the “Create Table” Statement.

Syntax:

CREATE TABLE table_name 
(
column1 datatype,
column2 datatype,
...
PRIMARY KEY (one_or_more_columns)
);

Example 1: Creating a Table Using “CREATE TABLE” Statement

Query:

CREATE TABLE students 
(
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);

Method 1: Using INSERT INTO VALUES

By using “INSERT INTO” statement we can insert multiple rows into the table in which we can provide multiple values in the VALUES clause and the values will be inserted.

All we have to do is use the INSERT INTO command with our table name and make our desired column, then enter our values according to the columns given.

Syntax:

INSERT INTO your_table_name (column1, column2, column3)
VALUES
(value1_row1, value2_row1, value3_row1),
(value1_row2, value2_row2, value3_row2),
...
(value1_rowN, value2_rowN, value3_rowN);

Example 1: Inserting Multiple Rows in MySQL

Query:

Let’s insert some data into the students table.

INSERT INTO students (StudentID, FirstName, LastName)
VALUES
(1, 'Prakhar', 'Awasthi'),
(2, 'Manvi', 'Chaturvedi'),
(3, 'Badal', 'Mishra');

Output:

studentsTable

Output

Explanation: We have inserted records successfully into the students table.

Example 2

Query:

Let’s insert some data into the class table.

INSERT INTO class (StudentID, StudentName, Address)
VALUES
(21, 'Shagun Kaushal', 'Los Angeles'),
(22, 'Manvi Chaturvedi', 'Los Angeles'),
(23, 'Prakhar Awasthi', 'Los Angeles');

Output:

classTable

Output

Explanation: We have inserted records successfully into the class table.

Method 2: Using INSERT INTO SELECT

We can also use the INSERT INTO SELECT statement to insert multiple values from another table, it simply selects our desired values from a table and inserts them into the table we want.

Syntax:

INSERT INTO destination_table (column1, column2, column3, ...)
SELECT value1, value2, value3, ...
FROM source_table
WHERE conditions;

Example

Query:

In the given, we will be creating a table first and then we will insert the values, and then we will create our destination in which we want to insert the multiple rows with the existing table.

-- Creating first table
CREATE TABLE first_table (
id INT,
name VARCHAR(50),
salary INT,
department VARCHAR(50)
);

-- Inserting data into first table
INSERT INTO first_table (id, name, salary, department)
VALUES
(1, 'John Doe', 50000, 'IT'),
(2, 'Jane Smith', 60000, 'HR'),
...

-- Create a second table to insert multiple values using first table
CREATE TABLE second_table (
id INT,
name VARCHAR(50),
salary INT
);

-- Inserting data from first_table into second_table with a condition
INSERT INTO second_table (id, name, salary)
SELECT id, name, salary
FROM first_table
WHERE department = 'IT';

Output for First Table:

FirstTable

First Table

Output for Second Table:

SecondTable

Second Table

Explanation: We have successfully fetched the records from the first_table.

Method 3: Using LOAD DATA INFILE

This command is used to insert data from a text file to a table in SQL, by using the “LOAD DATA INFILE” command we can easily insert multiple rows into the table. If there is a condition in which we are having a “data.txt” file and a table of employees with columns id, name, salary, and department as Columns.

Syntax:

LOAD DATA INFILE '/path/to/data.txt'
INTO TABLE employees
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(id, name, salary, department);

Example

Query:

In this example, we will create an employees Table then we will load the file along with their path.

-- Creating Table
CREATE TABLE employees (
id INT,
name VARCHAR(50),
salary INT,
department VARCHAR(50)
);
-- Loading the file
LOAD DATA INFILE '/path/to/data.txt'
INTO TABLE employees
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(id, name, salary, department);
-- To show your table
SELECT * FROM employees;

Output:

UsingLOADDATAINFILE

Using LOAD DATA INFILE

Explanation: We have inserted records successfully into the employees table.

Method 4: Using Batch Inserts for Improved Performance

Using Batch Inserts reduces the no. of query, and we can insert multiple rows in a query. Here the syntax used will be “INSERT INTO” and “VALUES” clause.

Example

Query:

Let’s create a table called classroom and then perform Batch Inserts for Improved Performance operations.

-- Create the table
CREATE TABLE classroom (
id INT PRIMARY KEY,
name VARCHAR(50),
rollno INT,
department VARCHAR(50)
);


-- Use a single INSERT INTO ... VALUES statement for bulk insert
INSERT INTO classroom (id, name, rollno, department)
VALUES
(1, 'John Doe', 12, 'IT'),
(2, 'Jane Smith', 13, 'IT'),
(3, 'Bob Johnson', 14, 'AI'),
(4, 'Alice Williams', 15, 'AI'),
(5, 'Charlie Brown', 16, 'CS'),
(6, 'Eva Davis', 17, 'IT'),
(7, 'Frank Miller', 18, 'CS'),
(8, 'Grace Taylor', 19, 'CS');

Output:

UsingBatchInserts

Using Batch Inserts

Explanation: We have inserted records successfully into the classroom table.

Conclusion

In this article, we explored how we can insert multiple rows into a table by using the “INSERT INTO” statement and the “VALUES” clause. For inserting multiple rows first, we have to create a table and then we can easily use the INSERT INTO statement to insert rows into the table, you can move to the steps motioned above to insert multiple rows.

FAQs on MySQL Insert Multiple Rows

How do I insert multiple rows in MySQL?

You can insert multiple rows with a single command by listing them together. For example:

INSERT INTO table_name (column1, column2) VALUES (value1, value2), (value3, value4);

Why should I insert multiple rows at once?

Doing this makes your database operations faster and more efficient by reducing the number of separate commands sent to the database. It also keeps your code cleaner and easier to manage.

Is there a limit to how many rows I can insert at once?

Yes, there’s a limit based on the maximum data size the server can handle in one go, usually around 4MB by default. You can change this limit in the server settings if needed.



Previous Article
Next Article

Similar Reads

How to Select 10 Random Rows from 600K Rows Fast in MySQL?
Selecting random rows simultaneously from a database is a common task in SQL especially when handling large datasets. Selecting multiple rows is useful for sampling data or generating random subsets for analysis. In MySQL, this can be achieved using various methods, each has its advantages. In this article, we explore retrieving 10 random rows from
4 min read
SQL Server INSERT Multiple Rows
SQL Server is a relational Database Management System(RDBMS). It offers various features for creating, and managing databases with its efficient tools. It can handle both small-scale and large-scale industry database applications. INSERT Statement in SQL ServerThe Insert statement is a command of the Data Manipulation Language (DML) of DBMS. After
4 min read
How to Insert Multiple Rows at Once in PL/SQL?
As the volume and complexity of data continue to grow in modern systems, efficient data management techniques become important. One fundamental operation in database management is the insertion of multiple rows at once. In this article, we understand the techniques and methods available in PL/SQL for inserting multiple rows simultaneously. We will
4 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common operation that may enhance efficiency when managing large datasets. By executing a single SQL query, more than one row is inserted simultaneously, which reduces the overload of multiple individual inserts. This method not only helps in the insertion process but also enhances the databas
4 min read
How to Insert Multiple Rows in SQLite?
In the area of database management, efficiency is key. When working with SQLite, a lightweight database engine, inserting multiple rows efficiently can significantly boost performance and speed our workflow. In this article, We will understand how to insert multiple rows in SQLite through various methods along with the examples and so on. How to In
3 min read
How to UPDATE Multiple ROWs in a Single Query in MySQL?
In the world of database management efficiency, perfection, accuracy & precision are considered to play a vital role. When it comes to MySQL stands for “Structured Query Language”, MySQL is the most common standardized language used for database management currently. A database is a structured collection of data. This data may include anything
5 min read
MySQL Insert Date Time
In today's world, working with data is now a data-to-data activity, so therefore managing data with proper data and time is also crucial. MySQL provides functionalities to handle data and time properly in the database. Understanding how to insert data and time into MySQL database with functions provided by MySQL. Let's understand with the help of e
4 min read
How to Insert a Line Break VARCHAR String in MySQL
When dealing with textual data in MySQL databases, maintaining proper formatting is important for readability and clarity. One common formatting requirement is to insert line breaks within VARCHAR and NVARCHAR strings. In this article, we will understand How to insert a line break in a MySQL VARCHAR/NVARCHAR string using two data types: VARCHAR (Va
3 min read
How to INSERT If Row Does Not Exist in MySQL
In databases, sometimes you want to add new information, but if they're already there, you might need to update their information. We use the term "upsert" for this dual action of inserting new records or updating existing ones. MySQL provides us with some simple ways to handle this. In this article, we are going to explore different approaches to
5 min read
MySQL INSERT INTO Statement
In MySQL, the INSERT INTO statement is essential for adding new data rows to a table in a database. This is important for setting up initial data in tables and for adding new records as needed when working with the database. Understanding how to use the INSERT INTO statement is key for managing and ensuring the integrity and functionality of the da
6 min read
MySQL INSERT INTO SELECT Statement
MySQL is an open-source relational database management system that uses Structured Query Language (SQL) to manipulate databases. It stores data in a table format. It provides various statements to perform Create, Read, Update, and Delete operations on a database table. INSERT INTO SELECT statement is considered as a part of Data Manipulation Langua
5 min read
MySQL INSERT IGNORE
In MySQL, managing data insertion errors is crucial for maintaining data integrity and ensuring smooth database operations. The INSERT IGNORE statement provides a practical solution by allowing records to be inserted without interruption even if some rows would cause errors like duplicate key violations. In this article, We will learn about MySQL I
5 min read
MySQL After Insert Trigger
An "AFTER INSERT" trigger in MySQL automatically executes specified actions after a new row is inserted into a table. It is used to perform tasks such as updating related tables, logging changes or performing calculations, ensuring immediate and consistent data processing. In this article, We will learn about the MySQL After Insert Trigger in detai
4 min read
MySQL Before Insert Trigger
MySQL BEFORE INSERT triggers are essential tools for maintaining data quality and enforcing business rules at the database level. These triggers automatically execute a series of SQL statements before a new row is inserted into a table, allowing for data validation, modification, and enhancement. An INSERT trigger in MySQL is a special set of instr
5 min read
How to Restrict Results to Top N Rows per Group in MySQL
When working with MySQL databases, the need to limit results to the top N rows per group is a common requirement. This is particularly useful in scenarios where you aim to retrieve a specific number of records for each distinct group in your dataset. Achieving this involves leveraging the ROW_NUMBER() window function along with the PARTITION BY cla
5 min read
How to Delete Duplicate Rows in MySQL?
Duplicate rows are a common problem in MySQL databases. Duplicate rows can cause problems with data accuracy and integrity. They can also make it difficult to query and analyze data. They can occur for a variety of reasons, such as: Data entry errorsData import/export errorsDatabase synchronization errorsSoftware bugs4 Ways to Delete Duplicate Rows
3 min read
How to Convert Rows into Columns in MySQL?
Converting rows into columns, also known as pivoting or transposing, is a common operation in DBMS, and MySQL provides robust functionality for achieving this transformation. This process is useful to reshape data for better analysis or reporting. This guide will explore the syntax, usage, and examples of converting rows into columns in MySQL. Tran
3 min read
Show All Rows with an Above-Average Value in MySQL
Finding All Rows with an Above-Average Value in MySQL is easy because in this article we will learn some methods to identify rows in a dataset where values exceed the dataset's average. Using MySQL we will discuss two approaches using subqueries with average calculations and through JOIN operations with subqueries. We'll implement the method with t
4 min read
How to Update Table Rows Using Subquery in MySQL
Updating table rows using subqueries in MySQL enables precise modifications based on specific conditions or values from other tables. This technique leverages subqueries within the SET or WHERE clauses of the UPDATE statement, allowing dynamic and context-specific updates. This guide covers the syntax, methods, and examples of updating rows with ag
5 min read
How to SELECT Rows With MAX PARTITION By Another Column in MySQL
MySQL is a widely used relational database management system (RDBMS) that provides a robust and scalable platform for managing and organizing data. MySQL is an open-source software developed by Oracle Corporation, that provides features for creating, modifying, and querying databases. It utilizes Structured Query Language (SQL) to interact with dat
6 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
MySQL functions are powerful tools that help in performing complex calculations and data manipulation with ease. The functions in MySQL can edit rows and tables, alter strings, and help you manage organized and easy-to-navigate databases. A function is a special type of predefined command set that performs some operation and returns a value. Functi
3 min read
How to Concatenate Text From Multiple Rows in SQL Server
When we fetch data from a table, there may be requirements to concatenate the text value of a table column in multiple rows into a single row. There are many ways we can concatenate multiple rows into single row SQL Server. We can use different ways based on need and convenience. In this article, we will discuss how to concatenate text from multipl
6 min read
How to Update Multiple Rows at Once Using PL/SQL?
Updating multiple rows simultaneously is a common requirement in database management, especially when handling large datasets. PL/SQL, the procedural extension of SQL in Oracle databases, provides various techniques to accomplish this task efficiently. In this article, we will explore different approaches to updating multiple rows effectively using
4 min read
How to Update Multiple Rows in PostgreSQL?
In PostgreSQL, the UPDATE statement is a powerful tool used to modify existing records within a table. We appoint two sorts of examples: the primary includes updating based totally on a single condition, while the second relates to updating based totally on multiple conditions. Throughout this article, we can make use of PostgreSQL Server as our da
5 min read
How to Get Multiple Counts With Single Query in MySQL
MySQL is an open-source Relational Database Management System that stores data in a structured format using rows and columns. MYSQL language is easy to use as compared to other programming languages like C, C++, Java, etc. By learning some basic commands we can work, create, and interact with the Database. MySQL is open-source and user-friendly. It
5 min read
How to Find the Maximum of Multiple Columns in MySQL?
Database management often involves the need to extract meaningful insights from multiple columns. One common challenge is identifying the maximum value across these columns. MySQL, a robust database management system, offers effective functionality for such tasks. To find the maximum value among several columns in MySQL, we use the GREATEST() funct
5 min read
How To Update Multiple Columns in MySQL?
To update multiple columns in MySQL we can use the SET clause in the UPDATE statement. SET clause allows users to update values of multiple columns at a time. In this article, we will learn how to update multiple columns in MySQL using UPDATE and SET commands. We will cover the syntax and examples, providing explanations to help you understand how
3 min read
Retrieve Records from Multiple Tables in MySQL
In relational databases like MySQL, data is often spread across multiple tables to maintain normalization and avoid redundancy. To effectively work with such data, you need to combine and retrieve records from these tables using various types of joins and other methods. This article will guide you through different ways to retrieve records from mul
5 min read
How to Store Multiple Dates in a Column in MySQL
In MySQL databases, storing multiple dates within a single column can be a requirement when dealing with scenarios such as event schedules, recurring tasks, or historical records. Understanding how to effectively manage and query multiple dates from a single column is crucial for optimizing database structure and query efficiency. This guide explor
4 min read
MariaDB INSERT Statement
MariaDB is a famous open-source relational database management system. It is renowned for its performance, scalability, and robust functions. One essential thing about operating with databases is the ability to insert information, and the INSERT statement plays a crucial role in this technique. In this article, we can explore the MariaDB INSERT dec
3 min read