"references" statement in SQL - sql

I have a table in SQL like;
table Court
CourtID numeric(4) primary key
Name varchar(40) not null
Place varchar(40) not null
Type varchar(3) not null
TypeID numeric(4) references Court(CourtID) default null
I could not find info about what that reference statement stands for and how does it relate TypeID with CourtID?

It is simply shorthand syntax for a FOREIGN KEY.
All sorts of Google results are found with "sql references keyword"
Or simply trying it can often help more than a Google search (the old fashioned way).
Your example shows a self-referential foreign key. It is a common pattern seen to model relationships like PARENT or SPOUSE, where all records belong in the same base table, but may reference each other.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> create table court(
2 courtid integer primary key,
3 typeid integer references court(courtid)
4 );
Table created.
SQL> insert into court values(1,0);
insert into court values(1,0)
*
ERROR at line 1:
ORA-02291: integrity constraint (MSMITH.SYS_C0016710) violated - parent key not
found
SQL> insert into court values(1,1);
1 row created.
The above syntax will generate a "random" name for the constraint. A better syntax is to explicitly name the constraint. Notice what happens if I recreate it with additional FOREIGN KEY syntax.
SQL> create table court(
2 courtid integer primary key,
3 typeid integer,
4 constraint fk_typeid foreign key (typeid) references court(courtid)
5 );
Table created.
SQL> insert into court values(1,0);
insert into court values(1,0)
*
ERROR at line 1:
ORA-02291: integrity constraint (MSMITH.FK_TYPEID) violated - parent key not
found
The key is now named FK_TYPEID rather than SYS_C0016710

Related

Create primary key for table with period (Temporal Validity) in Oracle SQL

I have a question regarding to primary key for Oracle Table with Period.
I have created two tables like following:
create table el_temporal_try( -- Parent Table
id number(10) not null,
ColumnA varchar(10),
constraint el_temporal_try_pk primary key (id),
period for valid_period
);
create table el_temporal_try_son( -- Son Table
id number(10) not null,
ColumnA varchar(10),
parent_id number(10),
constraint el_temporal_try_FY foreign key (parent_id) references el_temporal_try(id),
period for valid_period
);
This script gone through successfully. However I have problem with inserting data:
I have executed following two insert statements into the parent table:
1st: statement
insert into el_temporal_try
(id, columnA,valid_period_start, valid_period_end)
values
(1,'A',sysdate - 10, sysdate - 9);
Result:
1 row inserted.
2nd: statement
insert into el_temporal_try
(id, columnA,valid_period_start, valid_period_end)
values
(1,'B',sysdate - 8, sysdate - 7);
Result
ORA-00001: unique constraint (PBSVW.EL_TEMPORAL_TRY_PK) violated
I understand it is because of the "ID" column. However, my issues because this two rows are for a different period, should it be allowed?
I was intended to use this period for feature to capture the change history of a record as an alternative to flashback. However, does it means that I should not use primary key at this situation?
Thanks in advance!
The problem is related to the id column like you said. it's not possible to add the registry because the primary key is unique, then your second insert statement references the same ID from the first. You need to change the ID always you insert a line.
On Oracle 12c, you can use the identity like this link.
https://www.oracletutorial.com/oracle-basics/oracle-identity-column/
in another version, you can use sequence and trigger to do this.
https://chartio.com/resources/tutorials/how-to-define-an-auto-increment-primary-key-in-oracle/
Thanks for everyone's help on this. This most likely means I cannot use Primary Key/Foreign Key to maintain the referential integrity between the parent and son for my situation within a particular timestamp, but I have to go for something else.
Thanks a lot!

Issue while updating Primary and foreign key using deferred FK

