Javacadabra
Javacadabra

Reputation: 5768

Trying to Order DB Column Alphabetically using CASE

I have a database table that contains a number of fields that have a value of NULL for a specific column called category.

Currently I am executing this statement that returns a list of all the entries with NULL appearing at the end. However, for some reason it is not sorting them alphabetically and I'm wondering If someone can help me?

This is my script:

SELECT c.* FROM `directorycolumn` c
WHERE `c`.`directorycompany_id` = 740
ORDER BY CASE WHEN `category` IS NULL THEN 0 ELSE 1 END DESC

This outputs The category column with NULL values at the end but not in alphabetical order. I.e The first entry category begins with a T...but I have categories beginning with A.

Any help is much appreciated.

Upvotes: 0

Views: 37

Answers (1)

Siyual
Siyual

Reputation: 16917

Just add a second Order By clause:

SELECT c.* FROM `directorycolumn` c
WHERE `c`.`directorycompany_id` = 740
ORDER BY CASE WHEN `category` IS NULL THEN 0 ELSE 1 END DESC, `category` ASC

Upvotes: 2

Related Questions