Question

I was practicing SQL problems at hackerrank.com when I came across the following question:

Query the Name of any student in STUDENTS who scored higher than 75. The Marks field in the table stores the marks for student. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID.

To solve this, I put together a query with the help of this post:

select Name 
from STUDENTS
where Marks > 75 
order by case when substring(Name from -1 for 3) then 1 else 0 end, ID asc;

Now I am not sure that it actually does what the question is asking since, I have no idea idea of using case in queries. Any help will be greatly appreciated.

Was it helpful?

Solution

Your query is wrong.

case when substring(Name from -1 for 3) 
     then 1 
     else 0 end

The expression substring(Name from -1 for 3) returns one last symbol from Name (if exists). Not 3 last as you want...

So the whole expression returns 0, when Name is NULL, empty string, or when the last symbol in Name is not a digit rather than 0. And 1 otherwise (when last symbol exists, and it is a digit from 1 to 9).


Correct query (looking on your query) is

SELECT Name 
FROM Students
WHERE Marks > 75 
ORDER BY RIGHT(Name, 3) ASC, 
         id ASC;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top