Sub topic 3
Reading and writing data with SQL
This chapter assumes you know what a table, primary key, and foreign key are, and that you can read short SQL snippets. The examples use the customers and orders tables from earlier chapters.
Writing and reading rows
SQL is the language you use to change and query a relational database. INSERT adds rows, SELECT reads them, and WHERE filters the rows that come back.
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
SELECT name, email
FROM customers
WHERE customer_id = 1;Combining tables with joins
A JOIN pairs rows from one table with matching rows in another. The ON clause names the columns that must match, usually a foreign key and the primary key it points to.
SELECT c.name, o.order_id, o.total_amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_date;Normalization: avoiding redundancy and update anomalies
Normalization means splitting data so that each fact is stored once. If a customer's email is copied into every order row, changing it means updating many rows. If you miss one, the data contradicts itself. That contradiction is an update anomaly. Keeping the email only in customers prevents it.
Transactions and ACID guarantees
A transaction groups several statements into one unit. Either all of them take effect, or none do. ACID stands for atomicity, consistency, isolation, and durability. Atomicity is the all-or-nothing rule. A transfer needs it: a debit without the matching credit loses money.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;Indexes and the cost of speed
An index is a separate structure that lets the database find rows by a column's value without scanning the whole table. An index on orders.customer_id speeds up lookups of one customer's orders. The trade-off is storage and write cost: each index takes space, and every INSERT, UPDATE, or DELETE must also update it. Index the columns you filter or join on often, not every column.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);Exercise
Why should a customer's email be stored only in the customers table?
Show answer
Storing it once means a change updates one row, so no copy can be missed and fall out of sync.