all groups > sql server new users > january 2005 >
You're in the

sql server new users

group:

Using the ORDER BY clause


Using the ORDER BY clause Amit
1/23/2005 1:43:03 PM
sql server new users:
This is for the Northwind database:

select count(customerId), country
from customers
group by country
order by 1+3

How come this works? What does it mean to include an arithmetic operation in
the Order By clause?
Thanks
Amit

Re: Using the ORDER BY clause Greg Low [MVP]
1/24/2005 10:19:43 AM
Hi Amit,

You can specify columns in the order by clause by number but most would
never consider it good practice. Use the column names instead.

HTH,

--
Greg Low [MVP]
MSDE Manager SQL Tools
www.whitebearconsulting.com

[quoted text, click to view]

Re: Using the ORDER BY clause Amit
1/24/2005 12:56:05 PM
Hi,
But if you see the "order by" clause, I'm not specifying "order by 1,3"
which I understand, that would be ok (although not in this particular
example because I only have two columns in the select list). I'm actually
giving it an arithmetic operation (1+3) and it still doesn't complain.
Thanks
Amit


[quoted text, click to view]

Re: Using the ORDER BY clause Steve Kass
1/26/2005 3:44:16 PM
Amit,

As far as I can tell, ORDER BY 1+3 will order the result set
by the value of the number 4. Rows with the smallest value
of 4 will appear first, and rows with the largest value of 4 will
appear last. ;)

The optimizer is able to recognize that 1+3 is constant,
and there is no sort in the query plan (in the cases I checked).
On the other hand, the optimizer does include a sort for
other constant expressions, such as ORDER BY PI() and
ORDER BY SIN(1), even though the query plan refers to
these values as ConstExpr instead of Expr.

Steve Kass
Drew University

[quoted text, click to view]
AddThis Social Bookmark Button