Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to order by the last three characters of a column

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;

like image 246
Sonam Kapoor Avatar asked Jan 16 '16 22:01

Sonam Kapoor


People also ask

How do I get last 4 characters of a string in sql?

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.

How do I get the first 3 characters of a column in sql?

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.

What is ORDER BY 3 in sql?

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.


2 Answers

Try with this for MySQL:

SELECT NAME FROM STUDENTS WHERE Marks > 75 ORDER BY RIGHT(NAME, 3), ID ASC; 
like image 178
hizbul25 Avatar answered Oct 13 '22 10:10

hizbul25


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; 
like image 25
Rohan Khude Avatar answered Oct 13 '22 10:10

Rohan Khude