UNIQUE constraint failed sqlite - sqlite

Before I alter a table I want to make a backup of it, so I use this code :
CREATE TABLE states_BACKUP (
state_id INTEGER NOT NULL,
domain VARCHAR(64),
entity_id VARCHAR(255),
state VARCHAR(255),
attributes TEXT,
event_id INTEGER,
last_changed DATETIME,
last_updated DATETIME,
created DATETIME,
context_id VARCHAR(36),
context_user_id VARCHAR(36), old_state_id INTEGER,
PRIMARY KEY (state_id),
FOREIGN KEY(event_id) REFERENCES events (event_id)
);
INSERT into states_BACKUP
Select *
FROM STATES;
However when the insert part is executed an error message says :
Execution finished with errors.
Result: UNIQUE constraint failed: states_BACKUP.state_id
At line 18:
INSERT into states_BACKUP
Select *
FROM STATES;
when I change the code to
Select distinct *
FROM STATES;
I get the same eror.
Trying to find an answer on the web how to solve this problem, I find this error has to do with duplicate id's. I wonder how this can happen when I just copy a table.
Anyone has a solution for this ?

Related

Sqlite3: Error deleting record: foreign key mismatch

I am trying to delete a record from table users.
Tried deleteing it with a DELETE-statement (DELETE FROM users WHERE user_id=10" as well as in my DB browser, but I get the above error, specifically it says: "Error deleting record: foreign key mismatch - "games" referencing "groups" (DELETE FROM "main"."users" WHERE rowid IN ('10');)".
Below my schema:
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
name VARCHAR(255) NOT NULL,
hash VARCHAR(255) NOT NULL,
UNIQUE(name));
CREATE TABLE 'groups' (
'group_name' VARCHAR(255) NOT NULL,
'turn' INTEGER NOT NULL,
'user_id'INTEGER,
FOREIGN KEY ('user_id') REFERENCES 'users'('user_id')
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE games (
game_id INTEGER PRIMARY KEY,
active INTEGER,
turn INTEGER,
group_name VARCHAR(255) NOT NULL,
FOREIGN KEY (turn) REFERENCES groups(turn_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (group_name) REFERENCES groups(group_name)
ON UPDATE CASCADE
ON DELETE NO ACTION
);
Why is this a problem? user_id is not even a foreign key in 'games'?? Thank you!
The problem in the end was my DB Browser for SQLite (3.11.2) whose GUI allows deletions but they don't actually work. When I tied again in the bash and closed and restarted the DB Browser, the rows were gone. Uninsightful but figured I'd post nonetheless in case anyone else comes across this.

sqlite integer primary key not null constraint failed

According to the SQLite documentation / FAQ a column declared INTEGER PRIMARY KEY will automatically get a value of +1 the highest of the column if omitted.
Using SQLite version 3.22.0 2018-01-22 18:45:57
Creating a table as follows:
CREATE TABLE test (
demo_id INTEGER PRIMARY KEY NOT NULL,
ttt VARCHAR(40) NOT NULL,
basic VARCHAR(25) NOT NULL,
name VARCHAR(255) NOT NULL,
UNIQUE(ttt, basic) ON CONFLICT ROLLBACK
) WITHOUT ROWID;
Then inserting like this:
INSERT INTO test (ttt, basic, name) VALUES ('foo', 'bar', 'This is
a test');
gives:
Error: NOT NULL constraint failed: test.demo_id
sqlite>
When it is expected to create a record with a demo_id value of 1. Even if the table already contains values, it'll fail inserting the row without explicitly specifying the id with the same error.
What am I doing wrong?
The documentation says that you get autoincrementing values for the rowid. But you specified WITHOUT ROWID.

Primary key does not allow unique replace functionality

CREATE TABLE resource_sync
(
_id INTEGER UNIQUE ON CONFLICT REPLACE PRIMARY KEY,
status_id INTEGER,
result_id INTEGER
);
In case two equal _id values get inserted, SQLite would throw an exception:
[13:39:48] Error while executing SQL query on database 'test': UNIQUE
constraint failed: resource_sync._id
However, it allows for desired replaces in case primary key declaration is removed from table creation SQL.
Why is that?
Thanks.
UNIQUE is ignored on primary keys.
The correct syntax, as shown in the documentation, is:
CREATE TABLE resource_sync
(
_id INTEGER PRIMARY KEY ON CONFLICT REPLACE,
status_id INTEGER,
result_id INTEGER
);

ORA-00907: missing right parenthesis when creating tables

I am trying to create 3 tables but I am getting this error:
CREATE TABLE dj_abonent
(
dj_klientID INT NOT NULL PRIMARY KEY,
emer_klienti varchar2(10),
mbiemer_klienti VARCHAR2(10),
sasia_cel INT
);
CREATE TABLE dj_phones
(
phone_number varchar2(12),
activated number(1) default 0,
activation_date date default null,
CONSTRAINT dj_phone_number_check
CHECK (substr(phone_number,1,5) in( '35566','35567','35568','35569') ),
CONSTRAINT dj_activated_check
CHECK (activated in(1,0) )
dj_KlientID int FOREIGN KEY REFERENCES dj_Abonenti(dj_KlientID)
);
CREATE TABLE dj_telef
(
start_time date,
end_time date,
abonent_1 varchar2(10),
abonent_2 varchar2(10)
);
Error at Command Line : 26 Column : 17
Error report -
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
*Cause:
*Action:
The line number is from your SQL Developer script window, which isn't entirely helpful as it doesn't seem to align with the issue. There may be other things too but you're missing a comma after your check constraint (just like a previous question). But you should put the constraints at the end of the command:
CREATE TABLE dj_phones
(
phone_number varchar2(12),
activated number(1) default 0,
activation_date date default null,
dj_KlientID int FOREIGN KEY REFERENCES dj_Abonenti(dj_KlientID)
CONSTRAINT dj_phone_number_check
CHECK (substr(phone_number,1,5) in( '35566','35567','35568','35569') ),
CONSTRAINT dj_activated_check
CHECK (activated in(1,0) )
);
You might find it easier to debug these issues if you ran one statement at a time, either with the run statement command (control-enter), or by highlighting the text one one command and using run script (F5).

How to set cascade on SQLite database with compound primary foreign key?

I have a db that's structured with a supertype table as well as subtype tables like so:
EVENT
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode )
different types of events have their own tables and have the same primary key, except that it's foreign.
EXERCISE
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ) ON CONFLICT IGNORE,
CONSTRAINT "PrimaryKey" FOREIGN KEY ("PatientId", "EventTypeCode", "DateTime") REFERENCES "Event" ("PatientId", "EventTypeCode", "DateTime") ON DELETE CASCADE ON UPDATE CASCADE
When I try to delete an entry in Event, I get a foreign key mismatch and when I delete it in Exercise it deletes, but only in Exercise.. it does not cascade. What do I need to do to get the cascade to work properly? I would prefer to delete the entry in Event and have it cascade to Exercise.. which from the examples I've seen seems like how it should work...
It is because you have set up an invalid foreign key. Even though SQLite allows you to set it up, it will error out when trying to enforce it.
http://www.sqlite.org/foreignkeys.html#fk_indexes
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
Foreign keys should be set up against a unique target. The column PatientId references Event(PatientID) is not valid, because PatientID alone in table Event is not unique.
EDIT
Foreign key support is only available on SQLite 3.6.19 or above. Depending on what tool you use, you also need to enable pragma foreign_keys explicitly. For SQLite Manager add-on for Firefox for example, see here http://code.google.com/p/sqlite-manager/wiki/ForeignKeys
This works for me
Caution!! don't drop your existing tables if they contain anything important. Try on a new db
drop table if exists event;
drop table if exists exercise;
create table EVENT (
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ));
create table EXERCISE(
PatientId INTEGER,
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode ) ON CONFLICT IGNORE,
CONSTRAINT "PrimaryKey" FOREIGN KEY ("PatientId", "EventTypeCode", "DateTime") REFERENCES "Event" ("PatientId", "EventTypeCode", "DateTime") ON DELETE CASCADE ON UPDATE CASCADE);
insert into Event (patientid, datetime, eventtypecode) values (1,2,3);
insert into Event (patientid, datetime, eventtypecode) values (4,5,6);
insert into Event (patientid, datetime, eventtypecode) values (7,9,8);
insert into Exercise (patientid, datetime, eventtypecode) values (1,2,3);
insert into Exercise (patientid, datetime, eventtypecode) values (7,9,8);
delete from event where patientid=1;

Resources