views:

34

answers:

2

I want to number the rows in my result set. I want some way I can have a result set of 3 records use some SQL keyword to generate a column that would read 1,2,3 for watch of the records...

I know I can make a temp table with an auto increment column but i wanted to know if there was a way I can get this back from a SQL query?

SELECT row_count, 
       project_name, 
       project_id 
  FROM Project 

anything available like "row_count" that i am dreaming of?

+2  A: 

Sounds like you want ROW_NUMBER, an analytic/ranking function. But it's unclear what you want to base the numbering on - this assumes the project_id, starting at the smallest value:

SELECT ROW_NUMBER() OVER(ORDER BY p.project_id) AS row_count,
       p.project_name,
       p.project_id
  FROM PROJECT p
OMG Ponies
ui want it to start at 1 and increase by 1 for each row in teh dataset of the select.
kacalapy
@kacalapy: That's what ROW_NUMBER does, but you can specific what that numbering is based on.
OMG Ponies
+5  A: 

Ordering by SELECT 0 will give you an incrementing column and saves a potentially unnecessary sort.

SELECT ROW_NUMBER() over (order by (select 0)) as row_count, 
       project_name, 
       project_id 
  FROM Project 
Martin Smith
+1: So what does the ROW_NUMBER value order by when using `SELECT 0`? It not arbitrary/random, right?
OMG Ponies
@OMG - The compute scalar operator before the segment iterator in the execution plan just passes in the value `0` as the SegmentColumn rather than a specific column value. But the segment iterator requires its input to be sorted by the SegmentColumn so using a constant allows the sort step to be skipped. (or gives it the freedom to choose a different access path such as a covering non clustered index sorted on a different column)
Martin Smith
So the number will be based on record insertion order?
OMG Ponies
In the order the results appear in the result of the `select` statement.
Martin Smith
@OMG - By the way a really good article describing what the Segment Iterator does and how the analytic functions are implemented is here http://sqlblog.com/blogs/paul_white/archive/2010/07/28/the-segment-and-sequence-project-iterators.aspx
Martin Smith