tags:

views:

160

answers:

4

Ffor testing purposes I need to write a SQL query which contains the actual record number as a column in the result set. If my SELECT gets back to me with 10 records as the result, I need to have one column which contains the values 1-10.

Is there a way to achieve this without a stored procedure cursoring through my data?

EDIT: I need this on postgresql.

+5  A: 

Have a look at ROW_NUMBER() (SQL Server 2005 and above)

Cade Roux
+6  A: 

You could partition your data and get a row_number()

For example:

SELECT FirstName, LastName, SalesYTD, PostalCode, 
       ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS 'Row Number'
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;

See the following: ROW_NUMBER (Transact-SQL)

Jason Irwin
The good thing about this solution is it will work for any RDBMS that is written to the ISO SQL:2003 standard.
sheepsimulator
+1  A: 

For postgresql see: Simulating Row Number in PostgreSQL Pre 8.4

Jason Irwin
thx, knew about this one. just hoped that there would be an easier way. thx anyways.
KB22
+1  A: 

If you're on 8.4, you can use window functions (row_number() to be exact).

If you're on pre 8.4, you can use the technique I described some time ago on my blog.

depesz