Alpha Numeric Sorting in MySQL


/ Published in: MySQL
Save to your folder(s)

Okay,

If it is required to sort columns like this

1A
1a
10A
9B
21C
1C
1D

And Our desired Result is

1A
1C
1D
1a
9B
10A
21C

We can use casting, but casting will not sort 1A, 1B,1C properly. To overcome this issue we are first converting this column to binary and sorting the binary combined with tbl_column.


hehe,,, after doing some headbanging just did it with casting too... and using same logic... damn why I didnt thought of that.


Copy this code and paste it in your HTML
  1. Bin Way
  2. ===================================
  3. tbl_column,
  4. BIN(tbl_column) AS binray_not_needed_column
  5. FROM db_table
  6. ORDER BY binray_not_needed_column ASC , tbl_column ASC
  7.  
  8. -----------------------
  9.  
  10. Cast Way
  11. ===================================
  12. tbl_column,
  13. CAST(tbl_column as SIGNED) AS casted_column
  14. FROM db_table
  15. ORDER BY casted_column ASC , tbl_column ASC

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.