- Phase: 9. Databases & Web Apps
- Duration: 2 hours
- Write SQL queries with WHERE, ORDER BY, GROUP BY, HAVING, and JOIN
- Use aggregate functions: COUNT, SUM, AVG, MAX, MIN
- Execute SQL from Python with sqlite3
- Fetch results with fetchone, fetchall, fetchmany
- Use row factories for dict-like access
- SELECT with WHERE clause
- ORDER BY for sorting
- GROUP BY and HAVING for aggregation
- INNER JOIN and LEFT JOIN
- Aggregate functions (COUNT, SUM, AVG, MAX, MIN)
- Executing SQL from Python with sqlite3
- Fetching results: fetchone, fetchall, fetchmany
- Row factories for dict-like access
Modules 000-082.
import sqlite3
conn = sqlite3.connect('store.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT category, COUNT(*) as count, AVG(price) as avg_price
FROM products
WHERE price > ?
GROUP BY category
HAVING count > 1
ORDER BY avg_price DESC
''', (10.0,))
for row in cursor.fetchall():
print(row['category'], row['count'], row['avg_price'])
conn.close()- SQLite documentation: https://sqlite.org/lang.html
- SQL Tutorial (W3Schools)
- Mode Analytics SQL Tutorial