Select TOP and BOTTOM Rows Together Using SQL Server 2008

In this article, I will explain how to retrieve the top and bottom rows together from a table.
  • 4060

In this article, I will explain how to retrieve the top and bottom rows together from a table.

Create Table

CREATE TABLE [dbo].[Student1Details](

      [ID] [int] NOT NULL,

      [Name] [varchar](50) NULL,

      [Branch] [varchar](10) NULL,

      [Location] [varchar](10) NULL,

 CONSTRAINT [PK_Student1] PRIMARY KEY CLUSTERED

(

      [ID] ASC

)

) ON [PRIMARY]

Insert some values

INSERT INTO Student1Details

SELECT 1, 'Nitin', 'CS','IND' UNION ALL

SELECT 2, 'Ravi', 'EI','ENG' UNION ALL

SELECT 3, 'Tim', 'ME','US' UNION ALL

SELECT 4, 'Rick', 'ME','IND' UNION ALL

SELECT 5, 'Rakesh', 'CS','ABD' UNION ALL

SELECT 6, 'Tarun', 'ME','IND' UNION ALL

SELECT 7,'Raushan','IT','IND' UNION ALL

SELECT 8,'Aman','EC','US'

SELECT * FROM Student1Details

Student1Details Table

StudentTable.jpg

To find TOP 1 and BOTTOM 1 record together from Student1Details table write following query:

select * from Student1Details where ID = (select max(id) from Student1Details)

union

select * from Student1Details where ID = (select min(id) from Student1Details)

Output:

TopAndBottomRows.jpg

© 2020 DotNetHeaven. All rights reserved.