您应该将其改为:
.order("COALESCE(CAST(custom_fields.value AS timestamp), custom_fields.value) DESC")
以提高可读性。
您按 sortDate 排序,如果该字段缺失,则使用 createdAt。所有排序均为降序。查询返回的数据完全符合您的要求,因为 2020 年“大于”第二名的 2011 年。
如果您希望空值排在最后,需要:
.order("CAST(custom_fields.value AS timestamp) DESC NULLS LAST")