1

I am using SQL server(MySQL Ver 14.14 Distrib 5.7.21, for Linux (x86_64)). I want to sort data like this.

DocTyp-2649
DocTyp-2650
DocTyp-2651
DocTyp-2652
DocTyp-26036
DocTyp-26037
DocTyp-26038

my query is

SELECT doc_unique_id FROM docs ORDER BY doc_unique_id ASC

my result is

DocTyp-26036
DocTyp-26037
DocTyp-26038
DocTyp-2649
DocTyp-2650
DocTyp-2651
DocTyp-2652

what can u do?

2
  • Prefix is not same always DocTyp- Commented Feb 9, 2018 at 7:32
  • Use SUBSTRING to split the column in two parts and sort by 1st part, length(2nd part), nd part. This avoids typecast errors when 2nd part is not always numeric Commented Feb 9, 2018 at 7:41

4 Answers 4

1

Try this query

SELECT doc_unique_id 
FROM docs 
ORDER BY cast(replace(doc_unique_id, 'DocTyp-', '') as int)
Sign up to request clarification or add additional context in comments.

Comments

1

You could explicitly sort the data by using substring() function (SQL Server) to get the numerical data

select * 
from table 
ORDER BY 
cast(substring(doc_unique_id, charindex('-', doc_unique_id)+1, len(doc_unique_id)) as int)

Comments

1

Try this:

select doc_unique_id from docs ORDER BY CAST(SUBSTRING_INDEX(doc_unique_id, '-', -1) AS UNSIGNED) ASC;

Comments

0

ORDER BY length(doc_unique_id), doc_unique_id ASC

2 Comments

Error Code: 1305 FUNCTION test.len does not exist
As you are using MySQL, you can try LENGTH instead of LEN?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.