Zahid Zahid - 3 months ago 22
SQL Question

Query with order by

Table : Students

ID Name Marks
1 Ashley 81
2 Samantha 75
4 Julia 76
3 Belvet 84


A query to return the name where marks is greater than 75, output will be sorted by last three characters of each name,if ties,then sort with ascending ID.

My Query:-

Select Name
From Students
Where Marks > 75
Order By (Select Substring(Name,1,2))


I tried this so far,I tried to figure out
order by
someway,but this is wrong . How could I accomplish it?

Answer
SELECT Name
FROM Students 
WHERE Marks > 75
ORDER BY RIGHT(Name, 3),
         ID

You could also use:

ORDER BY SUBSTRING(Name, LEN(Name)-2, 3)

as an alternative.