tags:

views:

101

answers:

2

I have 2 tables with duplicate record including 'Id' field, and I need union them.
But I think [union all] is much more efficient than [union]
for the reason that it need not sorting.

Following is my sql:
SELECT *
FROM [dbo].[RealTime]
UNION ALL
SELECT *
FROM [dbo].[Query] a
WHERE NOT EXISTS(
   SELECT TOP 1 1
   FROM [dbo].[RealTime] b
   WHERE a.Id = b.Id
)
Will you have any suggestion or more elegant statement ?

+1  A: 

Your sample sql get recordset without record in the second table whose id is same but maybe other fields are different.
Is it your requirement?

petergo
yes, it is my requirement.
sesame
+1  A: 

Option 1 (yours): query dbo.RealTime first, then query dbo.Query, then for each row from dbo.Query, do a lookup on dbo.Realtime.

Option 2 (UNION): query dbo.RealTime, query dbo.Query, then remove duplicates.

Apart from the fact that these two options will give different results (the first option will retain duplicates obtained from dbo.RealTime and dbo.Query), I'd say Option 2 will most probably be less resource intensive since it doesn't have to query dbo.RealTime twice - unless (perhaps) dbo.RealTime is smaller than dbo.Query by an order of magnitude.

Jeffrey Kemp
dbo.RealTime is much smaller than dbo.Query. Thank you !
sesame