Search code examples
sqlitecreate-table

Parse error: near "employee_id": syntax error


A foreign key is not created when a table is created, although a reference for it exists in another table

Table customers:

CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_name VARCHAR(50),
contact_info VARCHAR(50));

Table employees:

CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY AUTOINCREMENT,
employee_name VARCHAR(50),
position VARCHAR(50),
hire_date DATETIME);

Table orders with FOREIGN KEY:

CREATE TABLE orders (
order_id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
employee_id INTEGER,
FOREIGN KEY (employee_id) REFERENCES employees(employee_id),
order_date DATETIME);

I created the first two tables and expected to be able to create the third, but I got an error that seems illogical to me "

Parse error: near "employee_id": syntax error (customer_id) REFERENCES customers(customer_id), employee_id INTEGER, FOREIGN


Solution

  • Foreign keys are the last declarations inside a CREATE TABLE statement. Make sure to move them at the bottom.

    CREATE TABLE orders (
        order_id INTEGER PRIMARY KEY AUTOINCREMENT,
        customer_id INTEGER,
        employee_id INTEGER,
        order_date DATETIME,
        FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
        FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
    );