How to add primary key constraint on two columns to make composite key in oracle? - composite-key

I am new to here, please help me to find an answer to the below query.
"How to add a primary key constraint on two columns to make a composite key column in a table?"
Instead of writing so many lines, kindly provide the answer as short as possible with code.
(I am creating a table in which I can have only one primary key on the values of two-columns as a composite key.)
JacknJill

You can create such constraint in scope of CREATE TABLE operator
CREATE TABLE foo (
id INTEGER,
name VARCHAR(25),
bar VARCHAR(255),
CONSTRAINT foo_pk PRIMARY KEY (id,name)
);
or ALTER TABLE operator
CREATE TABLE foo (
id INTEGER,
name VARCHAR(25),
bar VARCHAR(255)
);
ALTER TABLE foo ADD CONSTRAINT foo_pk PRIMARY KEY (id,name);

Related

drop foreign key constraint on DB2 table through alter table

I have a DB2 (for IBMi) table created as below. I would like to drop the forign key constraint while running in an SQLRPGLE program. Is this possible?
create table grid_action_details(id integer not null
generated always as identity
(start with 1 increment by 1)
PRIMARY KEY,grid_details_id integer,foreign key(grid_details_id)
references grid_details(id),action_code_details_id integer,
foreign key(action_code_details_id)
references action_code_details(id),action_code_status varchar(2),
created_date date default
current_date,created_by varchar(30),
last_updated_date date default current_date,updated_by
varchar(30),required_parameter clob);
I tried the below syntax but it just doesn't seem to work for me:
ALTER TABLE table-name
DROP FOREIGN KEY foreign_key_name
alter table iesqafile.grid_action_details
drop foreign key action_code_details_id
ACTION_CODE_DETAILS_ID in IESQAFILE type *N not found.
You drop the FK constraint via name, not via column.
Since you didn't specify one during create, you'll need to look to see what name the system generated.
Always a best practice to name things yourself.
CONSTAINT <name> FOREIGN KEY (<columns>)
create table grid_action_details (
id integer not null generated always as identity (
start with 1 increment by 1
)
,constraint grid_action_details_pk
primary key
,grid_details_id integer
,constraint grid_details_fk
foreign key (grid_details_id)
references grid_details (id)
,action_code_details_id integer
,constraint action_code_details_fk
foreign key (action_code_details_id)
references action_code_details (id)
,action_code_status varchar(2)
,created_date date default current_date
,created_by varchar(30)
,last_updated_date date default current_date
,updated_by varchar(30)
,required_parameter clob
);
Now you can drop by the known name
alter table iesqafile.grid_action_details
drop foreign key action_code_details_fk
EDIT
To find the generated name use:
the ACS Schema component
DSPFD
SQL against one of the catalog views (QSYS2.SYSCST, SYSIBM.SQLFOREIGNKEYS, SYSIBM.REFERENTIAL_CONSTRAINTS )

want to link crew Assignment to above tables given I'm getting an error How to solve this error?

