2

I have a table in my database in Access 2013.

Table : city

ID_city city
1       Tetuan
5       Rabat
9       Marrakech
10      Agadir
15      Laayoun

I wish to add the Rowid number beside them:

Rowid   ID_city city
1       1       Tetuan
2       5       Rabat
3       9       Marrakech
4       10      Agadir
5       15      Laayoun
1

4 Answers 4

3

One way to do this is to use the count function in a subquery. Not sure it scales well though and there are probably better ways...

select 
    (select count(*) from city where ID_city <= t1.ID_city) as row_number,
    *
from city t1
Sign up to request clarification or add additional context in comments.

1 Comment

Could be a problem if the results are orderd by city
1

The best way to do it is by using a self-join...

    SELECT
    COUNT(*) AS Rowid,
    C.ID_City,
    C.city
    FROM City C
    INNER JOIN City C1 ON C.ID_City >= C1.ID_City
    GROUP By C.ID_City, C.city

Comments

0

A little VBA goes a long way...

'Module level variables; values will persist between function calls
'To reset the row number, you have to explicitly call Reset
Dim lastValue As Integer

Public Function RowNumber(x) As Integer
    'We need this parameter so Access will call the function on each row, instead of only once
    lastValue = lastValue +1
    RowNumber = lastValue
End Function

Public Sub Reset()
    lastValue = 0
End Sub

SQL statement:

SELECT RowNumber(city) AS RowID, *
FROM City

5 Comments

This will not work if you plan on using the query results as the basis of a form, or in datasheet view. Any scrolling around, or changing records changes the row numbers.
@Montclair True, although IIRC it's possible to set the form/datasheet to perform only a single pass through the data. (I haven't used Access in a while now.)
Never heard of that. Perhaps it's in the newer versions. I primarily use a very old version.
@Montclair Queries and forms both have a RecordsetType property, which can be set to Snapshot; this allows only a single pass through the data. I think it also has the effect I described.
I am aware of snapshots and use them for various things. I'm not sure a snapshot would react the way you expect though, but we can assume you're correct. For whomever else cares, though, snapshots are read-only recordsets. You can't make any data changes.
-2

another option: (http://www.openwinforms.com/row_number_to_sql_select.html)

  SELECT ROW_NUMBER() 
  OVER (ORDER BY ID_city) AS Rowid, 
  ID_City, city
  FROM city

1 Comment

ROW_NUMBER() and OVER are not supported in Access SQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.