I need to find a single value from a table A
containing three foreign keys to two other tables B
and C
.
For the sake of experiment, I tested two ways to query the value:
Multiple queries:
declare @start int = (select top 1 [Id] from [B] where [Day] = '2015-01-01')
declare @end int = (select top 1 [Id] from [B] where [Day] = '2017-06-14')
declare @category int = (select top 1 [Id] from [C] where [Title] = 'Hello, World!')
select top 1 [Name]
from [A]
where [StartId] = @start
and [EndId] = @end
and [CategoryId] = @category
and [Day] = '2016-05-27'
Single query:
select top 1 [Name]
from [A]
left join [B] as [BStart] on [BStart].[Id] = [A].[StartId]
left join [B] as [BEnd] on [BEnd].[Id] = [A].[EndId]
left join [C] on [C].[Id] = [A].[CategoryId]
where [BStart].[Day] = '2015-01-01'
and [BEnd].[Day] = '2017-06-14'
and [C].[Title] = 'Hello, World!'
and [A].[Day] = '2016-05-27'
I was surprised that the execution plan indicates that the single query is more expensive than multiple queries. When doing all five select
s together, the one with left join
s indicates 53%. The other four queries indicate 12% each.
Those are the execution plans:
declare @start int = (select top 1 [Id] from [B] where [Day] = '2015-01-01')`
declare @end int = (select top 1 [Id] from [B] where [Day] = '2017-06-14')
(Same as below)
declare @category int = (select top 1 [Id] from [C] where [Title] = 'Hello, World!')
select top 1 [Name]
from [A]
where [StartId] = @start
and [EndId] = @end
and [CategoryId] = @category
and [Day] = '2016-05-27'
select top 1 [Name]
from [A]
left join [B] as [BStart] on [BStart].[Id] = [A].[StartId]
left join [B] as [BEnd] on [BEnd].[Id] = [A].[EndId]
left join [C] on [C].[Id] = [A].[CategoryId]
where [BStart].[Day] = '2015-01-01'
and [BEnd].[Day] = '2017-06-14'
and [C].[Title] = 'Hello, World!'
and [A].[Day] = '2016-05-27'
Why is the single query with left join
s slower than the first approach?
top(n)
without anorder by
returns the first N number of rows ramdom. How big are the tables ?[B].[Day]
and[C].[Title]
have an unique index, which means that the lack oforder by
doesn't make the result non-deterministic.