Primary key not AUTO INCREMENT in the PostgreSQL - sql

I have table Category and I have 3 columns category_id, category_name,category_description.
When I execute insert script without category_id parameter I have this error:
ERROR: null value in column "category_id" violates not-null constraint
DETAIL: Failing row contains (null, T_601, Yojimbo).
SQL state: 23502
This is my select script:
INSERT INTO category ( category_name, category_description)
VALUES ('T_601', 'Yojimbo');
This is the image of my table :

Change the data type to serial, which is Postgres's way of spelling auto_increment. If you have a not-NULL integer column with no default, then you will get an error when you attempt an insert.
If you assign a default, then the unique constraint (part of the primary key) will just create a duplicate key error on the second insert.

Use the following to add a serial to the column category_id
CREATE SEQUENCE cateogry_id_seq;
ALTER TABLE category ALTER COLUMN category_id SET DEFAULT nextval('cateogry_id_seq');
Now the column will be auto incremented and you don't have to enter the catgory_id column in insert queries

Related

How to make reference to sqlite_master's field?

It's possible make reference to field name of sqlite_master table? Something like this:
CREATE TABLE metadata (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT REFERENCES sqlite_master (name) ON DELETE CASCADE
UNIQUE
NOT NULL,
description TEXT
);
When I'm trying to execute this script then SQLiteStudio return error message SQL logic error. I need create table with human-readable description of tables. I want make field name of service table sqlite_master as foreign key in my table.
Here's what's happening:
A column used as a parent key needs to either be the parent table's primary key, or have an unique index/constraint on it. The sqlite_master table has no such thing for the name column (And you can't add an index on it), thus it can't be used. I'm not sure why you're getting a logic error on table creation instead of a foreign key mismatch error at time of insert like you do in the same situation on normal tables, though:
sqlite> pragma foreign_keys = on;
sqlite> create table parent(id integer primary key, name text not null);
sqlite> insert into parent(name) values ('Bob');
sqlite> create table child(id integer primary key, name text references parent(name));
sqlite> insert into child(name) values ('Bob');
Error: foreign key mismatch - "child" referencing "parent"
sqlite> create unique index parent_idx_name on parent(name);
sqlite> insert into child(name) values ('Bob');
sqlite>
If foreign key enforcement is disabled like it is by default, what you're trying will be accepted, it just doesn't do anything and will raise errors if you turn on FKs later and try to do stuff with the table.

How to alter a table to add a constraint?

So, the question I have is:
Due to various values entered by users for the status of the facility, this leads
to confusion. The database owner would like to limit the following values
“Open”, “Closed”, “Reserved”, and “Maintenance” to be used for the status of
facility.
My table FACILITY has the following columns:
FACILITYNAME
RATE
STATUS
I tried the following:
ALTER TABLE FACILITY ADD CONSTRAINT FACILITY_STATUS 'Open','Closed','Reserved','Maintenance' FOR STATUS;
I get an error, ORA-00904:invalid identifier
I then tried the following:
ALTER TABLE FACILITY ADD CONSTRAINT STATUS_CHECK CHECK (STATUS IN ('Open','Closed','Reserved','Maintenance'));
It said table altered, but when I tried updating the STATUS column, with 'abc' and 'Open', it says row updated, but nothing happened. I was expecting it to give me a constraint error for 'abc', and updating it to 'Open'.
Strange, for me it is working as expected:
CREATE TABLE FACILITY (
FACILITYNAME VARCHAR2(100),
RATE INTEGER,
STATUS VARCHAR2(20));
Table created.
INSERT INTO FACILITY VALUES ('f1', 1, 'Open');
1 row created.
ALTER TABLE FACILITY ADD CONSTRAINT STATUS_CHECK CHECK (STATUS IN ('Open','Closed','Reserved','Maintenance'));
Table altered.
UPDATE FACILITY SET STATUS = 'abc';
ORA-02290: check constraint (XXX.STATUS_CHECK) violated
Maybe verify the status of the constraint:
SELECT CONSTRAINT_NAME, STATUS, DEFERRABLE, DEFERRED
FROM USER_CONSTRAINTS
WHERE TABLE_NAME = 'FACILITY';
+------------------------------------------------+
|CONSTRAINT_NAME|STATUS |DEFERRABLE |DEFERRED |
+------------------------------------------------+
|STATUS_CHECK |ENABLED|NOT DEFERRABLE|IMMEDIATE|
+------------------------------------------------+
Also note, unless you give clause VALIDATE in your ALTER TABLE the constraint does not check existing values! By default only new and updated values are affected by the constraint.
As #KaushikNayak suggested try adding check constraint:
ALTER TABLE FACILITY ADD CONSTRAINT check_status CHECK (FACILITY_STATUS IN ('Open','Closed','Reserved','Maintenance'));
Otherwise, Column level constraint must use another column:
a column-level constraint
Column-level constraints refer to a single column in the table and do not specify a column name (except check constraints). They refer to the column that they follow.
I suggest you create table FACILITY_STATUS with column STATUS as Primary key and insert the values.
Then add constraint to FACILITY table STATUS column using FACILITY_STATUS(STATUS) as foreign key

Foreign key not null default value for undirectional ManyToOne association

Consider I have a table:
create table product(id int8 not null, ... , primary key (id));
I have inserted some records, so 'product' is not empty.
Then I need another table:
create table order(id int8 not null, ..., primary key (id))
After that I decided to add connection between 'product' and 'order', in Order entity added:
#NotNull
#ManyToOne
private Product product;
So in sql I do following:
alter table order add column product int8 not null default (???);
alter table order add constraint FK_order_product foreign key (product) references product;
What should I write at (???)?
If I set default to 0, then SQL will expectedly complain like:
(Key product(0)) is not in the 'product' table
It looks like your order table is also not empty (if the table is empty it works fine). In your case I recommend you to add the field by executing
alter table order add column product int8 not null default 0;
then alter each row of the order table to make the correct references to the product table in the product field and finally add the Foreign Key constraint.
Also if your order table is populated with test data, you may just truncate it before executing your script, and you can use any default in this case or not use it at all.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Why does add a foreign key to the tblDomare table result in this error?
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__tblDomare__PersN__5F7E2DAC". The conflict occurred in database "almu0004", table "dbo.tblBana", column 'BanNR'.
Code
CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);
CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));
INSERT INTO tblBana (BanNR)
Values (1);
INSERT INTO tblBana (BanNR)
Values (2);
INSERT INTO tblBana (BanNR)
Values (3);
ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
It occurred because you tried to create a foreign key from tblDomare.PersNR to tblBana.BanNR but/and the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR. You cannot create a relation which violates referential integrity.
This query was very useful for me. It shows all values that don't have any matches
select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)
Try this solution:
There is a data item in your table whose associated value doesn't exist in the table you want to use it as a primary key table.
Make your table empty or add the associated value to the second table.
It is possible to create the foreign key using ALTER TABLE tablename WITH NOCHECK ..., which will allow data that violates the foreign key.
"ALTER TABLE tablename WITH NOCHECK ..." option to add the FK -- This solution worked for me.
Remove all existing data from your tables and then make a relation between the tables.
Before You add Foreign key to the table, do the following
Make sure the table must empty or The column data should match.
Make sure it is not null.
If the table contains do not go to design and change, do it manually.
alter table Table 1 add foreign key (Column Name) references Table 2 (Column Name)
alter table Table 1 alter column Column Name attribute not null
I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.
So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.
For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.
In very simple words your table already has data present in it and the table you are trying to create relationship with does have that Primary key set for the values that are already present.
Either delete all the values of the existing table.
Add all the values of foreign key reference in the new table.
Try DELETE the current datas from tblDomare.PersNR . Because the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR.
When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.
In your example, your tables contain:
tblDomare with PRIMARY KEY (PersNR):
PersNR |fNamn |eNamn |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt' |'Carlberg' |10
7606091347 |'Josefin' |'Backman' |4
8508284163 |'Johanna' |'Backman' |1
---------------------------------------------
tblBana:
BanNR
-----
1
2
3
-----
This statement:
ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
says that any line in tblDomare with key PersNR must have a correspondence in table tblBana on key BanNR. Your error is because you have lines inserted in tblDomare with no correspondence in tblBana.
2 solutions to fix your issue:
either add lines in tblBana with BanNR in (6811034679, 7606091347, 8508284163)
or remove all lines in tblDomare that have no correspondence in tblBana (but your table would be empty)
General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.
i had this error too
as Smutje reffered make sure that you have not a value in foreign key column of your base foreign key table that is not in your reference table i.e(every value in your base foreign key table(value of a column that is foreign key) must also be in your reference table column)
its good to empty your base foreign key table first then set foreign keys
the data you have entered a table(tbldomare) aren't match a data you have assigned primary key table. write between tbldomare and add this word (with nocheck) then execute your code.
for example you entered a table tbldomar this data
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);
and you assigned a foreign key table to accept only 1,2,3.
you have two solutions one is delete the data you have entered a table then execute the code. another is write this word (with nocheck) put it between your table name and add
like this
ALTER TABLE tblDomare with nocheck
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
Smutje is correct and Chad HedgeCock offered a great layman's example.
Id like to build on Chad's example by offering a way to find/delete those records.
We will use Customer as the Parent and Order as the child. CustomerId is the common field.
select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
if you are reading this thread... you will get results. These are orphaned children. select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null Note the row count in the bottom right.
Go verify w/ whomever you need to that you are going to delete these rows!
begin tran
delete Order
from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
Run the first bit.
Check that row count = what you expected
commit the tran
commit tran
Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.
From our end, this is the scenario:
We have an existing table in the database with records.
Then I introduces a NOT nullable foreign key
After executing the update i got this error.
How did i solve you ask?
SOLUTION: I just removed all the records of the table, then tried to update the database and it was successful.
This happens to me, since I am designing my database, I notice that I change my seed on my main table, now the relational table has no foreign key on the main table.
So I need to truncate both tables, and it now works!
You should see if your tables has any data on the rows. If "yes" then you should truncate the table(s) or else you can make them to have the same number of data at tblDomare.PersNR to tblBana.BanNR and vise-verse.
In my scenario, using EF, upon trying to create this new Foreign Key on existing data, I was wrongly trying to populate the data (make the links) AFTER creating the foreign key.
The fix is to populate your data before creating the foreign key since it checks all of them to see if the links are indeed valid. So it couldn't possibly work if you haven't populated it yet.
I encounter some issue in my project.
In child table, there isn't any record Id equals 1 and 11
I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK
Please first delete data from that table and then run the migration again. You will get success
I had the same problem.
My issue was having nullable: true in column (migration file):
AddColumn("dbo.table", "column", c => c.Int(nullable: true));
Possible Solutions:
Change nullable 'false' to 'true'. (Not Recommended)
Change property type from int to int? (Recommended)
And if required, change this later after adding column > then missing field data in previous records
If you've changed an existing property from nullable to non-nullable:
3) Fill the column data in database records
A foreign key constraint in a child table must have a parent table with a primary key. The primary key must be unique. The foreign key value must match a value in the patent table primary key
When you alter table column from nullable to not nullable column where this column is foreign key, you must :
Firstly, initialize this column with value (because it is foreign
key not nullable).
After that you can alter your table column normally.
Please try below query:
CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL PRIMARY KEY,
);
CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL PRIMARY KEY,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
FK_tblBana_Id VARCHAR (15) references tblBana (BanNR)
);
INSERT INTO tblBana (BanNR)
Values (3);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet,FK_tblBana_Id)
Values (8508284173,'Johanna','Backman',1,3);
or you can use this
SELECT fk_id FROM dbo.tableA
Except
SELECT fk_id From dbo.tableB
and just FYI, in case you do all of your data reference checks and find no bad data...apparently it is not possible to create a foreign key constraint between two tables and fields where those fields are the primary key in both tables! Do not ask me how I know this.

How to add a PK to an existing table in DB2?

I am facing one problem. I have a table already create in DB2.
CREATE TABLE "DDL12"
(
"D4_1" decimal(10,0),
"D4_2" decimal(10,0),
);
I am trying to create a PK on this table as :-
ALTER TABLE "DDL12" ADD CONSTRAINT "Key4" PRIMARY KEY ("D4_1");
But while running the command, I am getting the error saying D4_1 is NULLABLE.
Now, how can I create a PK on this table?
Thanks
Yes, this is due the fact, that your database "could have" rows having NULL value in that non PK column right now.
So first set the column to NOT NULL (+ make sure having a unique value in all rows) and then set the primary key with the command above.
You can change a column to not NULL like this:
ALTER TABLE "DDL12"
MODIFY "D4_1" decimal(10,0) NOT NULL;