Lesson 2 of 5 · 2 min
Grouping and filtering groups
where filters rows before grouping. having filters the groups afterwards. Mixing them up is the most common beginner mistake.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("create table calls (user text, tokens int)")
db.executemany("insert into calls values (?, ?)", [("a", 900), ("a", 400), ("b", 100), ("c", 2000), ("b", 50)])
query = """
select user, count(*) as calls, sum(tokens) as total
from calls
group by user
having sum(tokens) > 500
order by total desc
"""
for row in db.execute(query):
print(row)
