Order by `updated_at` and `created_at` even if they are NULL
mysql, sql, sql-order-by
Solution
I believe what you want is:
ORDER BY coalesce(updated_at, created_at) DESC, id DESC
This orders by either the updated date (if available) or the created date (if it is not available). Then it orders by id descending.
Problem
I have the following table: ``` CREATE TABLE `entries` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; ``` I want to sort the entries by both `updated_at` and `created_at`. But either of them could be `NULL`. My query: ``` SELECT * FROM `entries` ORDER BY `updated_at` DESC, `created_at` DESC, `id` DESC ``` But this will put every entry which has not been updated at the bottom of the results. Basically I need them to be sorted by the last date available. And if there is none available to be sorted by `id`.