Database Project Queries, Indexes and Rules
What you will learn
- How to turn each question into a query
- How to use a view for a question you ask often
- How to add an index and see the plan change
- How to check deletes against the foreign keys
1. Setup
This lesson uses the tables and data from lesson 15.2. The sample data has three customers, three garments, three orders and four order items. Setup (the same tables and data as in lesson 15.2, so this lesson runs on its own):
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
phone TEXT NOT NULL UNIQUE
);
CREATE TABLE garments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
price INTEGER NOT NULL CHECK (price > 0)
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
ordered_on TEXT NOT NULL,
due_on TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'sewing', 'ready', 'collected')),
CHECK (due_on >= ordered_on)
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
garment_id INTEGER NOT NULL REFERENCES garments(id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price INTEGER NOT NULL CHECK (unit_price > 0),
PRIMARY KEY (order_id, garment_id)
);
""")
con.executescript("""
INSERT INTO customers VALUES (1,'Rina Akter','01711000001'),(2,'Sam Roy','01711000002'),(3,'Lee Khan','01711000003');
INSERT INTO garments VALUES (1,'Shirt',800),(2,'Trousers',1000),(3,'Panjabi',1500);
INSERT INTO orders VALUES (1,1,'2026-03-01','2026-03-10','sewing'),(2,1,'2026-03-05','2026-03-15','new'),(3,2,'2026-03-02','2026-03-09','ready');
INSERT INTO order_items VALUES (1,1,2,800),(1,2,1,1000),(2,3,1,1500),(3,1,1,750);
""")
2. The five questions
Q1. Which orders are not collected yet, soonest due first?
print(con.execute("SELECT c.name, o.id, o.due_on FROM orders o JOIN customers c ON c.id = o.customer_id WHERE o.status <> 'collected' ORDER BY o.due_on").fetchall())
[('Sam Roy', 3, '2026-03-09'), ('Rina Akter', 1, '2026-03-10'), ('Rina Akter', 2, '2026-03-15')]
Q2. What is the total of each order?
print(con.execute("SELECT o.id, SUM(i.quantity * i.unit_price) FROM orders o JOIN order_items i ON i.order_id = o.id GROUP BY o.id ORDER BY o.id").fetchall())
[(1, 2600), (2, 1500), (3, 750)]
Order 1: 2 shirts at 800 plus 1 trousers at 1000 is 2600. The total uses the price stored on the item, not the garment's current price.
Q3. What has each customer ordered in total, including customers with no orders?
print(con.execute("""SELECT c.name, COUNT(DISTINCT o.id), SUM(i.quantity * i.unit_price)
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
LEFT JOIN order_items i ON i.order_id = o.id
GROUP BY c.id ORDER BY c.id""").fetchall())
[('Rina Akter', 2, 4100), ('Sam Roy', 1, 750), ('Lee Khan', 0, None)]
LEFT JOIN keeps Lee, who has no orders; his total is None (SQL NULL), not 0, because there was nothing to add. A report could show it as 0 with COALESCE(SUM(...), 0).
Q4. Which garment is ordered most?
print(con.execute("SELECT g.name, SUM(i.quantity) FROM garments g JOIN order_items i ON i.garment_id = g.id GROUP BY g.id ORDER BY SUM(i.quantity) DESC, g.name").fetchall())
[('Shirt', 3), ('Panjabi', 1), ('Trousers', 1)]
Q5. Which customers have never ordered?
print(con.execute("SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders)").fetchall())
[('Lee Khan',)]
All five questions are answered from the four tables, as planned in lesson 15.1.
A warning about Q5: NOT IN gives a surprising empty result if the subquery returns any NULL. That cannot happen here because orders.customer_id is NOT NULL, but NOT EXISTS is the safer habit. On a small test with a NULL in the list (a holds 1 and 2, b holds 1 and NULL), NOT IN returned [] while NOT EXISTS returned [(2,)].
3. A view
Q1 is something the owner asks every morning. A view saves it under a name (lesson 4.7):
con.execute("""CREATE VIEW open_orders AS
SELECT o.id, c.name, o.due_on, o.status
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.status <> 'collected'""")
print(con.execute("SELECT * FROM open_orders ORDER BY due_on").fetchall())
[(3, 'Sam Roy', '2026-03-09', 'ready'), (1, 'Rina Akter', '2026-03-10', 'sewing'), (2, 'Rina Akter', '2026-03-15', 'new')]
4. An index
Finding all orders of one customer is a common need. Ask SQLite how it will run the query, before and after adding an index (lessons 7.3 and 7.6):
plan = "EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 1"
print(con.execute(plan).fetchall()[0][3])
con.execute("CREATE INDEX idx_orders_customer ON orders(customer_id)")
print(con.execute(plan).fetchall()[0][3])
SCAN orders
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
Before: SCAN reads every order. After: SEARCH ... USING INDEX jumps straight to the customer's orders. With three orders it makes no real difference; with thousands it does. Foreign key columns are good candidates for indexes because joins and lookups use them constantly.
5. Changes and deletes
con.execute("UPDATE orders SET status = 'collected' WHERE id = 3")
con.commit()
print(con.execute("SELECT status FROM orders WHERE id = 3").fetchone())
con.execute("DELETE FROM orders WHERE id = 1")
print(con.execute("SELECT COUNT(*) FROM order_items WHERE order_id = 1").fetchone())
try:
con.execute("DELETE FROM customers WHERE id = 1")
except sqlite3.IntegrityError as e:
print("refused:", e)
('collected',)
(0,)
refused: FOREIGN KEY constraint failed
- Order 3 is now
collected, andcommit()made the change permanent. - Deleting order 1 also removed its items (the count is 0), thanks to
ON DELETE CASCADE. - Deleting customer 1 was refused because order 2 still belongs to Rina. The database protects the link.
Worked example: check the design against the requirements
| Requirement | Evidence |
|---|---|
| R1 unique phone | refused duplicate phone (15.2) |
| R3 status values | refused status lost (15.2) |
| R5 price at ordering | order 3 totals 750 although a shirt now costs 800 (Q2) |
| R6 due date | refused due date before order date (15.2) |
| Q1 to Q5 | all answered (this lesson) |
If a requirement had no evidence, the design would not be finished.
Common mistakes
- Using
JOINwhereLEFT JOINis needed, losing customers with no orders. - Forgetting that
SUMof nothing isNULL, not 0. - Indexing every column. Index what you search and join on (lesson 7.4).
- Deleting in an order that breaks links, or using
CASCADEwithout thinking about what disappears.
Key takeaways
- Turn each listed question into a query and keep the result as proof.
- A view gives a repeated question a name.
- An index on a searched column changes the plan from
SCANtoSEARCH. - Foreign keys and cascades decide what a delete does; test them.
- Finish by matching every requirement to evidence.
Practice
1. Why is Lee's total None in Q3?
Show answer
He has no orders, so SUM had no values to add and returns NULL.
2. Why does Q2 use unit_price from order_items and not garments.price?
Show answer
To use the price at the time of ordering, as requirement R5 says.
3. Write a query for orders due before 2026-03-12 that are not collected.
Show answer
SELECT id, due_on FROM orders WHERE status <> 'collected' AND due_on < '2026-03-12'
4. What changed in the query plan after the index was created?
Show answer
SCAN orders became SEARCH orders USING INDEX idx_orders_customer.
5. Why was deleting customer 1 refused?
Show answer
Order 2 still refers to that customer, and no cascade is defined on that link.
6. If Q3 used JOIN instead of LEFT JOIN, which customer would disappear from the answer, and why?
Show answer
Lee Khan. A plain JOIN keeps only rows that have a match on both sides, and Lee has no orders, so he has no matching row.