Issue in mapping a new table data to an existing table - database

I have a parent table like below
CREATE TABLE "Tablename"
(
"column1" integer,
"column2" integer NOT NULL,
"column3" text,
"column4" integer,
"column5" text,
"column6" integer,
CONSTRAINT "Tablename_pkey" PRIMARY KEY ("column1"),
CONSTRAINT uk_t1 UNIQUE ("column2")
);
so in the above table, column2 is Unique&Not Null which means primary key??
I am trying to assign column2 as Foreign Key in another table but I get the error like below
ERROR: there is no unique constraint matching given keys for referenced table "Tablename"
SQL state: 42830
Note If I assign the column2 as Primary Key directly in the parent table, then I am able to assign it as a Foreign Key in the child table. Here I can't do that. I need help for the same!

The following worked from psql. Are you just having a syntax problem?
CREATE TABLE foo
(column2 integer not null,
FOREIGN KEY (column2) REFERENCES "Tablename"(column2)
);

Related

Foreign key references invalid table. Could not create constraint or index

I'm trying to create a table with 3 columns. The first column should be an identity column named DescriptionsID, the second column should be a foreign key column named ProductID, and the third column should be an xml column named Description. But, I'm receiving an error:
Foreign Key 'FK_ProductDescriptions_bacb18ce3aa67348e55d' references invalid table 'Product' and "Could not create constraint or index. See previous errors."
This is what I got:
CREATE TABLE ProductDescriptions (DescriptionsID int PRIMARY KEY NOT NULL,
ProductID varchar(25) NOT NULL,
FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
Description text NULL) ;
References Product(ProductID) has the error/red underlining
When you create a Referential Constraint, You Need to make sure that the Table and the Column which you are referring already exists in the Database.
Also, the Datatype of Both Referring Column and the Referred Column Should Be the Same
Column 'Product.ProductId' is not the same data type as referencing column
'ProductDescriptions.ProductID' in the foreign key
So Create Product Table First, and set the Product Id as Primary Key
CREATE TABLE Product
(
ProductId INT IDENTITY(1,1) PRIMARY KEY,
ProductName VARCHAR(50)
)
CREATE TABLE ProductDescriptions
(
DescriptionsID int PRIMARY KEY NOT NULL,
ProductID INT NOT NULL
,FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
[Description] text NULL
) ;

H2 Composite Primary Key (fields get unique but not primary key)

I have a problem with a composite primary key in my h2 database table.
This is the create statement of the table:
CREATE TABLE IF NOT EXISTS TTColumn (
Name VARCHAR(15) NOT NULL,
TTName CHAR(8) NOT NULL,
Type VARCHAR(15) NOT NULL,
Length INTEGER NOT NULL,
Position INTEGER NOT NULL,
IsDBLogType BIT NOT NULL,
PRIMARY KEY(TTName,Name),
FOREIGN KEY(TTName) REFERENCES TrackingTable(Name))
(TTName is the name of the table for the columns, so its the same for each column of the table, but each column is unique in a table so its an composite key)
If i fill this table with data, i get the following exception
rg.h2.jdbc.JdbcSQLException: Eindeutiger Index oder Primärschlüssel verletzt: "CONSTRAINT_INDEX_E8 ON PUBLIC.TTCOLUMN(TTNAME) VALUES ('KIBLCOVI', 1)"
Unique index or primary key violation: "CONSTRAINT_INDEX_E8 ON PUBLIC.TTCOLUMN(TTNAME) VALUES ('KIBLCOVI', 1)"; SQL statement:
INSERT INTO TTColumn (Name,TTName,Type,Length,Position,IsDBLogType) VALUES (?,?,?,?,?,?) [23505-189]
As you can see the column "Name" is not part of the primary key anymore, like i defined in the create statement and i dont know why.
I have this problem in other tables too and adding the primary with alter table, after creating it, resolves in the same problem. When "Name" is the first column in the primary key, it gets the only column in the primary key, so the last entrys get removed.
I know, one solution would be to use id's, but I want to use a composite primary key, because i hate to add id's when its not necessary.
Is there something wrong with my create statement or do you have any other hints?
P.s. i tried the Version 1.4.189 and Version 1.3.176 as .jar (no server)
Edit:
Hmm, following the output from show columns:
NAME|VARCHAR(15)|NO|UNI|NULL|
TTNAME|CHAR(8)|NO|UNI|NULL|
TYPE|VARCHAR(15)|NO||NULL|
LENGTH|INTEGER(10)|NO||NULL|
POSITION|INTEGER(10)|NO||NULL|
ISDBLOGTYPE|BOOLEAN(1)|NO||NULL|
Somehow the column Name and TTName are UNI (Unique) but not a primary key.
if i change the order in the primary key declaration, the column TTName becomes a primary key field, but Name stays unique.

