Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Turn many rows into summaries: totals, averages and counts per group.
CREATE TABLE sales (id INT AUTO_INCREMENT PRIMARY KEY, region VARCHAR(20), amount DECIMAL(8,2), sold_on DATE);
INSERT INTO sales (region, amount, sold_on) VALUES
('north', 100, '2026-01-05'), ('north', 250, '2026-02-10'),
('south', 80, '2026-01-20'), ('south', 40, '2026-03-02'), ('east', 500, '2026-03-15');SELECT COUNT(*) AS orders, SUM(amount) AS total, AVG(amount) AS average,
MIN(amount) AS smallest, MAX(amount) AS largest
FROM sales;SELECT region, COUNT(*) AS orders, SUM(amount) AS total
FROM sales
GROUP BY region
ORDER BY total DESC;WHERE filters rows before grouping. HAVING filters the groups after.
SELECT region, SUM(amount) AS total
FROM sales
GROUP BY region
HAVING SUM(amount) > 200;SELECT DATE_FORMAT(sold_on, '%Y-%m') AS month, SUM(amount) AS total
FROM sales
GROUP BY month
ORDER BY month;Every column in SELECT must either be in GROUP BY or inside an aggregate function.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.