SQLite Update
Update Rows
Use the UPDATE statement to change data in a table. SET tells which column to change, and WHERE tells which rows to change.
The examples on this page use this players table:
| name | score |
|---|---|
| Emil | 120 |
| Tobias | 95 |
| Linus | 150 |
| Lene | 80 |
To keep the examples short, they show only the code for the UPDATE statement. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Example
Change the score of Tobias to 130:
cur.execute("""
UPDATE players
SET score = 130
WHERE name = 'Tobias'
""")
con.commit()
Try it Yourself »
Warning: Remember the WHERE part. Without WHERE, all the rows are updated!
Update With Variables
Use ? placeholders for values from variables:
Example
Use the values in the variables name and score:
name = "Tobias"
score = 130
sql = """
UPDATE players
SET score = ?
WHERE name = ?
"""
cur.execute(sql, (score, name))
con.commit()
Try it Yourself »
The values are used in order: the first ? gets score, and the second ? gets name.
Add to a Value
You can use the old value of a column to calculate the new value:
Example
Give Lene 10 more points:
cur.execute("""
UPDATE players
SET score = score + 10
WHERE name = 'Lene'
""")
con.commit()
Try it Yourself »
How Many Rows Were Changed?
After an UPDATE, cur.rowcount tells how many rows were changed:
Example
Give 10 more points to all players with less than 100:
cur.execute("""
UPDATE players
SET score = score + 10
WHERE score < 100
""")
con.commit()
print(cur.rowcount, "rows updated")
Try it Yourself »
Tobias and Lene had less than 100 points, so two rows were updated.