T-SQL Query To Order By The Last Three Characters Of A Column

Introduction

In this article, we will discuss how to Order By the Column Result By Last Three Characters of that Column.

Order By The Last Three Characters

First lets select all the rows from the table,

SELECT 
	StudentId,
	FirstName,
	LastName,
	RegistrationNumber
FROM [Details].[StudentDetails] 
Fig 1. All Results from the table StudentDetails

Now lets apply logic to Order By last three characters of the column FirstName.

SELECT 
	StudentId,
	FirstName,
	LastName,
	RegistrationNumber
FROM [Details].[StudentDetails] 
ORDER BY RIGHT(FirstName,3)

And it results as shown below,

Fig 2. Order By Last Three Characters of a Columns

If we look into the result rows, 8th and 9th rows last three characters are same and also it is same for 11th and 12th rows. So in this scenario, we have to again apply Order By for StudentId column. Basically f two or more students both have names ending in the same last three characters (i.e.: “Bobby”, “Robby”, etc.), secondary sort them by ascending StudentId.

SELECT 
	StudentId,
	FirstName,
	LastName,
	RegistrationNumber
FROM [Details].[StudentDetails] 
ORDER BY RIGHT(FirstName,3), StudentId ASC
Fig 3. After adding StudentId to Sort the Names

Conclusion

In this article, we have discussed how to Order the Column by its last three characters and if we have similar ending characters then sort by its Id column. I hope this article was useful to many of us. Please share your feedback in the comment section.

One thought on “T-SQL Query To Order By The Last Three Characters Of A Column

Add yours

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 )

Facebook photo

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

Connecting to %s

Website Built with WordPress.com.

Up ↑

%d bloggers like this: