I would like to make a table where I would have a specific order of rows to make it easier to access them individually and as fast as possible. To achieve this I have created the index
column and made it a PRIMARY KEY
, NOT NULL
and UNIQUE
. I am not sure that the last two will meke it faster, but feel free to correct me. This is where the problems start to arise. Whenever I delete any record from this table, the indexing will be destroyed, and this is a big issue, becuse in my code I rely on the fact that the next row has an index that is larger by one. To battle this, I have attempted to use the AUTOINCREMENT
keyword, but it did not work as planned. Here the code which shows what I mean:
import sqlite3
con = sqlite3.connect('test_db.db')
con.execute('''
CREATE TABLE IF NOT EXISTS epic_table (
'index' INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
city TEXT NOT NULL,
avg_salary FLOAT
);
''')
con.execute('INSERT INTO epic_table VALUES (0, "Chicago", 12.0)')
con.execute('INSERT INTO epic_table VALUES (1, "New York", 9.11)')
con.execute('INSERT INTO epic_table VALUES (2, "Detroit", 0.19)')
print(con.execute('SELECT * FROM epic_table').fetchall(), '\n')
con.execute('DELETE FROM epic_table WHERE `index` = 1')
print(con.execute('SELECT * FROM epic_table').fetchall())
As an output I get:
[(0, 'Chicago', 12.0), (1, 'New York', 9.11), (2, 'Detroit', 0.19)]
[(0, 'Chicago', 12.0), (2, 'Detroit', 0.19)]
As you can see, Detroit
should have had the index 1
, but it hasn't updated.
I could not find any way of fixing this, so I am asking this here, but if you know how to approach this problem in a different way, I am open for suggestions, after all, the only thing that matters is the result, not the means.