tags:

views:

74

answers:

2

I need the records in my database that are "featured" to be listed first. If a listing is "featured" the value in the featured column is "yes".

I am not sure what kind of MySQL Query would give me this result, or if it even exists. But the other idea I have is to have one query that gets all featured ones and lists them, and then another one gets all of the listings that aren't featured.

Do you have any ideas? Thanks in Advance!

+3  A: 

Use an ORDER BY with a CASE statement, as in

SELECT * 
FROM TheTable
ORDER BY CASE LOWER(Featured)
           WHEN 'yes' THEN 0 
           ELSE 1 
         END 
         ASC,
         SomeOtherColumnNameForAMinorKeySort ASC

EDIT: Renamed RecordName to SomeOtherColumnNameForAMinorKeySort to better express what the column's purpose is.

David Andres
What is RecordName?
Chris B.
RecordName is there just to demonstrate a minor key sort. If you want to sort by featured status, then name, you can do so with the ORDER BY expression shown above. I imagine that you want to sort on additional columns in addition to featured status.
David Andres
@Chris B: I've renamed RecordName to SomeOtherColumnNameForAMinorKeySort to be more clear.
David Andres
So it should look like the following? ORDER BY CASE featured WHEN 'yes' THEN 0 ELSE 1 END ASC, featured ASC
Chris B.
Yes, It's similar to strager's idea, but there we have to convert some textual data, "yes", to a numeric value for sorting purposes. Give it a try, let me know if it works.
David Andres
Thanks David, i tried it but it does not seem to work. does it matter that I have to escape the double quotes \" or use single quotes ' to enclose yes?
Chris B.
Sorry, that was my mistake. yes should be in single quotes only. Also, I'm not sure if MySQL compares strings in a case insensitive. If not, lowercase the text using LOWER(featured), as shown in this example.
David Andres
unfortunately, it is still not working, and I cant seem to find mysql documentation on this. Do you happen to have the link? thank you david :)
Chris B.
Do you get an error, or is the result set not sorted correctly?
David Andres
the result is not sorted correctly.
Chris B.
Do the values in the featured column range from "yes" and "no" or "yes" and NULL?
David Andres
Documentation is here: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html. See the section on ordering by a dynamic column.
David Andres
values are always one of these two: "on" or "off" but i changed the query accordingly.
Chris B.
Try parenthesize the CASE statement. See my edit to this answer.
David Andres
Before the parenthesis it works, i just had a typo. sorry David, thanks for your help :)
Chris B.
Excellent, good to hear.
David Andres
A: 
SELECT fields FROM table ORDER BY featured DESC;
strager
This would work if featured was a bit field. In this scenario, it's a textual column that is either "yes" or "no," presumably.
David Andres