I’m digging into a legacy code (C++/Qt) which uses SQL(uses Oracle 11g) a lot. I’ve come with this piece of code(just changed variables name and write it in multiple lines for a better readability):
insert into FOO_TABLE (BEGIN, FIRST_VALUE, SECOND_VALUE, VALUE, BAR) select
999,
D.FIRST,
(select O.SECOND from TABLE_TWO O where O.ID=555),
333,
444
from TABLE_ONE D where D.ID=666
This in the form of INSERT INTO ... SELECT ...
Now it seems here “select” is used together with insert to retreive and create a row with a single line. However the syntax seems awkward. I changed it to:
insert into FOO_TABLE (BEGIN, FIRST_VALUE, SECOND_VALUE, VALUE, BAR) values (
999,
(select D.FIRST from TABLE_ONE D where D.ID=666),
(select O.SECOND from TABLE_TWO O where O.ID=555),
333,
444)
And this one works without any problem. This is in the form of INSERT INTO ... VALUES ...
Is there any difference in terms of performance or anything else? Because the second line seems more natural to me.
The difference is the cardinality of the result sets.
The first statement will work regardless of how many rows in TABLE_ONE match
D.ID=666. Whereas the second statement will fail if more than one row is returned.For completeness there is a third variation:
The Oracle optimizer is clever enough to know whether TABLE_TWO is matching on a unique key and will draw up an execution plan accordingly.
With regards to relative performance all variations ought to be the same. Certainly this is what I woudl expect if both queries return a single row each. There might be differences if TABLE_ONE returns multiple rows. As always, when it comes to tuning queries, you would have to benchmark each approach, as execution times are sensitive to data volumes and skew.