I have two tables with data as –
TestTable1 TestTable2
---------- ----------
Id Name DealDate Id Name DealDate
1 aaTable 2010-09-22 1 aaTable2 2010-09-23
2 bbTable 2010-09-23 2 bbTable2 2010-09-24
3 ccTable 2010-09-28 3 ccTable2 2010-09-26
4 ddTable 2010-09-25 4 ddTable2 2010-09-27
I want to have only two latest records from resultset of TestTable1 + TestTable2 to return this –
Id Name DealDate
4 ccTable 2010-09-28
3 ddTable2 2010-09-27
This is my current query
SELECT TOP 2 * FROM
(
SELECT * FROM
(SELECT TOP 2 Id, Name, DealDate FROM TestTable1 ORDER BY DealDate DESC) T1
UNION ALL
SELECT * FROM
(SELECT TOP 2 Id, Name, DealDate FROM TestTable2 ORDER BY DealDate DESC) T2
) T1T2
ORDER BY DealDate DESC
Can anyone please guide me for a better way (performance-wise/readability wise) to achieve this?
P.S. Above tables are just to present the use-case, my actual tables have thousands of records.
Thank you!
The only thing I would change performance wise is to remove the
ORDER BYand theTOP 2in the inner selects – they are pointless.Other than that, your solution is the way to go. There shouldn’t be any performance problems as you are using
UNION ALLand notUNION…