CREATE TABLE Route(
RouteNo VARCHAR(10),
Origin VARCHAR(30),
Destination VARCHAR(30),
DepartureTime VARCHAR(15),
SerialNo VARCHAR(5),
ArrivalTime VARCHAR(15),
PRIMARY KEY(RouteNo) );
CREATE TABLE Employee(
EmployeeID VARCHAR(5) NOT NULL,
Name VARCHAR(30),
Phone NUMBER,
JobTitle VARCHAR(30),
PRIMARY KEY(EmployeeID) );
CREATE TABLE Flight(
SerialNo VARCHAR(5),
RouteNo VARCHAR(5),
FlightDate DATE,
ActualTD VARCHAR(10),
ActualTA VARCHAR(10),
PRIMARY KEY(SerialNo, RouteNo, FlightDate),
FOREIGN KEY(RouteNo) REFERENCES Route(RouteNo),
FOREIGN KEY(SerialNo) REFERENCES Airplane(SerialNo) ); -- does Airplane table exists ?
CREATE TABLE CrewAssigment(
EmployeeID VARCHAR(5),
RouteNo VARCHAR(5),
FlightDate DATE,
Role VARCHAR(45),
Hours INT,
PRIMARY KEY(EmployeeID, RouteNo, FlightDate),
FOREIGN KEY(EmployeeID) REFERENCES Employee(EmployeeID),
FOREIGN KEY(RouteNo) REFERENCES Route(RouteNo),
FOREIGN KEY(FlightDate) REFERENCES Flight(FlightDate) );
Select * from CrewAssignment
This is my code where I'm getting an error in the CrewAssignment table and above are the tables where the foreign key is referenced from.
Error report -
ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
catalog view
A few objections.
This is clearly an Oracle question, not MySQL. How do I know? ORA-02270 is an Oracle database error code; pay attention to tags you use.
You should use VARCHAR2 datatype instead of VARCHAR. Why? Oracle recommends so.
create table flight fails first as it references the airplane table, and it doesn't exist yet (at least, not in code you posted)
error you're complaining about is due to create table crewassignment. One of its foreign keys references the flight table:
FOREIGN KEY(flightdate) REFERENCES flight(flightdate)
but flight's primary key is composite, made up of 3 columns:
PRIMARY KEY(serialno,
routeno,
flightdate)
which means that you can't create that foreign key.
So, what to do? No idea, I don't know rules responsible for such a data model. Either modify primary key of the flight table, or modify foreign key constraint of the crewassingment table.
Perhaps you could add a new column to flight table (made up of a sequence (or identity column, if your database version supports it) and then let the crewassignment table reference that primary key. Columns you currently use as a primary key (serialno, routeno, flightdate) would then switch to unique key.

Tried to have recursive relation

I use oracle and I try to have a recursive relation
CREATE TABLE "EVENT"
(
"EVENT_ID" NUMBER(18) NOT NULL, //primary key
"NAME" VARCHAR(20) NULL,
"RELATED_EVENT_ID" NUMBER(18) NULL //foreign key
);
Event 1 parent is Event 2....
When I try to create this table, I get this error.
ALTER TABLE "EVENT"
ADD CONSTRAINT "FK_RELATED_EVENT_ID"
FOREIGN KEY ("RELATED_EVENT_ID") REFERENCES "EVENT" ("RELATED_EVENT_ID")
Error report -
SQL Error: ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
catalog view
You have two problems:
There is no primary key constraint on this table.
The foreign key constraint you defined has RELATED_EVENT_ID referencing RELATED_EVENT_ID. I suspect that was just a typo.
Change your table definition to:
CREATE TABLE EVENT
(EVENT_ID NUMBER
NOT NULL
CONSTRAINT PK_EVENT
PRIMARY KEY
USING INDEX,
NAME VARCHAR2(20),
RELATED_EVENT_ID NUMBER);
Then add the foreign key constraint as
ALTER TABLE EVENT
ADD CONSTRAINT EVENT_FK1
FOREIGN KEY (RELATED_EVENT_ID) REFERENCES EVENT(EVENT_ID);
db<>fiddle here
EDIT
Note that the better way to handle this is to use a junction table, such as:
CREATE TABLE EVENT_EVENT
(EVENT_ID1 NUMBER
CONSTRAINT EVENT_EVENT_FK1
REFERENCES EVENT(EVENT_ID),
EVENT_ID2 NUMBER
CONSTRAINT EVENT_EVENT_FK2
REFERENCES EVENT(EVENT_ID),
CONSTRAINT PK_EVENT_EVENT
PRIMARY KEY (EVENT_ID1, EVENT_ID2)
USING INDEX);
Then you can drop the RELATED_EVENT_ID column from EVENT as you no longer need it.
According to oracle document :
Foreign key specifies that the values in the column must correspond to values in a
referenced primary key or unique key column or that they are NULL.
In your case, create primary key on column (EVENT_ID) and use it in reference clause as following:
ALTER TABLE "EVENT"
ADD CONSTRAINT "FK_RELATED_EVENT_ID"
FOREIGN KEY ("RELATED_EVENT_ID")
REFERENCES "EVENT" ("EVENT_ID") -- this
Now, use EVENT2's EVENT_ID as RELATED_EVENT_ID in EVENT1 record to make EVENT2 as parent of EVENT1.
Cheers!!

I'm trying to create foreign key between two tables but got: ORA-02270

Maybe I'm burnout, but I don't understand this. I have two tables in Oracle: TBL_a and TBL_x. I'm trying to create a foreign key between thos two tables as follows and get error
ORA-02270: no matching unique or primary key.
CREATE TABLE tbl_a (
cod_op integer,
cod_dni char(8),
cod_correl integer,
varchar2(50)
);
CREATE TABLE tbl_x (
cod_op integer,
cod_dni char(8),
blabla varchar2(50)
);
CREATE UNIQUE INDEX TBL_A_PK ON TBL_A (COD_OP);
CREATE UNIQUE INDEX TBL_x_PK ON TBL_x (COD_OP);
ALTER TABLE TBL_a ADD CONSTRAINT TBL_a_R01
FOREIGN KEY (COD_OP) REFERENCES TBL_x (COD_OP);
The problem is that you've created unique INDEXES on your tables, but you didn't create a unique or primary key CONSTRAINT. Oracle requires that the constraints exist in order to establish a foreign key relationship.
If you drop your existing indexes and add the appropriate constraints you can establish your foreign key relationship:
DROP INDEX TBL_A_PK;
DROP INDEX TBL_x_PK;
ALTER TABLE TBL_A
ADD CONSTRAINT UQ_A
UNIQUE(COD_OP)
USING INDEX;
ALTER TABLE TBL_X
ADD CONSTRAINT UQ_X
UNIQUE(COD_OP)
USING INDEX;
dbfiddle here
The table that is referred by the foreign key (here, tbl_x) must have a primary key or a unique constraint.
In your use case, as you are declaring a unique index on cod_op, you could simply make cod_op the primary key of tbl_x instead: that would make the error disappear.
Demo on DB Fiddle
In general, it is a good practice to have a primary key on any table. Extending the principe of turning your unique indexes to primary keys, your DDL statements could be simplified as follows:
CREATE TABLE tbl_x (
cod_op INTEGER PRIMARY KEY,
cod_dni CHAR(8),
blabla VARCHAR2(50)
);
CREATE TABLE tbl_a (
cod_op INTEGER PRIMARY KEY,
cod_dni CHAR(8),
cod_correl INTEGER,
blabla VARCHAR2(50),
CONSTRAINT TBL_a_R01 FOREIGN KEY (COD_OP) REFERENCES TBL_x (COD_OP)
);
Demo on DB Fiddle

Can two or more tables which share same foreign keys share a constraint on that foreign key?

What is the problem with this code??
It gives error "name already used by another constraint". Also if I can't define same constraint in different tables then is there any way I can reuse the previously defined constraint?
Any insight??
CREATE TABLE tbl_formats
(
format_id NUMBER(5),
format_name VARCHAR2(50),
format_desc VARCHAR2(100),
valid_from DATE,
valid_to DATE,
format_type VARCHAR2(50),
CONSTRAINT pk_format_id PRIMARY KEY(format_id)
);
CREATE TABLE tbl_format_detail
(
id NUMBER(10),
format_id NUMBER(5),
src_field VARCHAR2(200),
target_field VARCHAR2(100),
business_rule VARCHAR2(4000),
expression VARCHAR2(4000),
target_segment VARCHAR2(4),
CONSTRAINT pk_id PRIMARY KEY(id),
CONSTRAINT fk_format_id FOREIGN KEY(format_id) REFERENCES tbl_formats(format_id)
);
CREATE TABLE tbl_client_formats
(
client_format_id NUMBER(10),
format_id NUMBER(5),
client_id NUMBER(5),
CONSTRAINT pk_client_format_id PRIMARY KEY(client_format_id),
CONSTRAINT fk_format_id FOREIGN KEY(format_id) REFERENCES tbl_formats(format_id),
CONSTRAINT fk_client_id FOREIGN KEY(client_id) REFERENCES tbl_clients(client_id)
);
It seem like the foreign key constraint 'fk_format_id' defined in the table 'tbl_client_formats' conflicts with the same constraint already defined in the table 'tbl_format_detail'.
I am new to oracle so explain even the obvious things please.
The problem is that you're trying to use the same constraint name twice.
Just use a different name for your second constraint (e.g. fk_client_formats_format_id), and you should be fine.
Generally, I'd recommend using the table name as part of the constraint name, to avoid name clashes (if the constraint name gets too long, you'll have to use some kind of abbreviation scheme).
Foreign key are stored in a database range, not a table range. You cannot have two FK with the same name on the same database, even if they are not in the same table. You could name your FK that way:
FK_PARENT_CHILD_FIELD
ex:
FK_FORMATDETAILS_FORMATS_ID,
FK_CLIENTFORMATS_FORMATS_ID,
FK_CLIENTFORMATS_CLIENT_ID

Resources