select foreign key sql code example
Example 1: sql foreign key
CREATE TABLE users(
userId INT NOT NULL,
username VARCHAR(64) NOT NULL,
passwd VARCHAR(32) NOT NULL,
PRIMARY KEY(userId);
);
INSERT INTO users VALUES(1000,"Terry","Teabagface$2");
CREATE TABLE orders(
orderId INT NOT NULL,
orderDescription VARCHAR(255),
ordererId INT NOT NULL,
PRIMARY KEY(orderId),
FOREIGN KEY (ordererId) REFERENCES users(userId)
);
INSERT INTO orders VALUES(0001,"Goat p0rn Weekly",1000);
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:
CREATE TABLE users(
user_id INT NOT NULL,
user_name VARCHAR(64) NOT NULL,
user_pass VARCHAR(32) NOT NULL,
PRIMARY KEY(user_id);
);
INSERT INTO users VALUES(1,"Raj","raj@123");
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)
);
INSERT INTO orders VALUES(1,"Daily groceries",1);
Example 3: sql server find all foreign keys that reference a column
SELECT
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
sys.tables t
ON t.OBJECT_ID = fc.referenced_object_id
WHERE
OBJECT_NAME (f.referenced_object_id) = 'YourTableName'