How can I create a column in a SQL Server query that works as a counter

Hi Experts,
I am using a SELECT query in SQL SERVER 2008 R2.  I want to add a column to my select query that will simply provide me a running record count, incremented by 1 for each row.

How could I do this?

Thanks in advance,
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun KlineLead Software EngineerCommented:
Take a look at the ROW_NUMBER() function:
Andrew CalhounSystems EngineerCommented:
Putting a column in the table itself to keep track of rowcount doesn't make sense, if that is what you are asking for. If that is what you are asking for, imagine deleting a row from the middle of the table. Are you going to go back in and alter the value of the count column for all rows that were added after the one you just deleted, in order to keep them accurate?

Instead, any time you need the number of rows in the table, use a query like below.
replace the word tablename with the actual name of the table that you are getting the row count on (but keep the single quotes).

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('tablename')  
AND (index_id=0 or index_id=1);
Vitor MontalvãoMSSQL Senior EngineerCommented:
You'll need to define the column that you want the data to be sorted and numbered:
	Column1, Column2, ..., ColumnN
FROM TableName
WHERE <YourCriteria>

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.