← CodePrimer
SQL Intermediate Database

Foreign key relationship

How do I relate posts to users?

FOREIGN KEY constraint.

Sample
CREATE TABLE posts (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL,
  title VARCHAR(160) NOT NULL,
  CONSTRAINT fk_posts_user
    FOREIGN KEY (user_id) REFERENCES users(id)
    ON DELETE CASCADE
);

Notes

FKs protect referential integrity.

Keywords: foreign key · relation · references

Related

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share