Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by last 2 characters string

This is the result of my query, but it doesn't order correctly. I want to order by the last 2 characters. The result should be: Fa0/10 below Fa0/9.

Fa0/1
Fa0/10
Fa0/11
Fa0/12
Fa0/2
Fa0/3
Fa0/4
Fa0/5
Fa0/6
Fa0/7
Fa0/8
Fa0/9
Gi0/1
Gi0/2
Null0
Vlan1

My query:

SELECT inft.port FROM interfaces AS intf ORDER BY RIGHT(intf.port + 0, 2)

Second: sqlfiddle

like image 474
9edge Avatar asked Dec 12 '13 10:12

9edge


People also ask

How do I sort last 3 characters of a string in SQL?

SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the 'yourSortingOrder' to ASC or DESC to set the ascending or descending order respectively. Here is the query to order by last 3 chars. Case 1 − Get the result in ascending order.

How do I get last two characters 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.

What is ORDER BY 2 1 DESC in SQL?

C) Sort rows by column's positions example SELECT name, credit_limit FROM customers ORDER BY 2 DESC, 1; In this example, the position of name column is 1 and credit_limit column is 2. In the ORDER BY clause, we used these column positions to instruct the Oracle to sort the rows.

How do I get the first two characters of a string in SQL query?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).


3 Answers

Try this:

SELECT port 
FROM interfaces 
ORDER BY SUBSTRING_INDEX(port, '/', 1), CAST(SUBSTRING_INDEX(port, '/', -1) AS SIGNED)

Check the SQL FIDDLE DEMO

OUTPUT

|   PORT |
|--------|
|  Fa0/1 |
|  Fa0/2 |
|  Fa0/3 |
|  Fa0/4 |
|  Fa0/5 |
|  Fa0/6 |
|  Fa0/7 |
|  Fa0/8 |
|  Fa0/9 |
| Fa0/10 |
| Fa0/11 |
| Fa0/12 |
|  Gi0/1 |
|  Gi0/2 |
|  Null0 |
|  Vlan1 |
like image 185
Saharsh Shah Avatar answered Oct 28 '22 23:10

Saharsh Shah


Why you need + 0 ?? Simply remove it and it will work.

SELECT port FROM interfaces ORDER BY RIGHT(port, 2)

SQL Fiddle Demo

Output:

PORT
------------
Fa0/1
Gi0/1
Gi0/2
Fa0/2
Fa0/3
Fa0/4
Fa0/5
Fa0/6
Fa0/7
Fa0/8
Fa0/9
Fa0/10
Fa0/11
Fa0/12
Null0
Vlan1
like image 31
Vishal Suthar Avatar answered Oct 29 '22 01:10

Vishal Suthar


The order is correct - lexicographically.

You need to convert them to a number.

like image 33
Jan Avatar answered Oct 29 '22 00:10

Jan