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.

In shortA foreign key points from one table to another. JOIN combines rows. An index makes searches fast. A transaction makes several changes succeed or fail together.

Theory in plain words

One to manyusersid (primary key)emailpassword_hashnotesid (primary key)user_id (foreign key)title, done
One to many

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

Two linked tables
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

INNER JOIN and LEFT 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.emailtotal
asha@example.com3
ravi@example.com0
JOIN typeKeeps
INNER JOINonly rows that match in both tables
LEFT JOINall rows from the left table, NULL when nothing matches
RIGHT JOINthe mirror of LEFT (rarely needed)

JOIN in JavaScript

Join two arrays by idTry it Yourself

MySQL does the same matching, but with indexes it stays fast with millions of rows.

Indexes

Add an index
CREATE INDEX idx_notes_title ON notes (title);
-- Check that MySQL uses it
EXPLAIN SELECT * FROM notes WHERE title = 'Buy milk';

Transactions

All or nothing
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 failed

In 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?

2. What is an index for?

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.