• Friday, March 16, 2012
  • Convert VARCHAR as INT for sorting in MYSQL


    Today i was working on a database which was more than 10 years old. My task is to fetch records form table and display based on sorting order. Here my problem is sorting column was defined as VARCHAR and values stored in are Integers.




    Table: tbl_contact
    Name(VARCHAR 20)Position(VARCHAR 5)
    Kathirason2
    Asokan3
    Techispeaks1

    In the above table i want to sort the records based on position field. As we know Integer sorting is not possible in varchar datatype. To solve this I read some articles from google and I found that Mysql provides an inbuilt function called CAST.

    Syntax:
    CAST(expr AS TYPE

    CAST makes my job easier. Here is my query that did the magic.

    Example:
    SELECT FROM `tbl_contact` ORDER BY CAST(`position` AS SIGNEDDESC 

    Output:
    Name  Position
    Asokan  3
    Kathirason  2
    Techispeaks  1

    Share this post

    Kathirason Asokan
    About the Author
    I'm , I love writing code in PHP, and spending time with friends. My hobbies are blogging, surfing internet, juggling etc.,.

    1 comment:

    1. thanks for the info. i am searching for the same.

      ReplyDelete

     
    Copyright (c) 2011 - 2021 techispeaks.com. All rights reserved the content is copyrighted to Kathirason Asokan
    Creative Commons License