bigpotato
bigpotato

Reputation: 27507

SQL: Order first by table.column = 'matchingstring', then order everything else alphabetically?

I'm currently using MySQL and I want to order my book_versions records where the book_versions.name = 'paperback' show up first, and then the rest of the book_versions (book_versions.name != 'paperback') show. How would I accomplish this?

Upvotes: 0

Views: 58

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

order by case when book_versions.name = 'paperback' then 0 else 1 end,
         book_versions.name, -- remove this line if other names should not be ordered 
         book_versions.isbn 

See sqlFiddle to see the difference

in mysql, you can also use field

order by field(book_versions.name, 'paperback') DESC,
         book_versions.name ASC,
         book_versions.isbn ASC

Upvotes: 2

Shai
Shai

Reputation: 7317

Try:

ORDER BY
    CASE WHEN book_versions.name = 'paperback' THEN 0 ELSE 1 END, -- puts paperbacks first (because paperbacks cause this to =0, which is ordered before 1)
    book_versions.name                                            -- then order alphabetically

Upvotes: 1

Related Questions