Ok I have a sqlite db, that has roughly 100 rows. It is kind of a strange thing that I’m trying to do, but I need to insert a new row between each of the existing rows.
I have been trying to use the Insert statement as follows, but haven’t had any luck:
insert into t1(column1) values("hello") where id%2 == 0
So I’m basically trying to use the %-operator to tell me if the id is even or odd. For every even id number, I’d like to insert a new row.
What am I missing? What can I do differently? How can I insert a new row into every other row and have the index updated as well?
Thanks
Your question assumes that the rows have some kind of built-in order to them, and that you can insert rows between other rows. That’s not true.
It is true that rows have an order on disk, and that the
idcolumn is usually assigned in order, but that’s an implementation detail. When you perform a query, the database is free to return the rows in any order it chooses, unless you specify what you want with anORDER BYclause.Now, I’m assuming what you really want is to insert rows between the existing rows in
idorder. One way to get what you want would look like this:The
UPDATEwould double the ids of all the existing rows (so 1,2,3 becomes 2,4,6); then theINSERTwould perform a query on t1 and use the result to insert a new set of rows withidvalues one more than the existing rows (so 2,4,6 becomes 3,5,7).I haven’t tested the above statements, so I don’t know if they would work or if they require some extra trickery (like a temporary table) since we are querying and updating the same table in one statement. Also I may have made a syntax error.