2

I have a site that stores cooking tutorials. one of the columns in the mysql database holds either Novice, Intermediate, Advanced, Expert. I'd like to know if there was a way to write the MySQL query to order the results in the above fashion? Is this even possible?

1
  • 1
    Yes its possible to write an expression that converts those values into values that can be sorted, and to put that expression into the ORDER BY clause. There are lots of ways to do that. The most portal ANSI-compliant would be to use a CASE expression e.g. ORDER BY CASE mycol WHEN 'Novice' THEN 1 WHEN 'Intermediate' THEN 2 WHEN 'Advanced' THEN 3 WHEN 'Expert' THEN 4 ELSE 5 END. With MySQL, we have several options for shorter expressions that achieve an equivalent result.e.g. FIND_IN_SET(mycol,'Novice,Intermediate,Advanced,Expert') Commented Nov 15, 2017 at 21:38

1 Answer 1

1

You can sort by INSTR if its a small table:

ORDER BY INSTR('Novice, Intermediate, Advanced, Expert', `colname`)

But this will be slow on a large table. Better to just store a numeric value from 1 to 4 and add an index on it. Then translate the number to Novice, Intermediate, Advanced, or Expert when needed. Or perhaps two columns but that could lead to differences between the numeric and textual value.

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

Comments

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.