Python SQLite: How to UPDATE Records in a Table

Last updated 1 month, 4 weeks ago | 149 views 75     5

Tags:- Python SQLite

Updating existing data in your SQLite database is a common and essential task when building applications. The SQL UPDATE statement allows you to modify existing records in a table. When combined with Python’s sqlite3 module, you can perform updates safely and efficiently.

In this article, you'll learn:

  • How to use UPDATE with Python and SQLite

  • How to update specific columns or all columns

  • How to avoid unintentional updates

  • Tips, best practices, and common mistakes


✅ Prerequisites

Make sure you have:

  • Python 3.x installed

  • SQLite database (e.g., example.db)

  • A sample table like this:

CREATE TABLE Users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    age INTEGER
);

Sample data:

(1, 'Alice', '[email protected]', 30)
(2, 'Bob', '[email protected]', 25)
(3, 'Charlie', '[email protected]', 35)

Step 1: Connect to SQLite Database

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

Step 2: Update a Record

Let’s say you want to update Bob’s age to 28:

cursor.execute("UPDATE Users SET age = ? WHERE name = ?", (28, "Bob"))
conn.commit()

Explanation:

  • SET specifies which column to change and its new value

  • WHERE ensures only Bob’s record is updated

  • Always use parameterized queries to prevent SQL injection


Step 3: Update Multiple Columns

You can update multiple fields at once:

cursor.execute("UPDATE Users SET name = ?, age = ? WHERE id = ?", ("Bobby", 29, 2))
conn.commit()

Step 4: Verify the Update

After updating, use a SELECT query to confirm the changes:

cursor.execute("SELECT * FROM Users WHERE id = 2")
print(cursor.fetchone())

⚠️ Step 5: Update Without WHERE (Danger!)

cursor.execute("UPDATE Users SET age = 100")
conn.commit()

This updates the age column for all rows!
Never omit WHERE unless you're intentionally updating every record.


Full Working Example

import sqlite3

# Connect to the database
conn = sqlite3.connect("example.db")
cursor = conn.cursor()

# Update user's age by name
cursor.execute("UPDATE Users SET age = ? WHERE name = ?", (32, "Alice"))
conn.commit()

# Verify the update
cursor.execute("SELECT * FROM Users WHERE name = ?", ("Alice",))
user = cursor.fetchone()
print("Updated user:", user)

conn.close()

Tips for Using UPDATE Safely

Tip Why It’s Useful
✅ Always use WHERE clause Prevents unintended updates
✅ Use ? placeholders Protects against SQL injection
✅ Commit after updating Saves changes to the database
✅ Use SELECT before and after Helps confirm the logic is correct

⚠️ Common Pitfalls

Problem Cause Solution
All rows updated Missing WHERE clause Always double-check your condition
Changes not saved Missing conn.commit() Remember to commit after updates
Record not updated Incorrect WHERE clause Debug your filter with SELECT
SQL injection risk Concatenated strings in query Use parameterized queries

Best Practices

  • Use transactions (BEGIN, COMMIT, ROLLBACK) when doing multiple updates

  • Log your update queries for auditing

  • Use updated_at columns with timestamps to track changes

  • Validate data before updating it in production systems


Conclusion

The UPDATE statement in SQLite is a powerful tool that lets you modify data in-place. Whether you’re correcting a typo or adjusting business data, it's a common and critical operation.

Using Python’s sqlite3 module makes it easy to perform updates safely, as long as you follow best practices like using parameterized queries and WHERE conditions.