I am trying to update my primary and foreign key. After searching a lot, I came across the concept of a deferred key. I am able to update my PK and FK using SQLscript in PL/SQL. However I am getting an error while doing the same thing using PHP. Below is my code for PHP.
$update_p="update project set project_id='$projectname' where project_id='$previousproject'";
$up=oci_parse($conn,$update_p);
$update_m="update members set project='$projectname' where project='$previousproject'";
$um=oci_parse($conn,$update_m);
$commit="commit";
$c=oci_parse($conn,$commit);
oci_execute($up);
oci_execute($um);
oci_execute($c);
echo"Project Updated!";
I don't know how you were able to do that in PL/SQL script, but it's not enough to declare a constraint as deferrable.
You should also mark a deferrable constraint as deferred in your transaction:
Specify DEFERRED to indicate that the conditions specified by the
deferrable constraint are checked when the transaction is committed.
So you need to make your constraints as deferred before updating the table.
This is because you need to explicitly set the session as well as the key to allow for deferred constraints.
If we assume the following environment:
create table tmp_1 (
pk number
, fk number
, constraint pk_tmp_1 primary key (pk)
);
create table tmp_2 (
pk number
, fk number
, constraint pk_tmp_2 primary key (pk)
, constraint fk_tmp_2 foreign key (fk) references tmp_1 (pk)
);
alter table tmp_1
add constraint fk_tmp_1
foreign key (fk)
references tmp_2(pk)
deferrable;
If you attempt an insert you'll get the following error:
SQL> insert into tmp_1 values (1, 2);
insert into tmp_1 values (1, 2)
*
ERROR at line 1:
ORA-02291: integrity constraint (MF.FK_TMP_1) violated - parent key not found
SQL> insert into tmp_2 values (2, 1);
insert into tmp_2 values (2, 1)
*
ERROR at line 1:
ORA-02291: integrity constraint (MF.FK_TMP_2) violated - parent key not found
However, by altering the session to set the constraints parameter to deferred this will work:
SQL> alter session set constraints = deferred;
Session altered.
SQL>
SQL> insert into tmp_1 values (1, 2);
1 row created.
SQL> insert into tmp_2 values (2, 1);
1 row created.
Here, deferred "indicates that the conditions specified by the deferrable constraint are checked when the transaction is committed" as opposed to when the DML occurs.
Though circular dependencies can sometimes be necessary Oracle doesn't go out of it's way to make life easy for you - it shouldn't. If you have circular dependencies it's always worth re-evaluating your data-model to ensure that these are required.

Why this sql query doesn't return any error?

When i run these queries:
create table University ( branch text primary key, region text, enrollment int);
create table Student ( sID int primary key, sName text, average int);
create table Apply ( sID int references Student(sID), branch text references University(branch), major text, decision text);
insert into Apply values ( 123, 'stanford', 'CS', 'Y');
It should return an error because i am inserting a tuple that doesn't have a Corresponding value in the reference table. but when i run these commands, this tuple inersts Successfully. What's wrong with this queries?
My DBMS is sqlite and i'm using sqliteman.
You should learn how to enable foreign key support
Quoting docs:
In order to use foreign key constraints in SQLite, the library must be
compiled with neither SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER
defined. If SQLITE_OMIT_TRIGGER is defined but SQLITE_OMIT_FOREIGN_KEY
is not, then SQLite behaves as it did prior to version 3.6.19 -
foreign key definitions are parsed and may be queried using PRAGMA
foreign_key_list, but foreign key constraints are not enforced. The
PRAGMA foreign_keys command is a no-op in this configuration. If
OMIT_FOREIGN_KEY is defined, then foreign key definitions cannot even
be parsed (attempting to specify a foreign key definition is a syntax
error).
Also read sqliteman constraint triggers:
There is one more unsupported SQL feature. Sqlite does not enforce
foreign keys and not null constraints.

Error report: SQL Error: A foreign key value has no matching primary key value. Completely baffled

