Home / Learn React / Relations, JOIN, Indexes and Transactions
Relations, JOIN, Indexes and Transactions
Real apps have more than one table. A foreign key links them and JOIN reads them together.
Theory in plain words
What it is
A relation links two tables by a key. The notes table stores user_id, which is the id of a row in the users table.
Why we use it
Storing the user email in every note repeats data and breaks when the email changes. Storing only the id keeps one truth and lets the database block impossible links.
How it works
JOIN ... ON notes.user_id = users.id lines up the matching rows. An INDEX is a sorted lookup structure on a column. A transaction wraps statements in START TRANSACTION and COMMIT.
Where it is used
- Users and their notes, orders and their items, posts and comments
- Reports with totals per user
- Money or stock changes that must never be half done
Foreign key
CREATE DATABASE IF NOT EXISTS notesapp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE notesapp;
CREATE TABLE users (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(190) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
CREATE TABLE notes (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NULL,
title VARCHAR(200) NOT NULL,
done TINYINT(1) NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_notes_user (user_id),
CONSTRAINT fk_notes_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB;ON DELETE CASCADE means deleting a user also deletes their notes. Use SET NULL if you want to keep the notes.
JOIN
-- every note with its author email
SELECT notes.id, notes.title, users.email
FROM notes
INNER JOIN users ON users.id = notes.user_id;
-- every user, even those with zero notes
SELECT users.email, COUNT(notes.id) AS total
FROM users
LEFT JOIN notes ON notes.user_id = users.id
GROUP BY users.id, users.email;| users.email | total |
|---|---|
| asha@example.com | 3 |
| ravi@example.com | 0 |
| JOIN type | Keeps |
|---|---|
| INNER JOIN | only rows that match in both tables |
| LEFT JOIN | all rows from the left table, NULL when nothing matches |
| RIGHT JOIN | the mirror of LEFT (rarely needed) |
JOIN in JavaScript
MySQL does the same matching, but with indexes it stays fast with millions of rows.
Indexes
CREATE INDEX idx_notes_title ON notes (title);
-- Check that MySQL uses it
EXPLAIN SELECT * FROM notes WHERE title = 'Buy milk';- Index columns you use in
WHERE,JOINandORDER BY. - Primary keys and UNIQUE columns are indexed automatically.
- Too many indexes slow down INSERT and UPDATE. Add them when a query is slow, not everywhere.
LIKE '%text'with a leading percent cannot use a normal index.
Transactions
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT; -- or ROLLBACK; if anything failedIn PHP: $pdo->beginTransaction(); ... $pdo->commit(); and call $pdo->rollBack(); inside catch. Tables must use InnoDB.
Quick quiz
1. Which join keeps users that have zero notes?
LEFT JOIN keeps all rows of the left table.
2. What is an index for?
An index is a sorted lookup structure.
Common questions
Which join keeps users that have zero notes?
LEFT JOIN from users. LEFT JOIN keeps all rows of the left table.
What is an index for?
Making searches faster. An index is a sorted lookup structure.