SQLite3 syntax error trying to create foreign key - sqlite

I am trying to create a bunch of tables in sqlite3 and I am getting an error that I can't fix. Something to do with my syntax for sqlite3 for foreign keys but can't figure it out.
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(64),
last_name VARCHAR(64)
);
CREATE TABLE classes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
class_name VARCHAR(64)
);
CREATE TABLE students_classes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
students_id INTEGER,
classes_id INTEGER,
FOREIGN KEY (students_id) REFERENCES students(id),
FOREIGN KEY (classes_id) REFERENCES classes(id)
);
CREATE TABLE teachers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
classes_id INTEGER,
first_name VARCHAR(64),
last_name VARCHAR(64),
FOREIGN KEY classes_id REFERENCES classes(id)
);
CREATE TABLE grades (
id INTEGER PRIMARY KEY AUTOINCREMENT,
students_id INTEGER,
grade_num INTEGER,
FOREIGN KEY students_id REFERENCES students(id)
);
Error: near "students_id": syntax error

SQLite Docs seem to indicate that column name(s) in FOREIGN Key constraint must be inside parenthesis:
I'm not sure how strictly it's actually enforced. My SQL Fiddle shows that using parenthesis should solve your problem.
Please note that SQL Fiddle for SQLite is emulated, so your result might still vary.

Related

Sqlite foreign key mismatch?

I've read this question and understood the referenced foreign keys to be unique, but somehow the insertion to table are still throwing foreign key mismatch errors:
CREATE TABLE medication (
med_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
med_name VARCHAR (20) NOT NULL,
dosage VARCHAR (10)
);
CREATE TABLE disease (
dis_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
disease_name VARCHAR (20) NOT NULL
);
CREATE TABLE dis_med (
disease_id int NOT NULL,
medication_id int NOT NULL,
CONSTRAINT PK_dis_med PRIMARY KEY (disease_id, medication_id),
CONSTRAINT FK_dis FOREIGN KEY (disease_id) REFERENCES disease (dis_id),
CONSTRAINT FK_med FOREIGN KEY (medication_id) REFERENCES medication (med_id));
CREATE TABLE user_disease (
user_id REFERENCES user (user_id),
dis_id REFERENCES disease (dis_id),
med_id REFERENCES dis_med(medication_id),
CONSTRAINT PK_dis_user PRIMARY KEY (user_id, dis_id)
);
Through the list in the question I cited:
the parent table (medication, disease) exists.
the parent columns exist
the child table references all of the primary key columns in the parent table
Update1
I was able to insert data and bypass the error by altering the user_disease table by composite foreign key. I'd appreciate it if someone can point out what's the best design here. Many thanks in advance!
CREATE TABLE user_disease (
user_id REFERENCES user (user_id),
dis_id REFERENCES disease (dis_id),
med_id REFERENCES dis_med(medication_id),
CONSTRAINT FK_dis_med FOREIGN KEY REFERENCES dis_med(disease_id, medication_id),
CONSTRAINT PK_dis_user PRIMARY KEY (user_id, dis_id)
);
From SQLite Foreign Key Support/3. Required and Suggested Database Indexes:
Usually, the parent key of a foreign key constraint is the primary key of the parent table.
If they are not the primary key, then the parent key columns must be collectively
subject to a UNIQUE constraint or have a UNIQUE index.
With this:
CREATE TABLE user_disease (
...........................
med_id REFERENCES dis_med(medication_id),
...........................
);
the column med_id of user_disease references the column medication_id of dis_med, which is not the PRIMARY KEY of dis_med and there is no UNIQUE constraint for it. It just references med_id of medication .
Why do you need the column med_id in user_disease?
You have dis_id referencing disease, which may also be used to retrieve from dis_med (all) the row(s) from dis_med for that disease.

