MySQL Insert Into Table Multiple Rows: A Complete Guide
In this article
To insert multiple rows into a MySQL table in a single operation, use the INSERT INTO statement followed by a comma-separated list of value sets. The basic syntax is: INSERT INTO table_name (column1, column2) VALUES (val1a, val1b), (val2a, val2b), (val3a, val3b);. This method is significantly faster than executing individual insert statements because it reduces the overhead of multiple network requests and transaction commits.
What You'll Need
- A running MySQL server instance.
- A MySQL client (such as MySQL Workbench, phpMyAdmin, or the command-line interface).
- An existing database and a target table with a defined schema.
- The necessary permissions (INSERT privileges) for the user account you are using to access the database.
Step-by-Step
- Identify the Target Table and Columns: Before writing the query, confirm the exact name of the table and the columns you intend to populate. For example, if you have a table named
employeeswith columnsfirst_name,last_name, anddepartment, these are the identifiers you will use in your statement. - Define the Column List: Start your SQL statement with
INSERT INTO table_name (column1, column2, ...). While you can omit the column list if you are providing values for every single column in the exact order they appear in the schema, explicitly naming the columns is a best practice. This prevents the query from breaking if the table structure changes (e.g., if a new column is added with a default value). - Construct the VALUES Clause: After the column list, add the keyword
VALUES. Now, create your first set of data enclosed in parentheses:('John', 'Doe', 'Sales'). - Append Additional Rows: To add more rows, place a comma immediately after the closing parenthesis of the previous row and start a new set of parentheses. For example:
('John', 'Doe', 'Sales'), ('Jane', 'Smith', 'Marketing'), ('Robert', 'Brown', 'Engineering'). Ensure there is no comma after the final set of values. - Terminate the Statement: End the entire command with a semicolon (
;). This tells the MySQL engine that the request is complete and ready for execution. - Execute and Verify: Run the command in your SQL editor. Once the system reports that the rows were inserted, verify the result by running a selection query:
SELECT * FROM employees;.
Common Mistakes
One of the most frequent errors is the Trailing Comma. Placing a comma after the final set of values before the semicolon will result in a syntax error because MySQL expects another row of data to follow the comma. Always double-check that the last closing parenthesis is followed directly by the semicolon.
Another common pitfall is Data Type Mismatch. If a column is defined as an INTEGER but you provide a string (e.g., 'Ten'), MySQL may either throw an error or attempt to cast the value, which can lead to unexpected zeros or truncated data depending on the server's SQL mode. Always ensure that strings and dates are wrapped in single quotes, while numeric values are not.
Column Count Mismatch is also a frequent issue. If you specify three columns in your INSERT INTO clause but provide only two values in one of your parentheses sets, the entire operation will fail. Every single row in a bulk insert must have the exact same number of values as there are columns specified in the initial list.
Finally, users often forget to handle Auto-Incrementing Primary Keys. If your table has an id column set to AUTO_INCREMENT, you should omit that column from your column list and your values list. MySQL will automatically assign the next available integer to each row. If you manually include the id and accidentally repeat a number, the query will fail due to a Duplicate Entry error.
Tips
Use Transactions for Safety: When inserting a very large number of rows, wrap your statement in a transaction. Start with START TRANSACTION;, execute your bulk insert, and then run COMMIT;. If something goes wrong during the process, you can run ROLLBACK; to revert the database to its state before the insert started, preventing partial data uploads.
Optimize Batch Sizes: While inserting multiple rows is faster than inserting one by one, there is a limit to how much data you can send in a single query. This is governed by the max_allowed_packet setting in the MySQL configuration. If you are inserting thousands of rows, it is more efficient to break them into batches of 500 to 1,000 rows per statement rather than one massive query that might exceed the packet size limit.
Handle Duplicates with INSERT IGNORE: If you are importing data that might contain records already present in the table (based on a Primary Key or Unique Index), use INSERT IGNORE INTO. This tells MySQL to skip any rows that would cause a duplicate key error and proceed with the rest of the insert, rather than failing the entire batch.
Use ON DUPLICATE KEY UPDATE: For more advanced scenarios where you want to update existing records instead of skipping them, use the ON DUPLICATE KEY UPDATE clause. This allows you to specify which columns should be updated if a row with the same primary key already exists, effectively turning your bulk insert into a "upsert" (update or insert) operation.
Troubleshooting
If your query fails, first check the Error Code provided by MySQL. A 1064 error usually indicates a syntax error, such as a missing comma or an extra comma. Check your parentheses and semicolons carefully.
If you receive an Error 1062 (Duplicate entry), it means you are trying to insert a value into a column with a UNIQUE constraint that already exists in the table. To fix this, identify the conflicting value or use the INSERT IGNORE or REPLACE INTO commands to handle the conflict.
If the query hangs or returns a Packet Too Large error, you have exceeded the max_allowed_packet limit. You can either increase this limit in the my.cnf or my.ini file (requiring a server restart) or, more practically, split your large insert statement into several smaller batches of rows.
If the data appears in the table but looks corrupted (e.g., dates are 0000-00-00 or strings are truncated), check your SQL Mode. If the server is in a non-strict mode, it may try to "fix" invalid data instead of throwing an error. Switch to STRICT_TRANS_TABLES to force MySQL to reject invalid data, which helps you identify exactly which row is causing the problem.
Frequently Asked Questions
Is there a limit to how many rows I can insert at once?
There is no hard-coded limit on the number of rows, but you are limited by the max_allowed_packet size of the server. If the total size of the SQL string exceeds this limit, the server will reject the query.
Can I insert multiple rows from another table?
Yes, you can use the INSERT INTO ... SELECT syntax. This allows you to pull data from one table and insert it into another without needing to manually list the values.
Does bulk inserting affect performance?
Yes, it significantly improves performance. It reduces the number of times the database has to parse the query, open and close table handles, and commit changes to the disk.
What happens if one row in the bulk insert fails?
By default, if one row fails (e.g., due to a constraint violation), the entire statement fails and no rows from that specific query are inserted. Using INSERT IGNORE can prevent this by skipping the failing row.
Can I use variables in a bulk insert?
In a raw SQL script, you cannot easily use variables for each row. However, if you are using a programming language like Python or PHP, you can use prepared statements with a loop or a specialized bulk-insert function provided by the database driver.