Query the name of any student in STUDENTS who scored higher than 75 marks. 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.
STUDENTS table has following columns:
ID , NAME , MARKS
Sample input:
id name marks 1 ashley 81 2 samantha 75 3 julia 76 4 belvet 84
Sample output:
Ashley Julia Belvet
Explanation:
Only Ashley, Julia, and Belvet have marks > 75
. If you look at the last three characters of each of their names, there are no duplicates and 'ley' < 'lia' < 'vet'
.
This is correct output:
select name from students where marks>75
order by substr(name, -3, 3), id;
To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.
You can use LEN() or LENGTH()(in case of oracle sql) function to get the length of a column. SELECT LEN(column_name) FROM table_name; And you can use SUBSTRING or SUBSTR() function go get first three characters of a column.
Order by 3 DESC. In this query, column birthdate is at the 3rd position; therefore, we can use three in the Order by clause to sort results on this column data. Note: I would not recommend using column position in Order By clause. You should always use a column name in Order by clause.
Try with this for MySQL:
SELECT NAME FROM STUDENTS WHERE Marks > 75 ORDER BY RIGHT(NAME, 3), ID ASC;
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. That's why ORDER BY ID
is needed.
For MySQL:
SELECT Name FROM STUDENTS WHERE Marks>75 ORDER By SUBSTRING(Name,-3,LENGTH(Name)),ID
Reference: MySQL SUBSTRING() function
For Oracle:
SELECT Name FROM Students WHERE Marks > 75 ORDER BY substr(Name, -3), ID;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With