Databases and SQL
Last updated
Shops, banks and apps keep their data in databases, and you ask a database questions in SQL. In this lesson you'll write SELECT, WHERE, GROUP BY and JOIN, run them from Python with sqlite3 and read_sql, see each clause's pandas twin, and learn the one rule that keeps a query safe: never paste text into SQL.
By the end of this lesson you can
- Query a table with
SELECT,WHERE,GROUP BY,ORDER BYandJOIN - Run SQL from Python and get a DataFrame back with
pd.read_sql - Match each SQL clause to the pandas code that does the same job
- Pass values with parameters, never by pasting them into the query
Tables and queries
A database keeps data in tables, like DataFrames that live on disk and can be shared by many programs at once. A shop's till writes each sale into one; you read from it. SQL (often said "sequel") is the language for asking a database questions, and nearly every database speaks it.
SQLite is a small database that's a single file, and it comes with Python as sqlite3. The first cell loads the Stage 4 sales and stores into one, in memory, then the rest ask it questions. Run them.
Reading the queries:
SELECT store, kilos FROM sales: which columns, from which table.SELECT *means every column.WHERE item = 'rice' AND kilos > 32: which rows. Text goes in single quotes.SUM(kilos) AS totalwithGROUP BY store: one row per store, with a name for the new column.ORDER BY total DESC: sorted, biggest first.JOIN stores AS t ON s.store = t.store: a join, likemerge(lesson 4.3).sandtare short names for the two tables.
pd.read_sql(query, con) runs a query and gives you the answer as a DataFrame. con is the connection, from sqlite3.connect. On your computer you'd connect to a file, sqlite3.connect("data/raw/tindahan.db"), and the last cell shows the same answer in pandas.
A good habit: let the database do the filtering and grouping, and bring only the answer into pandas. A database can search a table far bigger than your memory.
SQL and pandas, side by side
Every clause has a pandas twin. Step through them:
Notice the order. SQL is written SELECT … FROM … WHERE … GROUP BY, but it runs FROM, WHERE, GROUP BY, SELECT, ORDER BY, the same order as the pandas chain. That's why, in most databases, WHERE can't use a name made in SELECT but ORDER BY can.
Other databases (PostgreSQL, MySQL, SQL Server) need a library to connect, but pd.read_sql works the same way with each.
Wrong way: pasting text into SQL
A small web page lets staff type a store name and see its sales. The code builds the query with an f-string. Run the cells.
With Lipa, four rows, as intended. Then someone types x' OR '1'='1. The f-string pastes it in, and the printed query shows what happened: the quote closes the text early, and OR '1'='1' is true for every row. All 12 rows come back, for every store. With a different string, someone could change or delete tables. This is SQL injection, one of the most common security holes on the web (Simple Cybersecurity covers it in its lesson on attacks on websites and apps).
The fix is parameters: write ? where the value goes, and pass the value separately with params=. The database treats it as a value, never as SQL. The whole string x' OR '1'='1 is compared with each store name, matches nothing, and gives 0 rows; Lipa still gives 4.
The rule: never put a value into SQL with +, % or an f-string, even when you think the value is safe. Always use params.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Standard Library: sqlite3: connections, queries and placeholders
- pandas: pandas.read_sql: a query's result as a DataFrame, with params
- SQLite: The SELECT statement: every clause, and the order they run in
- OWASP: SQL Injection Prevention Cheat Sheet: why parameters are the defence