Note that there are some explanatory texts on larger screens.

plurals
  1. POSQLite: select results affected by subsequent insert
    primarykey
    data
    text
    <p>I am developing an application in which I am iterating over many (1,000,000+) rows in a table while inserting new rows and updating existing rows along the way. It is a requirement that the select statement yields every row in the table (those that exist when the select is initially executed) exactly once, and never yield rows that are inserted after the select is executed. I would prefer not to load all rows into memory (that takes a long time and a lot of RAM—I tried it).</p> <p>I have developed a small Python example that demonstrates that SQLite apparently does not isolate inserts (and presumably updates and deletes) from a long-running select. I was not able to find any place in the SQLite documentation that specifically mentions this behavior, but I found several links that alluded to the fact that the insert would fail (possibly in earlier versions of SQLite?), which it does not in my example.</p> <pre class="lang-py prettyprint-override"><code>import sqlite3 def select_affected_by_insert(): # select from and simultaneously modify same table cn = sqlite3.connect(':memory:') cn.execute("CREATE TABLE demo (v INTEGER PRIMARY KEY)") n = 5 values = [[v] for v in range(n)] cn.executemany('INSERT INTO demo VALUES (?)', values) for (v,) in cn.execute('SELECT v FROM demo'): with cn: # insert in transaction cn.execute('INSERT INTO demo VALUES (?)', [n + v]) print v, n + v assert v &lt; n, 'got more rows than expected!' if __name__ == '__main__': select_affected_by_insert() </code></pre> <p>SQLite 3.6.12<br/> Python 2.6.4</p> <p>Is there a better way to work around this than copying the data to a separate (temporary) table and select from there?</p> <p>Clarification: I neglected to say that I need to do commits inside the loop. The process may be interrupted, and partially done work must be committed so it does not need to be redone on the next run-through.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload