Part 12 / Topic 8 of 11
SQL basics
SQL (Structured Query Language) is the language you use to talk to a relational database. Keywords are usually written in CAPITALS (only a habit). -- starts a comment.
Think of SQL as filling in a request slip at the library counter: you say what you want, the librarian works out how to find it.
-- Create a table
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL, -- NOT NULL: this column must have a value
city TEXT NOT NULL
);
-- Add rows
INSERT INTO customers (id, name, city) VALUES (1, 'Asha', 'Pune');
-- Read rows: pick columns, filter with WHERE, sort with ORDER BY
SELECT name, city FROM customers WHERE city = 'Pune' ORDER BY name;
-- Asha | Pune
-- Meera | Pune
-- Change rows (WHERE picks which ones!)
UPDATE orders SET amount = 270 WHERE item = 'Thali';
-- Remove rows (WHERE again!)
DELETE FROM orders WHERE amount < 200;
⚠️
UPDATEorDELETEwithoutWHEREchanges every row in the table.
Aggregates turn many rows into one answer. GROUP BY makes one answer per group.
SELECT COUNT(*), SUM(amount) FROM orders;
-- 6 | 1510
SELECT item, COUNT(*) AS n, SUM(amount) AS total
FROM orders
GROUP BY item
ORDER BY total DESC;
-- Thali | 3 | 750
-- Biryani | 2 | 640
-- Dosa | 1 | 120
JOIN puts two tables side by side, matching rows with ON:
SELECT customers.name, SUM(orders.amount) AS spent
FROM customers
JOIN orders ON orders.customer_id = customers.id
GROUP BY customers.id
ORDER BY spent DESC;
-- Asha | 820
-- Ravi | 570
-- Meera | 120
| SQL | Does | Python cousin |
|---|---|---|
SELECT a, b FROM t |
Pick columns | [(r["a"], r["b"]) for r in rows] |
WHERE x > 5 |
Filter rows | if r["x"] > 5 |
ORDER BY x DESC |
Sort | sorted(..., reverse=True) |
LIMIT 3 |
First 3 only | [:3] |
COUNT(*), SUM(x), AVG(x), MIN, MAX |
One answer from many rows | len, sum, min, max |
GROUP BY city |
One answer per group | a dict of totals |
JOIN ... ON |
Combine two tables | look up a second dict by id |
🔍 Going deeper: a plain
JOIN(an inner join) drops customers with no orders.LEFT JOINkeeps them, withNULLfor the order columns.HAVINGfilters groups afterGROUP BY(e.g.HAVING SUM(amount) > 500).
Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.