Dendory Network

Logo

Hi, my name is Patrick Lambert and I'm a tech worker, blogger, anime fan, digital artist and video gamer. I live in Montreal, Canada and have over 15 years of experience in technology.

Send me an email dendory@icloud.com

Connect with me on LinkedIn patrick-lambert-530383162

Chat with me on Discord TzrNgbx

Digital art galleries dendory

My YouTube channel elfguy

3D models on ShareCG elfguy


Creating a foreign key in MySQL


The idea behind foreign key in a database is that one table relates to another table. The common example is that you may have a table containing users which has these fields:

Then you may have a table with purchases, which links to the user table:

Technically, you don’t have to link both tables. You could fill the user_id field with an idea from the users’ table and just assume it’s valid. But adding it as a foreign key just makes sure that the database will enforce that the id actually exists in the other table.

This is how you can create the two tables:

CREATE TABLE users (id VARCHAR(20) UNIQUE NOT NULL PRIMARY KEY, name VARCHAR(200), email VARCHAR(50));
CREATE TABLE purchases (id VARCHAR(20), date VARCHAR(20), item VARCHAR(50), price BIGINT, user_id VARCHAR(20), CONSTRAINT user_id FOREIGN KEY (user_id) REFERENCES users(id));

From there, you can use joins to get information about both tables. For example, you could get a list of purchased items and prices along with user names, for items that cost more than $10:

SELECT u.name,p.item,p.price FROM purchases p INNER JOIN users u ON u.id = p.user_id WHERE p.price > 10;