다음과 같이 변경하는 것이 좋습니다:
.order("COALESCE(CAST(custom_fields.value AS timestamp), custom_fields.value) DESC")
가독성을 높이기 위해서입니다.
sortDate 기준으로 정렬하고, 해당 값이 없으면 createdAt을 사용합니다. 모두 내림차순으로 정렬됩니다. 2020년이 2011년인 2등보다 “크기” 때문에 쿼리는 요청한 대로 데이터를 정확히 반환하고 있습니다.
null 값을 마지막에 배치하려면 다음이 필요합니다:
.order("CAST(custom_fields.value AS timestamp DESC NULLS LAST")