near ",": syntax error using foreign keys [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I keep getting the issue syntax error on the CREATE TABLE lines for all three tables that use the foreign key statements. I've been troubleshooting for a while and I'm stressing out as it's my first programming uni assignment.
PRAGMA foreign_keys = ON;
CREATE TABLE Customer_info (
customer_id VARCHAR(32) PRIMARY KEY,
name VARCHAR(255),
address VARCHAR(255),
login_name VARCHAR(255)
);
CREATE TABLE Payment_method (
payment_id VARCHAR(32) PRIMARY KEY,
billing_adress VARCHAR(255),
card_holder_name VARCHAR(255),
credit_card_nr INT,
cvs INT,
exp_date DATE
);
CREATE TABLE Product_list (
p_name VARCHAR(255) PRIMARY KEY,
p_price INT,
publisher VARCHAR(255),
developer_studio VARCHAR(255)
);
CREATE TABLE Games (
game_name VARCHAR(255) PRIMARY KEY,
game_desc VARCHAR(255),
FOREIGN KEY (game_name),
REFERENCES Product_list (p_name)
);
CREATE TABLE Software (
soft_name VARCHAR(255) PRODUCT KEY,
soft_desc VARCHAR(255),
FOREIGN KEY (soft_name),
REFERENCES Product_list (p_name)
);
CREATE TABLE Prof_info (
profile_id VARCHAR(32) PRIMARY KEY,
nickname VARCHAR(255),
display_name VARCHAR(255),
description VARCHAR(255),
FOREIGN KEY (profile_id),
REFERENCES Customer_info (customer_id)
);
CREATE TABLE Groups (
group_id VARCHAR(32) PRIMARY KEY,
g_name VARCHAR(255),
g_desc VARCHAR(255)
);
Also I apologise if these are easy questions but I am sleep deprived, stressed & running out of time.
edit: removed the second question I had at the end as it was pointed out to me this isn't supposed to be done.
foreign key ... references is a single expression.
FOREIGN KEY (profile_id) REFERENCES Customer_info(customer_id)
SQLite does not require a separate foreign key clause. You can do this inline.
-- A primary key that is also a foreign key is a bit odd.
game_name VARCHAR(255) PRIMARY KEY REFERENCES Customer_info(customer_id)
See table-constraint and foreign-key-clause in the SQLite create table grammar.
Also would it be possible to state 2 foreign keys referencing different tables within the same table? How would I go about doing this?
Yes, just declare two foreign keys. Perhaps you're confused because you're making your foreign keys also your primary keys.
Here's a sketch of a better design. All of the pieces get their own table. All tables get an auto-incremented integer primary key which is assured to be unique and unchanging. Column names do not use prefixes, fully qualify them in queries if necessary. Table names are normalized as plurals.
create table publishers (
id integer primary key,
name varchar(255) not null
);
create table developers (
id integer primary key,
name varhcar(255) not null
);
create table products (
id integer primary key,
name varchar(255) not null,
price numeric(6,2),
publisher_id integer references publishers(id),
developer_id integer references developers(id)
);
create table games (
id integer primary key,
name varchar(255) not null,
description varchar(255),
product_id integer references products(id)
);

sqlite column constraints both unique and foreign

Does sqlite allow a column to be both unique and a foreign key at the same time?
How does the definition look like?
CREATE TABLE table1 (
id INTEGER PRIMARY KEY,
fkey INTEGER NOT NULL UNIQUE REFERENCES table2(id)
)
CREATE TABLE table2 (
id INTEGER PRIMARY KEY
)
Sure
CREATE TABLE table1 (
id INTEGER PRIMARY KEY,
fkey INTEGER NOT NULL UNIQUE,
FOREIGN KEY(fkey) REFERENCES table2(id)
)
result.
Query executed successfully: CREATE TABLE table1 (
id INTEGER PRIMARY KEY,
fkey INTEGER NOT NULL UNIQUE,
FOREIGN KEY(fkey) REFERENCES table2(id)
) (took 0ms)
REMEMBER. As of version 3.6.19, SQLite supports foreign key constraints. But enforcement of foreign key constraints is turned off by default (for backwards compatibility). To enable foreign key constraint enforcement, run PRAGMA foreign_keys=ON, from http://sqlite.org/faq.html

many foreign keys in one table sqlite

I want to use many foreign keys in one table on sqlite.
But it makes just one. how can I do it?
CREATE TABLE STORES(
SId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
SName TEXT NOT NULL
)
CREATE TABLE CITY(
CId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
CName TEXT NOT NULL
)
CREATE TABLE PRODUCTS(
PId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
PName TEXT NOT NULL,
Price REAL NOT NULL
)
CREATE TABLE STORE_CITY(
CId INTEGER REFERENCES CITY(CId) NOT NULL,
SId INTEGER REFERENCES STORES(SId) NOT NULL,
PId INTEGER REFERENCES PRODUCTS(PId)
)
Define the columns first, THEN make them foreign keys.
CREATE TABLE STORE_CITY(
CId INTEGER,
SId INTEGER,
PId INTEGER,
FOREIGN KEY (CId) REFERENCES CITY(CId) NOT NULL,
FOREIGN KEY (SId) REFERENCES STORES(SId) NOT NULL,
FOREIGN KEY (PId) REFERENCES PRODUCTS(PId)
)

SQLite foreign key mismatch error

Why am I getting a SQLite "foreign key mismatch" error when executing script below?
DELETE
FROM rlsconfig
WHERE importer_config_id=2 and
program_mode_config_id=1
Here is main table definition:
CREATE TABLE [RLSConfig] (
"rlsconfig_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"l2_channel_config_id" integer NOT NULL,
"rls_fixed_width" integer NOT NULL
,
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([importer_config_id]),
FOREIGN KEY ([importer_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id]),
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ImporterConfig]([program_mode_config_id])
)
and referenced table:
CREATE TABLE [ImporterConfig] (
"importer_config_id" integer NOT NULL,
"program_mode_config_id" integer NOT NULL,
"selected" integer NOT NULL DEFAULT 0,
"combined_config_id" integer NOT NULL,
"description" varchar(50) NOT NULL COLLATE NOCASE,
"date_created" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY ([program_mode_config_id], [importer_config_id])
,
FOREIGN KEY ([program_mode_config_id])
REFERENCES [ProgramModeConfig]([program_mode_config_id])
)
When you use a foreign key over a table that has a composite primary key you must use a composite foreign key with all the fields that are in the primary key of the referenced table.
Example:
CREATE TABLE IF NOT EXISTS parents
(
key1 INTEGER NOT NULL,
key2 INTEGER NOT NULL,
not_key INTEGER DEFAULT 0,
PRIMARY KEY ( key1, key2 )
);
CREATE TABLE IF NOT EXISTS childs
(
child_key INTEGER NOT NULL,
parentKey1 INTEGER NOT NULL,
parentKey2 INTEGER NOT NULL,
some_data INTEGER,
PRIMARY KEY ( child_key ),
FOREIGN KEY ( parentKey1, parentKey2 ) REFERENCES parents( key1, key2 )
);
I am not sure about SQLite. But I found this link on google. http://www.sqlite.org/foreignkeys.html.
Some of the reasons can be
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Unfortunately, SQLite gives this error all the time without mentioning WHICH foreign key constraint failed. You are left to try to check them one by one, which often doesn't work, and then rebuild the table without the constraints and add them back one by one until you find the problem. SQLite is great in a lot of ways, but this isn't one of them.

Resources