Benefits Of Using SQL Ordinal Position Notation?

瘦欲@ 提交于 2019-11-27 04:13:00

I'd use it:

  • If you love troubleshooting
  • Creating adhoc queries without intellisense

There is no upside.

SQL Server only supports in the ORDER BY anyway. Anywhere else it's an expression to be evaluated.

Often times when I'm querying a table with a lot of columns (in ad-hoc-land just for data exploration... I would never code like this for a PROD environment) I do something like this to get fields I care about close together:

select top 1000
  Col_1, Col_18, Col_50, Col_117, *
from
  TableWithTonsOfCols
order by
  1, 4 desc, 3

If I said order by Col_1, Col_117 desc, Col_50 my query would barf because the statement wouldn't know which columns I meant to order by due to the " * " doubling up. Not very common, but still a useful feature.

The two use cases for me are:

  • I am in a hurry and don't want to type, so I use the ordinal. I would always convert this to the column name for any non-temporary use
  • the column I am ordering by is a lengthy CASE statement; rather than retyping the CASE statement for the ORDER BY clause, I use the ordinal which keeps it DRY. There are ways around this, e.g., using CTEs, subqueries, or view, but I often find the ordinal is the simplest solution.

I tend to use in-line views now:

select col_a, count(*) from
  (select case ...... end col_a from ...)
group by col_a
order by col_a;

But in the days before they were valid syntax, it did help retyping the full text of the column. With tricky functions you had the potential for discrepancies between the value in the SELECT and ORDER BY such as

select ltrim(col_name,'0123456789')
from table
order by ltrim(col_name,'123456789')

The '0' in the SELECT means that you are not ordering by what you select.

I have a query generating algorithm - the SQL is auto generated. Using the ordinal means that I can refer to the generated field without having to fetch the field name again. The user can refer to the field name in a table by selecting it from a list on the screen. As long as I make the list correspond with the sql, I would never need to know field names, if the SELECT items were ordinal, too.

Memory says this used to be in the SQL standard in the late 1970's

If I recall correctly, the use of ordinals like you describe is being deprecated by Microsoft in a future release of SQL Server. I could be wrong on this, but I think that's the case. I've always liked using them in certain cases because it involves less typing when you're dealing with derived columns that contain a longish query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!