使用 SQL Order By 和 null 的 DBMS 之间的行为一致
我的数据库中有一个类型为 varchar(1) 的列(一个标志),该列填充为 Y 或 NULL(不在我的控制范围内)。
在SQL Server中,按查询进行升序排列,NULL排在最前面。
SQL Server 的这种行为与 Oracle 和 DB2 一致吗?
相反,如果我在列上进行 COALESCE 以确保它在查询中不为空,那么我可能会遇到哪些性能问题(由于表扫描等)?
查询需要在所有 3 个数据库中保持一致,否则我将不得不在代码中处理它,因此我考虑使用 COALESCE 函数。
I have a column in my database (a flag) with type varchar(1) that is populated either Y or NULL (not in my control).
In SQL Server, doing an ascending order by query, NULL is ordered at the top.
Is this SQL Server behaviour consistent with Oracle and DB2?
If, instead, I have a COALESCE on the column to ensure it is not null in the query, what performance issues (due to table scans and the like) could I hit?
The query needs to be consistent over all 3 databases, otherwise I will have to handle it in code, hence my thinking of using the COALESCE function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道 DB2 Express 和 DB2(至少到 v8)不支持
NULLS FIRST
子句。如果您想要一个可移植的解决方案,您可能必须选择以下内容:
我认为联合的结果(至少在 DB2 中,您需要检查其他结果)保证被正确排序。
由于您正在为返回的每一行运行一个函数,因此合并将会对性能产生影响。 但是,这取决于数据库中的行数。
您很可能不得不在代码中对两个不同的记录集进行两次查询,然后按顺序处理它们。
编辑:我刚刚检查了 SQL 标准,并不能保证使用
UNION ALL
连接的查询是有序的; 它们可能是混合的。 因此,您可能必须求助于运行上面提到的两个不同查询的代码。I know for a fact that DB2 Express and DB2 (at least up to v8) does not support the
NULLS FIRST
clause.If you want a portable solution, you may have to opt for something like:
I think the result of the union (at least in DB2, you'll need to check the others) is guaranteed to be ordered correctly.
The coalesce will have performance implications since you're running a function for every row returned. However, it depends on the number of rows in the database.
You may well have to resort to doing two queries in code into two different record sets, then processing them in order.
EDIT: I've just checked the SQL standard and it's not guaranteed that the queries joined with a
UNION ALL
are sequenced; they might be inter-mixed. So it looks like you may have to resort to code running two different queries as mentioned above.显然这是该标准的一个相对较新的成员。
Apparently this is a relative newcomer to the standard.
在 oracle 中你可以这样做:
或者
在 SQL Server 中尝试一下
In oracle you can do this:
or
Try it in SQL Server