SQL Error Regarding Foreign Key Restraint - sqlite

I am currently getting the following error when trying to add to one of my tables:
Error adding record: FOREIGN KEY constraint failed: (INSERT INTO Stock(StockID,ItemName,MinAmountRequired,AmountInStock,Order? (Yes/No),DataLastUpdated,OrderNumber,SupplierRefrence,PurchaseID`) VALUES (1,",0,0,",",0,0,0);)
Currently, This is how I have my tables set up:
Stock
CREATE TABLE Stock (
StockID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
ItemName TEXT NOT NULL,
MinAmountRequired INTEGER NOT NULL,
AmountInStock INTEGER NOT NULL,
Order? (Yes/No) TEXT NOT NULL,
DataLastUpdated TEXT NOT NULL,
OrderNumber INTEGER NOT NULL UNIQUE,
SupplierReference INTEGER NOT NULL,
PurchaseID INTEGER NOT NULL UNIQUE,
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference));
Orders
CREATE TABLE Orders (
OrderNumber INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
CustomerReferenceNumber INTEGER NOT NULL UNIQUE,
OrderDate TEXT NOT NULL,
ItemName TEXT NOT NULL UNIQUE);
Suppliers
CREATE TABLE Supplier (
SupplierReference INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Name TEXT NOT NULL UNIQUE,
Address TEXT NOT NULL UNIQUE,
ContactNumber INTEGER NOT NULL UNIQUE);
Purchases
CREATE TABLE Purchase (
PurchaseID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
Date TEXT NOT NULL,
AmountSpent REAL NOT NULL);

You have defined these foreign keys in table Stock:
FOREIGN KEY(PurchaseID) REFERENCES Purchase(PurchaseID),
FOREIGN KEY(OrderNumber) REFERENCES Orders(OrderNumber),
FOREIGN KEY(SupplierReference) REFERENCES Supplier(SupplierReference)
meaning that the values in columns PurchaseID, OrderNumber, SupplierReference need to reference values in columns of the tables Purchase, Orders and Supplier.
But you want to store 0 to all of these columns which I'm sure that is not the value of any of the referenced columns, since these referenced columns are defined as
PRIMARY KEY AUTOINCREMENT
and so their values are > 0.
Pass valid values that do exist in these 3 tables and the statement will execute succesfully.

Related

Is it possible to insert the specified value in autoincrement column?

I need to copy one table to another and both tables contain column with AUTOINCREMENT. Is it possible to insert a defined value into AUTOINCREMENT column.
Tables:
CREATE TABLE tmptimetables (
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
_title NVARCHAR(256) NOT NULL,
_weeks INTEGER NOT NULL,
_first_week_date INTEGER NOT NULL,
_auto_complete INTEGER NOT NULL,
_first_lesson_time INTEGER NOT NULL,
_lesson_duration INTEGER NOT NULL,
_break_duration INTEGER NOT NULL,
_color INTEGER NOT NULL,
_symbol NCHAR(1) NOT NULL
);
CREATE TABLE timetables (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
title NVARCHAR(256) NOT NULL,
weeks INTEGER NOT NULL,
first_week_date INTEGER NOT NULL,
auto_complete INTEGER NOT NULL,
first_lesson_time INTEGER NOT NULL,
lesson_duration INTEGER NOT NULL,
break_duration INTEGER NOT NULL,
color INTEGER NOT NULL,
symbol NCHAR(1) NOT NULL
);
My SQL request:
INSERT INTO timetables (
auto_complete,
break_duration,
color,
first_lesson_time,
first_week_date, id,
lesson_duration,
symbol,
title,
weeks
)
SELECT
_auto_complete,
_break_duration,
_color,
_first_lesson_time,
_first_week_date,
_id,
_lesson_duration,
_symbol,
_title,
_weeks
FROM tmptimetables
AUTOINCREMENT can only be used for a column that is INTEGER PRIMARY KEY, it is INTEGER PRIMARY KEY that is the factor that makes the column a special column whereby if the value is not provided when inserting a row that a unique integer will be assigned.
So be the column INTEGER PRIMARY KEY or INTEGER PRIMARY KEY AUTOINCREMENT you can specify an integer value and a row may be inserted with the given value.
A row will not be inserted with a given value if that value is not unique.
For example if the table timetables is currently :-
Then
INSERT INTO timetables (id,title,weeks,first_week_date,auto_complete,first_lesson_time,lesson_duration,break_duration,color,symbol) VALUES (null,'mytitle',78,86000,23,1800,900,200,16,'E');
Would insert a new row with the id as determined by SQLite's algorithm for providing a unique id (probably 5).
If the id were changed to be provided (i.e. not null) say to 10 as per :-
INSERT INTO timetables (id,title,weeks,first_week_date,auto_complete,first_lesson_time,lesson_duration,break_duration,color,symbol) VALUES (10,'mytitle',78,86000,23,1800,900,200,16,'E');
Then the id for the new row would be 10.
However if then using (the same SQL but with the last column value changed) :-
INSERT INTO timetables (id,title,weeks,first_week_date,auto_complete,first_lesson_time,lesson_duration,break_duration,color,symbol) VALUES (10,'mytitle',78,86000,23,1800,900,200,16,'Z');
A new row would not be inserted as a row with an id of 10 already exists.
Finally if the id is not given (null is used) but the SQL is otherwise the same a new row is inserted with a unique id being provided by SQLite e.g.
INSERT INTO timetables (id,title,weeks,first_week_date,auto_complete,first_lesson_time,lesson_duration,break_duration,color,symbol) VALUES (null,'mytitle',78,86000,23,1800,900,200,16,'Z');
So the end result of following the above is :-
AUTOINCREMENT
The AUTOINCREMENT keyword, only usable for an INTEGER PRIMARY COLUMN, invokes a different algorithm for determining the next sequence to ensure that the next sequence/id is always greater, whilst without AUTOINCREMENT a lower sequence/id can be applied.
The AUTOINCREMENT keyword does not specify that if a value for the column is not provided then a sequence/id is applied it is INTEGER PRIMARY KEY that specifies that. Well actually, by default, i.e. unless WITHOUT ROWID is specified, this happens for all tables. It's just the the special rowid column is hidden. Specifying <column_name> INTEGER PRIMARY KEY (where is a valid column name) creates an alias of the rowid.
For example using SELECT rowid,* FROM timetables produces :-
SQLite Autoincrement
Rowid Tables

Foreign key mismatch SQLite

I searched all the documentation about this and I can't seem to understans what's the problem, maybe an experienced could help me.
So I'm creating a table called LOCALIZACAO:
CREATE TABLE LOCALIZACAO(
id INTEGER PRIMARY KEY AUTOINCREMENT,
rua TEXT NOT NULL,
codigoPostal TEXT NOT NULL,
UNIQUE (codigoPostal));
And this other table that references LOCALIZACAO, called SOCIOLOCALIZACAO:
CREATE TABLE SOCIOLOCALIZACAO(
idS INTEGER REFERENCES SOCIO(idS),
idL INTEGER NOT NULL REFERENCES LOCALIZACAO(idL),
CONSTRAINT pk_SOCIOLOCALIZACAO PRIMARY KEY (idS),
CONSTRAINT fk_SOCIOLOCALIZACAO FOREIGN KEY (idL) REFERENCES LOCALIZACAO(id) ON DELETE CASCADE ON UPDATE CASCADE);
Altough I'm inserting elements on the LOCALIZACAO table, when I'm inserting on the SOCIOLOCALIZACAO table:
INSERT INTO SOCIOLOCALIZACAO VALUES (1,1);
I'm given an error
foreign key mismatch "SOCIOLOCALIZACAO" referencing "LOCALIZACAO"
I'm sure there is the element 1 in SOCIO and in LOCALIZACAO
Here is the SOCIO table:
CREATE TABLE SOCIO(
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
anoDeNascimento INTEGER NOT NULL,
numeroDeSocio INTEGER NOT NULL CHECK (numeroDeSocio > 0),
nif INTEGER NOT NULL CHECK (nif > 99999999 AND nif < 1000000000),
anoDeVinculacao INTEGER NOT NULL CHECK (anoDeNascimento < anoDeVinculacao),
UNIQUE (nome, nif),
UNIQUE (numeroDeSocio));
Any help is appreciated!
Thank you!
Your foreign key references the fields idS and idL in table LOCALIZACAO. There are no such fields, there's only an id field there.
I guess you're only seeing this when inserting records because SQLite is not very pedantic. Other databases wouldn't have let you create such a foreign key.

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)
)

one column value reference from two tables is it support SQLITE

one column value reference from two tables is it support SQLITE
see the below table structure
account_id reference from two tables
FOREIGN KEY(account_id) REFERENCES account(id),
FOREIGN KEY(account_id) REFERENCES category(id)
CREATE TABLE transaction (
id NUMERIC PRIMARY KEY,
user_id NUMERIC NOT NULL,
account_id NUMERIC NOT NULL,
category_id NUMERIC NOT NULL,
amount DOUBLE NOT NULL, date VARCHAR(25) NOT NULL,
description VARCHAR(25),
FOREIGN KEY(account_id) REFERENCES account(id),
FOREIGN KEY(account_id) REFERENCES category(id)
);
This is possible.
All constraints must be met, i.e., each account_id value must appear in both parent tables.

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