0
Q:

foreign key

# A foreign key is essentially a reference to a primary
# key in another table.

# A Simple table of Users, 
CREATE TABLE users(
	userId INT NOT NULL,
  	username VARCHAR(64) NOT NULL,
  	passwd VARCHAR(32) NOT NULL,
  	PRIMARY KEY(userId);
);
# Lets add a LEGIT user!
INSERT INTO users VALUES(1000,"Terry","Teabagface$2");

# We will create an order table that holds a reference
# to an order made by our Terry
CREATE TABLE orders(
	orderId INT NOT NULL,
  	orderDescription VARCHAR(255),
  	ordererId INT NOT NULL,
  	PRIMARY KEY(orderId),
  	FOREIGN KEY (ordererId) REFERENCES users(userId)
);
# Now we can add an order from Terry
INSERT INTO orders VALUES(0001,"Goat p0rn Weekly",1000);

# Want to know more about the plight of Goats?
# See the link below
24
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

Example:
# creating table users
CREATE TABLE users(
	user_id INT NOT NULL,
  	user_name VARCHAR(64) NOT NULL,
  	user_pass VARCHAR(32) NOT NULL,
  	PRIMARY KEY(user_id);
);
# adding user data
INSERT INTO users VALUES(1,"Raj","raj@123");

# creating table orders
CREATE TABLE orders(
	order_id INT NOT NULL,
  	order_description VARCHAR(255),
  	orderer_id INT NOT NULL,
  	PRIMARY KEY(order_id),
  	FOREIGN KEY (orderer_id) REFERENCES users(user_id)
);
# adding order data
INSERT INTO orders VALUES(1,"Daily groceries",1);
14
Foreign Key is a non-key attribute which is derived from the primary key 
of another table which links those tables together.
1
ALTER TABLE table_name
DROP CONSTRAINT fk_name;
1

CREATE TABLE Orders
(

   
OrderID int NOT NULL,

   
OrderNumber int NOT NULL,

   
PersonID int,

   
PRIMARY KEY (OrderID),

   
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)

); 
1

ALTER TABLE Orders

ADD CONSTRAINT FK_PersonOrder

FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID); 
0

New to Communities?

Join the community