I have a sql query,
SELECT
col1,
col2,
col3, (
SELECT COUNT(id)
FROM B
WHERE B.aid = A.id
) AS col4
FROM A
What is the performance impact of having a select as a column? Will that statement be executed for every row that is returned?
I am really just interested in the performance of this query. I know there are other ways getting the count can be accomplished. But in this case I am only trying to understand how sql works with an inline select.
Apologies if this question is a dupe, I have looked through stackoverflow and I have not been able to find this anywhere.
This depends upon your SQL implementation.
SQL is declarative and it is up to the optimiser to construct a physical plan from the logical specification. SQL Server can decorrelate this sub query and turn into an
OUTER JOINGives plan
Which is basically the same as
The sub query is logically represented as a
RIGHT OUTER JOINwithMERGE JOINas the physical implementation. The merge join processes each input once rather than the row by row behaviour of a nested loops join.