devxlogo

Conditional Sorting in T-SQL

Conditional Sorting in T-SQL

There may be certain situations where you have to sort character-based columns in a particular order.

For example, Let us consider a table:

 --///////////////////////////////////SID	Subject		Marks---	------		-----1	Physics		801	Chemistry	751	Maths		901	Biology		702	Physics		652	Chemistry	702	Maths		802	Biology		60--///////////////////////////////////

Now you are asked to query a table in such a manner that Maths should come first, Physics second, Chemistry third, and Biology last for each StudentID.

To accomplish this, use T-SQL “Case” statement:

 --///////////////////////////////////select tblMarks.*from tblMarks  order by SID,	(case Subject		when 'Maths' then 1		when 'Physics' then 2		when 'Chemistry' then 3		when 'Biology' then 4		end ) ascSID	Subject		Marks---	------		-----1	Maths		901	Physics		801	Chemistry	751	Biology		702	Maths		802	Physics		652	Chemistry	702	Biology		60--///////////////////////////////////
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist