Feb 6, 2015

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

Hi,

We have to find TOP 1 & BOTTOM 1 records together.
If we use UNION ALL it will throw an error like

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

UNION accept only one ORDER BY clause.

So,

1. For column contains characters like ABC-123

Use this syntax :

SELECT * FROM table_name
WHERE column_name IN (SELECT TOP 1 column1 FROM table_name ORDER BY column_name)
OR
column_name IN(SELECT TOP 1 column1 FROM table_name ORDER BY column_name DESC)

2. For column contains int values like 123

Use this syntax :

SELECT * FROM table_name
WHERE column_name IN (SELECT TOP 1 min(column1) FROM table_name)
OR
column_name IN(SELECT TOP 1 max(column1) FROM table_name)

========================================

Example :

1. For column contains characters like ABC-123



2. For column contains int values like 123



Thanks