0

I'm trying to add a column to my MySQL database that contains the row number of the entry. I'm adding the data using a python script, and have been unsuccessful in doing so. I learnt about the ROW_NUMBER() MySQL function but haven't been able to use it successfully. Should I be using this function? Is there a way I can achieve this without retrieving the number of rows in the table first?

Thanks!

6
  • but haven't been able to use it successfully Show your attempts nevertheless. Commented Sep 28, 2021 at 12:33
  • I tried using the ROW_NUMBER() function in my python script and it didn't work? Commented Sep 28, 2021 at 12:43
  • ROW_NUMBER() is MySQL function, not python one, it cannot be applied in python. Commented Sep 28, 2021 at 12:44
  • Ok. Do you have a solution? Commented Sep 28, 2021 at 12:48
  • is there a library I can import the function from? Commented Sep 28, 2021 at 13:10

1 Answer 1

2

Two options:

Do it yourself in Python:

cursor = cnx.cursor(dictionary=True)
result = cursor.execute("SELECT ... FROM MyTable")

rownum = 0
for row in cursor:
    row['rownum'] = rownum
    rownum += 1
    print(row)

cnx.close()

Or use the MySQL ROW_NUMBER() window function (provided you are using at least MySQL 8.0, because earlier versions don't support the window functions).

cursor = cnx.cursor()
result = cursor.execute("SELECT ROW_NUMBER() OVER() AS rownum, ... FROM MyTable")

for row in cursor:
    print(row)

cnx.close()
Sign up to request clarification or add additional context in comments.

Comments

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.