tags:

views:

107

answers:

6

I'm reading through some old code at work, and have noticed that there are several views with an order by 1 clause. What does this accomplish?

Example:

Create view v_payment_summary AS
SELECT A.PAYMENT_DATE,
       (SELECT SUM(paymentamount)
          FROM payment B
         WHERE = PAYMENT_DATE = B.PAYMENT_DATE
           and SOME CONDITION) AS SUM_X,
       (SELECT SUM(paymentamount)
          FROM payment B
         WHERE = PAYMENT_DATE = B.PAYMENT_DATE
           and SOME OTHER CONDITION) AS SUM_Y    
FROM payment A    
ORDER BY 1;
+2  A: 

I believe in Oracle it means order by column #1

Christopherous 5000
+2  A: 

This will sort your results by the first column returned. In the example it will sort by payment_date.

CTKeane
+6  A: 

This:

ORDER BY 1

...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:

ORDER BY A.PAYMENT_DATE

It's not a recommended practice, because:

  1. It's not obvious/explicit
  2. If the column order changes, the query is still valid so you risk ordering by something you didn't intend
OMG Ponies
My question asking if there was an upside to using Ordinals: http://stackoverflow.com/questions/2253040/benefits-of-using-sql-ordinal-position-notation
OMG Ponies
This only has the `sql` tag. In Standard SQL only column correlation names are allowed in the `OREDER BY` clause because, in theory, the table correlation names are out of scope i.e. should be `ORDER BY PAYMENT_DATE;`. Of course, not all SQL implementations conform to Standards.
onedaywhen
A: 

Also see:

http://www.techonthenet.com/sql/order_by.php

For a description of order by. I learned something! :)

I've also used this in the past when I wanted to add an indeterminate number of filters to a sql statement. Sloppy I know, but it worked. :P

kdmurray
+1  A: 
daven11
Aha, that makes sense. This is the first good reason I've seen so far.
echo