Getting Top 1 and Bottom 1 results with a simple SQL query

Whenever there is a requirement to get a top 1 and the bottom 1 records in a single query, we start writing the query as below

SELECT TOP 1 * FROM Customers order by CustomerID  ASC
UNION ALL
SELECT TOP 1 * FROM Customers order by CustomerID DESC

But this will result below error.

Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword ‘UNION’

This will be resolved simply by making use of CTEs which are introduced in SQL2005 and higher

;WITH TopBottomRows
AS
(
SELECT TOP 1 * FROM Customers order by CustomerID  ASC
UNION ALL
SELECT TOP 1 * FROM Customers order by CustomerID DESC
)
SELECT * FROM TopBottomRows

Hope this helps..

Advertisements

One Comment on “Getting Top 1 and Bottom 1 results with a simple SQL query”

  1. Sundeep says:

    Hi Khadar,Its very simple and effective technique to use and remember as well :-)Thanks,Sundeep


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s