I have to write an INSERT query in sqlite3 that uses the values of multiple columns from the same nested query.
In the example below i need to insert into table_a multiple values from the same nested query on table_b. I did not find a way to use the values from multiple columns without repeating the query.
This is what i am using at the moment:
INSERT INTO table_a (col_0, col_1, col_2, col_3) VALUES (
?,
?,
-- Use different columns from the same query
(SELECT col_x from table_b where rowid = ?),
(SELECT col_y from table_b where rowid = ?)
);
As you can see, i am writing the query again and the output of EXPLAIN QUERY PLAN (below) shows that the nested query is in fact being executed twice. This is a very simple query but with more complex ones it would get very bad very quickly.
QUERY PLAN
|--SCALAR SUBQUERY 1
| `--SEARCH table_b USING INTEGER PRIMARY KEY (rowid=?)
`--SCALAR SUBQUERY 2
`--SEARCH table_b USING INTEGER PRIMARY KEY (rowid=?)
Is there an easier method for the simpler case where i am inserting values from the same table in the same columns? (In other words, duplicating an already existing row but with some columns modified)
INSERT INTO table_a (col_0, col_1, col_2, col_3) VALUES (
?,
?,
-- Use different columns from the same query
(SELECT col_2 from table_a where rowid = ?),
(SELECT col_3 from table_a where rowid = ?)
);