Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Mysql order by values within IN() function

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 257
    Comment on it

    Hello guys,
    Most of time we face the problem order by within IN() values . Mysql provides the function FIELD(), It will sort fetched IN() data according to requirment . The FIELD function returns the position of the first string in the remaining list of strings
    For Example:-

    |   id   |   name  |
    ^--------^---------^
    |   5    |   B     |
    |   6    |   B     |
    |   1    |   D     |
    |   15   |   E     |
    |   17   |   E     |
    |   9    |   C     |
    |   18   |   C     |
    

    If you fetch data without FIELD function , It may give result unordered according to within IN() values. If we use FIELD function as given below , It will gives sorted result.

    SELECT id, name
    FROM mytable
    WHERE name IN ('B', 'A', 'D', 'E', 'C')
    ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: