Answers for "foreign key example"

SQL
25

mysql add foreign key

-- On Create
CREATE TABLE tableName (
    ID INT,
    SomeEntityID INT,
    PRIMARY KEY (ID),
    FOREIGN KEY (SomeEntityID)
        REFERENCES SomeEntityTable(ID)
        ON DELETE CASCADE
);

-- On Alter, if the column already exists but has no FK
ALTER TABLE
  tableName
ADD
  FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
  
 -- Add FK with a specific name
 -- On Alter, if the column already exists but has no FK
ALTER TABLE
  tableName
ADD CONSTRAINT fk_name
  FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
Posted by: Guest on April-27-2020
4

add constraint fk

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
Posted by: Guest on September-02-2020
19

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);
Posted by: Guest on April-25-2020
2

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)
);
Posted by: Guest on January-07-2021
1

foreign keys

CREATE TABLE Employee(
    EmployeeID int NOT NULL,
    LastName varchar(50) NOT NULL,
    FirstName varchar(20) NOT NULL,
    Age int,
    DeptNo int,
    PRIMARY KEY (EmployeeID),
    FOREIGN KEY (DeptNo) REFERENCES Department(DeptNo)
);
Posted by: Guest on November-01-2021
0

foreign key

CREATE TABLE Employee(
    EmployeeID int NOT NULL,
    LastName varchar(50) NOT NULL,
    FirstName varchar(20) NOT NULL,
    Age int,
    DeptNo int,
    PRIMARY KEY (EmployeeID),
    FOREIGN KEY (DeptNo) REFERENCES Department(DeptNo)
);
Posted by: Guest on July-06-2021

Code answers related to "foreign key example"

Code answers related to "SQL"

Browse Popular Code Answers by Language