PDA

View Full Version : Order By Null First


isleshocky77
11-20-2005, 11:33 AM
Does anyone know of a way to sort by a datetime type field desc, but have nulls show first?

Statement currently looks like this:
SELECT * FROM $tables[portfolio] ORDER BY `date_completed` DESC

But the NULL Fields are last in the sort.

I'm editing this incase anyone in future searches this and needs it.
The following code will do the trick.

(
SELECT *
FROM `$tables[portfolio]`
WHERE `date_completed` IS NULL
ORDER BY `title`
)
UNION ALL
(
SELECT *
FROM `$tables[portfolio]`
WHERE `date_completed` IS NOT NULL
ORDER BY `date_completed` DESC, `title`
)

Kid Charming
11-23-2005, 08:09 PM
Here's another option that might be faster:


SELECT
*
FROM
`$tables[portfolio]`
ORDER BY
CASE
WHEN date_completed IS NULL THEN 0
ELSE 1
END
,title