0

I have started to learn sql and for that i am following a youtube video.

I am creating a relational database using many tables but for the context of this question i will talk about only 2. The first one is employee table and other one is branch.


employee table

CREATE TABLE employee (
    emp_id INT PRIMARY KEY,
    first_name VARCHAR(20),
    last_name VARCHAR(20),
    birth_date DATE,
    sex CHAR,
    salary INT,
    super_id INT,
    branch_id INT
);

branch table

CREATE TABLE branch (
    branch_id INT PRIMARY KEY,
    branch_name VARCHAR(20),
    mgr_id INT,
    mgr_start_date DATE,
    FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULL
);

After creating the table I have to set the branch_id in employee table to reference branch_id of branch table. I am doing it using:-

ALTER TABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;

Whenever i am trying to execute it i am getting following error

Error while executing SQL query on database 'TestDatabase': near "FOREIGN": syntax error

I am completely new to sql and have spent too much time on this issue already and still can't figure it out. I was expecting that probably this syntax is old (video i am learning from is around 5 years old) and is now not supported, but on every platform it is the method mentioned to add a foreign key.

I don't know if this help but my sql version is 3.40.0 and i also tested this code on 3.41.0 but not working. Also i am using SQLiteStudio on linux.

If this is not the right way of doing it or is deprecated way than how can i achieve this?

tycoon
  • 121
  • 9
  • 1
    It looks like that sqlite's ALTER does not support updating FK things, just a few lesser rename and add column things. See [this answer](https://stackoverflow.com/a/1884841/7644018) for alternatives. – Paul T. Mar 25 '23 at 20:24

0 Answers0