How to create database schema with shared primary foreign key?

My goal is to have a subtable whose primary key and foreign key both are the same column, and reference to an ID of the main table.
CREATE TABLE main_table(
id integer NOT NULL,
//some fields
)
CREATE TABLE test(
id integer NOT NULL,
name varchar,
CONSTRAINT test_pk PRIMARAY KEY (id),
CONSTRAINT test_fk FOREIGN KEY (fk_id)
REFERENCES main_table (id) MATCH SIMPLE
)
But this will create a table mapping with two columns: id[PK] and test_fk as foreign key column. How can I combine them?
You have misunderstood how the foreign key clause works. You list the names of existing columns in there. And listing the column names will create any new column. Any FK column must have already be defined in the "columns part" of the create table statement.
So your statement wouldn't work at all because the table test does not have a column named fk_id. You need to supply the name of the already defined column id there:
CREATE TABLE test(
id integer NOT NULL,
name varchar,
CONSTRAINT test_pk PRIMARAY KEY (id),
CONSTRAINT test_fk FOREIGN KEY (id) --- <<< this was wrong
REFERENCES main_table (id) MATCH SIMPLE
)

How can I have a foreign key that points to a computed column?

I have this table:
CREATE TABLE [dbo].[Question] (
[QuestionId] INT IDENTITY (1, 1) NOT NULL,
[Text] NVARCHAR (4000) NULL,
[QuestionUId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
);
I would like to create a foreign key linking QuestionUId in my other table AdminTestQuestion back to the QuestionUId in the Question table.
The referenced table '[dbo].[Question]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
Any advice would be much appreciated.
First of all: this is really NOT a computed column - it's just a regular column with a default constraint...
For a column in a table to be used for a foreign key reference, it must be either the primary key of that table, or it has to have a unique index on it.
So here, all you need to do is to add a unique index on your column
CREATE UNIQUE INDEX UIX_QuestionUid ON dbo.Question(QuestionUid)
and then you should be able to reference it as a foreign key.

Error upon creating tables in sqlplus

I'm new to sqlplus and was trying to run a sql script that creates a few tables, but once I try to run it, it gives me an error saying that the table or view doesnt exist and I dont know how to fix this error.
My script is:
drop table Borrower;
create table Borrower (
bid char(100) not null,
password char(100) not null,
name char(100) null,
address char(100) null,
phone char(100) null,
emailAddress char(100) null,
sinOrStNo char(100) null,
expiryDate date null,
--type ENUM('student','faculty','staff'),
type char(100) not null,
--CONSTRAINT Btype_check CHECK (type IN ('student','faculty','staff')),
FOREIGN KEY (type) references BorrowerType(type),
PRIMARY KEY (bid));
grant select on Borrower to public;
"unique/primary keys in table referenced by foreign keys "
Data integrity is crucial to a properly run database so Oracle will not let us drop a table if its primary key is referenced by another table's foreign key. So it hurls ORA-02449.
So, given this set up:
create table t_parent (
id number not null
, constraint tp_pk primary key (id)
);
create table t_child (
id number not null
, p_id number not null
, constraint tc_pk primary key (id)
, constraint tc_tp_fk foreign key (p_id)
references t_parent (id)
);
There are three ways to drop table t_parent.
run drop table t_child first: no child table, no foreign key.
Remove the blocking foreign key: alter table t_child drop constraint tc_pc_fk.
A variant on the previous one, let the database figure out the foreign keys:
drop table t_parent cascade constraints.
The first option is the most proper, because it leaves the database in a valid state (no tables, no possibility of data integrity corruption). The valid use for the third approach is a script which razes all the tables from a schema: it's easy to generate such a script from the data dictionary.
The order that you drop or create tables are important because if you have foreign keys referencing another table, you cant delete that table before deleting your own table.
In this example, the Borrower table has to be dropped before the BorrowerType table.

Resources