Editor

Predict the Query Result

Intermediate · Predict the output · from Python SQLite: Build and Query Databases Without a Server

From the lesson: Python SQLite: Build and Query Databases Without a Server

Every app needs to store data somewhere. A to-do list needs to remember your tasks. A contacts app needs to save names and phone numbers. You could write everything to a text file, but what happens when you need to find all contacts in a specific city, or delete tasks older than a week?

Read the lesson

What will this code print? Think about what UPDATE does and how the final SELECT will return the data.

import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('CREATE TABLE scores (name TEXT, points INTEGER)')
cursor.executemany('INSERT INTO scores VALUES (?, ?)', [
('Alice', 10), ('Bob', 20), ('Alice', 30),
])
cursor.execute('UPDATE scores SET points = points + 5 WHERE name = ?', ('Alice',))
conn.commit()
cursor.execute('SELECT name, points FROM scores ORDER BY points')
for row in cursor.fetchall():
print(f'{row[0]}: {row[1]}')
conn.close()

More SQLite exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz