在 order by 中依赖空值的顺序是否安全?

Is it safe to rely on the order of null values in an order by?

我刚刚看到这段代码,在我看来它有点脆弱:

String statement = "select * from SOURCE where category = ? order by sub_category desc";
...
List<Source> results = query.list();

/* If we get more than one result return the one with the null sub-category 
 (the 'order by' should make the first record the one with the null): */
if(results.size() > 0) {
    return results.get(0);
}else{
    return null;
}

反正我是要重构的,但是我的好奇心被点燃了!

依赖 order by 子句中空值的排序是否安全?订购数据库是特定的还是独立于供应商的共识?

空值的排序是特定于数据库的。比方说,MSSQL 将空值视为 'less than any other value',因此空值将在 ASC 排序中排在第一位,而在 DESC 排序中排在最后。 Oracle 默认将空值视为 'greater than any other value',但它有特殊的语法,ORDER BY column ASC|DESC NULLS FIRST|LAST,因此开发人员可以明确地将空值放入所需位置。等等。