Answers for "how to insert foreign key in sql"

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
1

how to insert values in table which contains foreign key

+----------------+------------+------+-----+---------+-------+
| Field          | Type       | Null | Key | Default | Extra |
+----------------+------------+------+-----+---------+-------+
| FACULTY_ID     | int(4)     | NO   | MUL | NULL    |       |
| COURSE_ID      | varchar(8) | NO   | MUL | NULL    |       |
| DATE_QUALIFIED | date       | NO   |     | NULL    |       |
+----------------+------------+------+-----+---------+-------+
3 rows in set (0.059 sec)

INSERT INTO tbl_isqualified
VALUES
(2143, "ISM 3113", '1998-9-01'); /* (FK),(FK), 'YEAR-MONTH-DAY' */

SELECT * FROM tbl_isqualified;
+------------+-----------+----------------+
| FACULTY_ID | COURSE_ID | DATE_QUALIFIED |
+------------+-----------+----------------+
|       2143 | ISM 3113  | 1998-09-01     |
+------------+-----------+----------------+
1 row in set (0.001 sec)
Posted by: Guest on October-26-2021

Code answers related to "how to insert foreign key in sql"

Code answers related to "SQL"

Browse Popular Code Answers by Language