开发者

SQL: Preserving order of return values

If I submit the following SQL statement to a database:

SELECT setting_value 
  FROM dba.system_settings 
 WHERE setting_name = 'RequestWebServiceURL' 
    OR setting_name = 'UNITS' 
    OR setting_name = 'FACTOR'

I get results in this order:

setting_value
---------------
www.requestURL 
1 
degrees

Even though I had specified "UNIT" before "FACTOR" in the SQL.

The table is, however, sorted by setting_name, which is why I got results in this order. May be a silly question but the order o开发者_开发知识库f the result based on the above query be preserved? Database in this case is Sybase.


The ANSI means would be to use a CASE expression in the ORDER BY clause:

  SELECT setting_value 
    FROM dba.system_settings 
   WHERE setting_name IN ('RequestWebServiceURL', 'UNITS', 'FACTOR')
ORDER BY CASE setting_name
           WHEN 'RequestWebServiceURL' THEN 1
           WHEN 'UNITS' THEN 2
           WHEN 'FACTOR' THEN 3
           ELSE 4
         END

An ORDER BY clause is the only means of guaranteeing result set order. Otherwise, you're likely to see insertion order.


SQL in general makes very little guarantees when it comes to the ordering of the results (when you don't explicitly request it), especially when indices are concerned.

If order is important to you, feel free to add a order by clause, for example on the primary key (that seems to be what you're trying to order on).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