Answers for "using foreign keys in sql"

SQL
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
0

Foreign Key in sql

CREATE TABLE Students ( 	 /* Create table with foreign key - Way 1 */
    ID INT NOT NULL
    Name VARCHAR(255)
    LibraryID INT
    PRIMARY KEY (ID)
    FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);

CREATE TABLE Students ( 	 /* Create table with foreign key - Way 2 */
    ID INT NOT NULL PRIMARY KEY
    Name VARCHAR(255)
    LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);


ALTER TABLE Students 	 /* Add a new foreign key */
ADD FOREIGN KEY (LibraryID)
REFERENCES Library (LibraryID);
Posted by: Guest on July-06-2021

Code answers related to "SQL"

Browse Popular Code Answers by Language