MySQL : order by with null fields

Customize the sorting algorithm with COALESCE.

COALESCE is a SQL function taking a list of parameters and returning the first not null. If every parameter is null, null is returned.

You can use COALESCE in an ORDER BY to create different sorting methods according to the fact that a field might be empty.

Sort with empty fields

SELECT * FROM payment ORDER BY COALESCE (date_refund, date_debit, date_create) DESC -- OR SELECT COALESCE (date_refund, date_debit, date_create) AS last_operation_date, p.* FROM payment p ORDER BY last_operation_date DESC -- A field can be sorted by a specific value SELECT COALESCE( date_refund, IF(payment_method = "bank card", NULL, date_debit), date_create ) AS last_operation_date, p.* FROM payment p ORDER BY last_operation_date DESC