Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?
MySQL Multi-Insert? MySQL DB integrity after failed INSERT
1.1k Views Asked by KeatsKelleher At
3
There are 3 best solutions below
0
Marc B
On
MySQL can insert multiple rows (search for 'multiple rows') like this:
INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...
However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use last_insert_id() to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.
If you need to guarantee integrity, then use single row insert statements and transactions.
Related Questions in PHP
- How to add the dynamic new rows from my registration form in my database?
- Issue in payment form gateway
- How to create a facet for WP gridbuilder that displays both parent and child custom fields?
- Function in anonymous Laravel Blade component
- How to change woocomerce or full wordpress currency with value from USD to AUD
- General questions about creating a custom theme Moodle CMS
- How to add logging to an abstract class in php
- error 500 on IIS FastCGI but no clue despite multiple error loggings activated
- Composer installation fails and reverts ./composer.json and ./composer.lock to original content
- How to isolate PHP apps from each other on a local machine(Windows or Linux)?
- Laravel: Using belongsToMany relationship with MongoDB
- window.location.href redirects but is causing problems on the webpage
- Key provided is shorter than 256 bits, only 64 bits provided
- Laravel's whereBetween method not working with two timestamps
- Implementing UUID as primary key in Laravel intermediate table
Related Questions in MYSQL
- How to Retrieve Data from an MySQL Database and Display it in a GUI?
- How to change woocomerce or full wordpress currency with value from USD to AUD
- window.location.href redirects but is causing problems on the webpage
- Error: local variable 'bramka' referenced before assignment
- Products aren't displayed after fetching data from mysql db (node.js & express)
- status table for all entries (even in different dates) in database changing value when all checkboxes are checked
- Can't Fix Mariadb & Mysql ERROR 2002 (HY000): Can't connect to local server through socket '/tmp/mysql.sock' (2) On MacOs
- Express Mysql getting max ID from table not working cought in a promise
- failed to upload a table from sql file
- Update a MySQL row depending on the ID in Google Sheets Apps Script
- Use row values from another table to select them as columns and establish relations between them (pivot table)
- SQL: Generate combination table based on source and destination column from same table
- How to display the column names which have only unique non-null values in MySQL table?
- mysql query takes too long because of wrong indexes usage
- Multitable joining in Sql
Related Questions in INSERT
- NEXTJS14 DRIZZLE : Async issue when trying to post data from component into DB
- Error adding data to mysql with javascript and php
- unshift vs assigning the values with loop vs manually assigning values by hand. Which one is faster?
- Save PDF file to sub folder based on a cell value
- Can I Insert Entire Typed Object Into Table With SQL, Without Specifying Each Column?
- T-SQL to merge data from different rows under different columns
- Data type mismatch in criteria expression for decimal with OleDbCommand
- Prepared Statement don't work and don't send error message in C++ with MySQL Connector 8 C
- How to add a separator between English and Arabic Text in a cell
- Sort a column automatically when an entry is added/deleted and directly create/delete a related row
- Using script to add new row below current row when cell in A is changed causes a row lower down to be deleted
- insert JSON into mysql json column
- Cannot use WHERE variable in where clause for Insert stored procedure
- BigQuery - Transaction rows double when Insert Into and Left Outer Join statement used
- Ansible lineinfile - add substring only if missing
Related Questions in MYISAM
- Solution Indication - Database
- InnoDB - errno: 1005, sqlState: 'HY000' sqlMessage: "Can't create table (tableName) (errno: -1)",
- Should handler open place a table metadata read lock on MariaDB MyISAM table?
- What does FULLTEXT indexing in MySQL understand as words?
- MyISAM queries are always at least 100ms
- How to increase speed of Node.js app using Mysql database in online gaming
- MySQL database not catching up with INSERT statements
- Does changing MYSQL table engine from MYISAM to INNODB can cause a data corruptions?
- MySQL Open Files (MyISAM, Parititioned Large Database)
- How to increase select performance on a 15 million row MyISAM table converted to InnoDB
- MySQL 64kb size limit for MyISAM table-based metadata storage unclear - differences between MySQL and MariaDB
- How to avoid #1217 foreign key error in phpMyAdmin when changing the engine of table from InnoDB to MyISAM
- Composite Primary Key with auto increment in innodb
- I want to open foo.MYI foo.MYD foo.frm db.opt in MySQL 8.0 with MyISAM engine
- Is it possible to mysqldump mixed DB (MyISAM,InnoDB) separatelly for replication setup?
Related Questions in DATABASE-INTEGRITY
- Running pymongo to save data in local mongoDB database
- Junction table referencing non existent entity
- Integrity Error on DRF on fixture teardown
- Integrity constraints to make sur two columns contain same values for two related tables
- How to prevent IntegrityError in case of using UUID in django
- How to avoid data insertion if an error occurs? (method with several insertions) in Laravel
- H2 Database : Cannot parse "DATE" constant "31-JAN-20" while inserting a new record
- How to skip an existing object instance when creating resources in bulk python
- Better to store miscellaneous metadata in database or calculate on each access
- The transient database snapshot for database XXXXX (database ID 8) has been marked suspect due to an IO operation failure
- How to ensure the data integrity using SQL Server?
- Magento 1 to Magento 2 | Data-Migration-Tool | Integrity Check + Offset
- Spring JPA + Hibernate : OneToMany bidirectional persisting
- Is there in KDB/Q any way to check integrity of a partitioned table?
- integrity error in django registration
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
That's exactly what transactions are for. If any of the commands fail, the whole thing since
START TRANSACTIONis rolled back:This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).
This will never be inserted into the table (normally you'd have some branching, e.g. an IF):
Caveat: SQL commands which change the database structure (e.g.
CREATE,ALTER,DROP) cannot be rolled back!