Skip to content

How to upsert multiple records at the same time? #1624

Answered by groue
pedrommcarrasco asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @pedrommcarrasco,

Write a loop, and make sure this loop is wrapped a single write transaction:

// CORRECT: one loop wrapped in a single transaction.
try dbQueue.write { db in
    for player in players {
        try player.upsert(db)
    }
}

// VERY BAD PERFORMANCE: one loop performs many transactions.
// This forces a lot of slow file-system synchronizations.
for player in players {
    try dbQueue.write { db in
        try player.upsert(db)
    }
}

If you are surprised, please check Many Small Queries Are Efficient In SQLite.


Now, if you are looking for the absolute best performance you can get with GRDB, then go down to the SQLite metal and use a prepared statement. The library …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@pedrommcarrasco
Comment options

Answer selected by pedrommcarrasco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants