Example 1: sql 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
Example 2: foreign key in sql
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);
Example 3: mysql alter add foreign key
ALTER TABLE ordenes ADD ticket VARCHAR(50) NOT NULL;
ALTER TABLE ordenes ADD CONSTRAINT fk_ticket FOREIGN KEY (ticket) REFERENCES tickets(ticket);
// I'm Horrible Hyena
Example 4: sql foreign key
CREATE TABLE orders (
id int NOT NULL,
user_id int,
product_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
Example 5: primary key sql
A primary key is a field in a table which uniquely identifies each row/record in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).
Example 6: What is foreign key?
Foreign Key is a non-key attribute which is derived from the primary key
of another table which links those tables together.