I can safely say that I am new to SQL and therefore upon writing the code to insert data into a table, I received an error report, that I can't seem to understand what it means, therefore I am hoping someone out there may be able to tell me what silly mistake I am making and remove a lot of stress ^.^
This is the error code I got:
Error report:
SQL Error: ORA-02291: integrity constraint (H.VENDOR_ID_FK) violated - parent key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
Thanks in advance!
If I run all of that I get several errors before this point, which I'll skip over for now... the first one against this FK seems to be:
INSERT INTO parts_order VALUES
(2
,2
,95115995
,'Delivered'
,'04/dec/2012'
,'01/jan/2013'
,'20/dec/2012'
,'Handler Pro'
);
It's better to put the columns in the insert clause so you can see what lines up (i.e. INSERT INTO parts_order (order_id, job_id, vendor_id, ...) VALUES (4, 4, 95115995, ...), and also so you (and we) don't have to refer back to the table definition, and to avoid failures if the definition changes in the future. It's also better not to rely on implicit date conversions (i.e. use to_char('05/jan/2013', 'DD/mon/YYYY').
Anyway... the constraint it's complaining about is VENDOR_ID_FK, which we can see in the table definition:
CREATE TABLE parts_order
( order_id NUMBER(11)
CONSTRAINT order_id_pk PRIMARY KEY
,job_id NUMBER(11)
CONSTRAINT job_id_fk REFERENCES maintenance(job_id)
,vendor_id NUMBER(11)
CONSTRAINT vendor_id_fk REFERENCES parts_vendor(part_vendor_id)
,parts_status VARCHAR2(20)
,date_ordered DATE
,date_arrived DATE
,date_delivery_due DATE
,part_name VARCHAR2(20)
CONSTRAINT part_name_nn NOT NULL);
... is against parts_vendor(part_vendor_id). What the error is saying is that the vendor_id you're inserting, 95115995, doesn't exist in the parent parts_vendor table - which is true, you only insert records with part_vendor_id values 1, 2, 3 and 4.
The constraint is working as intended - it's stopping you putting a 'child' record in without its 'parent' existing. You either need to create a parts_vendor record for ID 95115995, or change the vendor_id value you're trying to insert into parts_order to one that already exists.

ORA-02437: cannot validate <name> - primary key violated

I have a table:
CREATE TABLE MY_TABLE (
MY_ID NUMBER NOT NULL,
COLUMN_1 NUMBER,
COLUMN_2 NUMBER
);
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID);
at a later point, when executing the following sql, I get an error:
ALTER TABLE MY_TABLE DROP PRIMARY KEY DROP INDEX;
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
ORA-02437: cannot validate PK_FOO - primary key violated
My table only contains 3 entries all with a different primary key which is also not null.
Anyone has an idea what this could be?
Thanks,
Peter
My table only contains 3 entries all with a different primary key which is also not null.
You must forgive a certain amount of scepticism on our part. Because that error definitely indicates a duplicate value.
What you need to do is use the exceptions clause. This will show you the ROWIDs of the records which are violating your constraint. You may need to create the target table: by default the script creates a table called EXCEPTIONS:
SQL> ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID);
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
*
ERROR at line 1:
ORA-02437: cannot validate (APC.PK_FOO) - primary key violated
SQL> #%ORACLE_HOME%\rdbms\admin\utlexpt1.sql
Table created.
SQL> ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
2 exceptions into exceptions
3 /
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
*
ERROR at line 1:
ORA-02437: cannot validate (APC.PK_FOO) - primary key violated
SQL> select * from exceptions
2 /
ROW_ID OWNER TABLE_NAME CONSTRAINT
------ ----- ---------- ----------
AABQXcAAEAAAXUPAAD APC MY_TABLE PK_FOO
AABQXcAAEAAAXUPAAB APC MY_TABLE PK_FOO
SQL>
Edit
You need to figure out what is different between your install code and the simplification you posted here. The chances are you have one or more INSERT statements which are accidentally executed more than once while the constraint is not in force. Adding the EXCEPTIONS INTO clause to your code might help you track it down.
from here
Cause: You tried to tried to enable a
primary key constraint, but the
columns in the primary key either
contained NULL values or duplicates..
The maim reason of violation of primary ki is the atrrbute you making is nullable or you have some dupliactes in table for that id or attribute
create table client_master
(
client_no varchar2(6),
client_name varchar2(20),
city varchar2(25),
state varchar2(15),
pin number(6),
balance_due number(10,2));
for e.g,
after inserting values
0008 Mukul NYCT NYC 199560 2500
0006 Rukmini bombay maharastra 100001 0
0007 Krishna mathura up 900050 100000
0008 Mukul NYCT NYC 199560 2500
or your id is nullable
so just MODIFY THE ATTRIBUTE is and set to NOT NULL
also remove duplicates if any
DELETE client_master
WHERE rowid NOT IN
(SELECT MAX(rowid)
FROM client_master
GROUP BY client_no,client_name,city,state,pin,balance_due);
then you we will be able to add primary key to client _no
Are 2 primary keys identical?
This error is usually thrown when you try to create/enable a primary key on a table
I'm upvoting APC's answer, but since you seem to have some problems implementing it, could you just post the results of this query:
select my_id, count(*) from my_table group by my_id having count(*) >1
This will give us (and you) some idea of the problematic keys.