2

Can anyone tell me how to fix this? My order by is by coursenum (for example, CS 20, CS 25, CS 100 are all course numbers) ascending. It's counting the first digit instead of the whole number though:

-----------------------------------------
Course                              Grade
-----------------------------------------
CS 120 Intro to Java Programming        A
CS 140 Structured Analysis              A
CS 20 Intro to Computers                F
CS 25 Intro to Programming              B

2 Answers 2

8

The problem here is that your database is doing a string sort, rather than a numeric sort. A computer won't be able to look at that data and infer a semantic sorting order. A string sort is done by taking two strings, and comparing each character until one character comes before another. So, in your example, each of those courses begins with "CS ", but then the 4th character is a numeric character (which is not the same as a numeric type!). the "1"s sort as lower than the "2"s, and then in the "1"s, the "2" sorts lower than the "4", and so on.

To solve this, you'd either need to zero pad the course number ("CS 020") or you'd need a separate numeric column with the course number to sort on.

Sign up to request clarification or add additional context in comments.

1 Comment

All right, thanks man. I'll keep that in mind the next time I design a database.
4

Strip out the non-digital characters and use to_number(),

with t as (
 select 'CS 120 Intro to Java Programming' course from dual
 union
 select 'CS 140 Structured Analysis' course from dual
 union
 select 'CS 20 Intro to Computers' course from dual
 union
 select 'CS 25 Intro to Programming' course from dual
)
select
  course, regexp_replace(course, '[^0-9]', null) n
from
  t
order by
  to_number(regexp_replace(course, '[^0-9]', null))
;

alt text

1 Comment

Thank you. I will try this when I get home.

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.