SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL – Part 3

Please read SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL before continuing this article. I had asked users to come up with alternate solution of the same problem. Khadar Khan came up with good solution using CTE SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL – Part 2. Today we will see the solution suggested by Dave Arthur. This solution is quite good as it uses UNION ALL instead of OR clause.

SQL SERVER - How to Retrieve TOP and BOTTOM Rows Together using T-SQL - Part 3

USE AdventureWorks
GO
SELECT A.*
FROM
(
SELECT TOP 1 *
FROM Sales.SalesOrderDetail
ORDER BY SalesOrderDetailID) A
UNION ALL
SELECT B.*
FROM
(
SELECT TOP 1 *
FROM Sales.SalesOrderDetail
ORDER BY SalesOrderDetailID DESC) B
GO

Want to try this yourself? Here is how to install AdventureWorks.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Function, SQL Joins, SQL Scripts
Previous Post
Finding the Most Frequently Run Queries
Next Post
SQL SERVER – 2005 – Find Nth Highest Record from Database Table – Using Ranking Function ROW_NUMBER

Related Posts

8 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.