Getting an error of invalid identifier when try to create relationship between two tables in Oracle SQL developer? [duplicate] - sql

This question already has an answer here:
A CREATE statement with quoted fields in Oracle
(1 answer)
Closed 1 year ago.
This is my device table
CREATE TABLE "DEVICE" (
"IMEI_Number" varchar(15),
"Device_Model" varchar(30),
"Device_Description" varchar(500),
"Assigned_Sim_Number" varchar(11),
"Activation_Date" timestamp,
"Deactivation_Date" timestamp,
"Manufacturer_ID" int,
"Customer_ID" int,
PRIMARY KEY ("IMEI_Number")
);
Then I have the manufacturer table which is
CREATE TABLE "MANUFACTURER" (
"Manufacturer_ID" int,
"Manufacturer_Name" varchar(30),
PRIMARY KEY ("Manufacturer_ID")
);
and I trying to create a relationship between these and getting the ORA-00904: "MANUFACTURER_ID": invalid identifier
My relationship code is
ALTER TABLE DEVICE
ADD FOREIGN KEY (Manufacturer_ID) REFERENCES MANUFACTURER(Manufacturer_ID);

That's just awful. Don't use double quotes when creating objects in Oracle as you'll have to use them every time you reference those objects, and match letter case every time.
SQL> alter table device add constraint fk_mf foreign key ("Manufacturer_ID")
2 references manufacturer ("Manufacturer_ID");
Table altered.
SQL>
A better option would be
SQL> create table device (
2 imei_number varchar2(15),
3 device_model varchar2(30),
4 device_description varchar2(500),
5 assigned_sim_number varchar2(11),
6 activation_date timestamp,
7 deactivation_date timestamp,
8 manufacturer_id int,
9 customer_id int,
10 primary key (imei_number)
11 );
Table created.
SQL> create table manufacturer (
2 manufacturer_id int,
3 manufacturer_name varchar2(30),
4 primary key (manufacturer_id)
5 );
Table created.
SQL> alter table device add constraint fk_mf foreign key (manufacturer_id)
2 references manufacturer (manufacturer_id);
Table altered.
SQL>
(Note also VARCHAR2 datatype; use that instead of VARCHAR).
By default, Oracle stores names in uppercase into data dictionary, but you can reference them using any case you want (upper, lower, mixed). If you do use double quotes, then you have to use their names exactly as during creation phase.

The columns in the tables you've created are surrounded by double-quotes, making their names case-sensitive, while the alter statement does not use quotes, and thus can't match the case-sensitive column name.
The best practice would be to drop these quotes and make the column names case-insensitive. If this is not an option, you could use the same quotes in the alter statement too:
ALTER TABLE DEVICE
ADD FOREIGN KEY ("Manufacturer_ID") REFERENCES MANUFACTURER("Manufacturer_ID");
-- Here ---------^---------------^--------------------------^---------------^

Related

creating a table with Foreign key in it gives error ORA-00904: : invalid identifier in oracle 10g [duplicate]

This question already has answers here:
Creating table via SQL Command Line, invalid identifier
(3 answers)
Closed 3 years ago.
Image of the code with table, query and error
I have oracle 10g installed on my computer. I have created a table in it named STUDENT and this STUDENT table has a primary key called RNO and now I want to create another table named FEE and make this RNO key into a foreign key in FEE table with the following query:
CREATE TABLE FEE ( RNO NUMBER(2), Amount number(20) Not Null, Date varchar2(10) Not Null, Receipt Number(10) Not Null, CONSTRAINT FEEFK FOREIGN KEY (RNO) REFERENCES STUDENT (RNO));
Now I have done all I could to correct it but just can't seem to find any problem or error with this query above. The Query gives the following error in Oracle 10g:
ORA-00904: : invalid identifier
Column name can't be DATE, it is reserved for datatype. Rename it to, say, CDATE.
SQL> CREATE TABLE student (rno NUMBER (2) PRIMARY KEY);
Table created.
SQL> CREATE TABLE FEE
2 (
3 RNO NUMBER (2),
4 Amount NUMBER (20) NOT NULL,
5 cDate VARCHAR2 (10) NOT NULL,
6 Receipt NUMBER (10) NOT NULL,
7 CONSTRAINT FEEFK FOREIGN KEY (RNO) REFERENCES STUDENT (RNO)
8 );
Table created.
SQL>
Use double qoutes "Date" or rename your column Date as some other name like DateColumn as Date is a reserved name fpr date types in oracle

SQL Integrity constraint-Parent key not found

I have looked over the internet and their solutions wont fix my problem, hence I'm asking for help here to check if there's mistakes in my coding.
I wanted to create a temporary table populated by other source tables and then implement it into the fact table. I have checked if the data type and the parameter is matching or the sequence of the keys but still it's giving me the error
"ORA-02291: integrity constraint (SYSTEM.SYS_C007167) violated -
parent key not found"
Fact Table:
CREATE TABLE DW_ITEMS7364 (
DW_ID int not null,
ManID char(5),
WHID char(5),
STKID char(5),
Profit number,
CONSTRAINT DW_ID PRIMARY KEY (DW_ID),
FOREIGN KEY(ManID) REFERENCES DW_MANUFACTURER7364,
FOREIGN KEY(WHID) REFERENCES DW_WAREHOUSE7364,
FOREIGN KEY(StkID) REFERENCES DW_STOCKITEM7364);
CREATE SEQUENCE seq_items7364 START WITH 101 increment by 1;
CREATE TRIGGER trg_items7364 BEFORE INSERT OR UPDATE ON DW_ITEMS7364
FOR EACH ROW
BEGIN
SELECT seq_items7364.NEXTVAL
INTO :new.DW_ID
FROM dual;
END;
Temporary Table:
CREATE TABLE TEMP_TAB7364 AS( SELECT m.ManID, w.WHID, s.STKID, (s.SellingPrice-s.PurchasePrice) AS "Profit"
FROM MANUFACTURER7364 m LEFT OUTER JOIN STOCKITEM7364 s ON s.ManID = m.ManID
RIGHT OUTER JOIN WAREHOUSE7364 w on s.WHID = w.WHID WHERE s.SELLINGPRICE IS NOT NULL AND s.PURCHASEPRICE IS NOT NULL
);
These are my source tables:
CREATE TABLE MANUFACTURER7364(
ManID char(5),
ManName varchar (25),
CityID char(5) NOT NULL,
PRIMARY KEY(ManID),
FOREIGN KEY(CityID) REFERENCES CITY7364);
CREATE TABLE WAREHOUSE7364(
WHID char(5),
MaxNoOfPallets number,
CostPerPallet number,
SecurityLevel char(1),
FreezerFacilities varchar(10),
QuarantineFacilities varchar(10),
CityID char(5) NOT NULL,
PRIMARY KEY(WHID),
FOREIGN KEY(CityID) REFERENCES CITY7364);
CREATE TABLE STOCKITEM7364(
StkID char(5),
StkName varchar(20),
SellingPrice number,
PurchasePrice number,
ManID char(5) NOT NULL,
WHID char(5) NOT NULL,
PRIMARY KEY(StkID),
FOREIGN KEY(ManID) REFERENCES MANUFACTURER7364,
FOREIGN KEY(WHID) REFERENCES WAREHOUSE7364);
As far as I can tell, nothing of what you posted raises that error.
Additional drawback is the way you chose to create foreign key constraints. If you don't name it, Oracle assigns the name itself and it looks the way you posted it: SYSTEM.SYS_C007167.
SQL> create table test
2 (id_dept number,
3 id_emp number,
4 foreign key (id_dept) references dept (deptno),
5 foreign key (id_emp) references emp (empno));
Table created.
SQL> select constraint_name from user_constraints where table_name = 'TEST';
CONSTRAINT_NAME
------------------------------
SYS_C008172
SYS_C008173
SQL>
When one of these fails, looking at its name you have no idea what went wrong, unless you investigate a little bit more:
SQL> select column_name from user_cons_columns where constraint_name = 'SYS_C008173';
COLUMN_NAME
-----------------------
ID_EMP
SQL>
But, if you name the constraint, it is way simpler:
SQL> create table test
2 (id_dept number,
3 id_emp number,
4 constraint fk_test_dept foreign key (id_dept) references dept (deptno),
5 constraint fk_test_emp foreign key (id_emp) references emp (empno));
Table created.
SQL> select constraint_name from user_constraints where table_name = 'TEST';
CONSTRAINT_NAME
------------------------------
FK_TEST_DEPT
FK_TEST_EMP
SQL>
Another major drawback one notices is what's written in front of the dot, here: SYSTEM.SYS_C007167. Yes, that would be SYSTEM. Shortly, don't do that. Leave SYS and SYSTEM alone; they are powerful, they are special. Why would you take the risk of destroying the database if you (un)intentionally do something hazardous? Create another user, grant required privileges and work in that schema.
If I understood you correctly, once you create that temp table (TEMP_TAB7364), its contents is transferred into the DW_ITEMS7364 and - doing so - you hit the error.
If that's so, what's the purpose of the temp table? Insert directly into the target table and save resources. Will it fail? Of course it will, unless you change the query. How? I don't know - make sure that you don't insert values that don't exist in any of three tables used for enforcing referential integrity.
Though, as you already have the temp table, if it isn't too large, a (relatively) quick & dirty way of finding out which row is responsible for the error can be found with a loop, such as
begin
for cur_r in (select col1, col2, ... from temp_table) loop
begin
insert into target (col1, col2, ...)
values (cur_r.col1, cur_r.col2, ...);
exception
when others then
dbms_output.put_line(sqlerrm ||': '|| cur_r.col1 ||', '||cur_r.col2);
end;
end loop;
end;
The inner BEGIN-END block is here to make sure that the PL/SQL code won't exit at the first error, but will display them all. Then review those values and find the reason that makes your query invalid.

Error in primary key in sqlplus?

I am beginner in sql.I am using sqlplus to run the sql query .I used simple query but it shows an error like "MISSING RIGHT PARENTHESIS".My objective is to create the autoincrement primary key .Can anyone solve the error?Thanks in advance...
create table student(rollno int identity(1,1) primary key,
name varchar(20),marks int);
For Oracle, the rollno column could be defined as NUMBER(0010) and primary key.
Then you would need to add an ON INSERT trigger to populate rollno from a SEQUENCE. There are many samples of triggers and sequences on this site.
In oracle 12 you can use a identity column to automatically fill your ID
CREATE TABLE students
(
"ID" NUMBER GENERATED BY DEFAULT AS IDENTITY MINVALUE 1 MAXVALUE 9999999999
INCREMENT BY 1 START WITH 1 ,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
This creates a table without any triggers needed and automatically fills the id column (of not specified with a value) with the next number up to 99999...
If you're using oracle 11 and below, you need a trigger on insert and assign a value (custom_sequence.nextval) to the id column.
CREATE TABLE students
(
"ID" NUMBER(5,0) not null,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
CREATE SEQUENCE SEQ_STUDENTS INCREMENT BY 1 START WITH 1;
/
TRIGGER TC_students
before insert on students
for each row
begin
if (:new.id is null) then
select SEQ_students.nextval into :new.id from dual;
end if;
end;
/
And please use VARCHAR2.

Remove Unique constraint on a column in sqlite database

I am trying to remove a UNIQUE constraint on a column for sqlite but I do not have the name to remove the constraint. How can I find the name of the UNIQUE constraint name to remove it.
Below is the schema I see for the table I want to remove the constraint
UNIQUE (datasource_name)
sqlite> .schema datasources
CREATE TABLE "datasources" (
created_on DATETIME NOT NULL,
changed_on DATETIME NOT NULL,
id INTEGER NOT NULL,
datasource_name VARCHAR(255),
is_featured BOOLEAN,
is_hidden BOOLEAN,
description TEXT,
default_endpoint TEXT,
user_id INTEGER,
cluster_name VARCHAR(250),
created_by_fk INTEGER,
changed_by_fk INTEGER,
"offset" INTEGER,
cache_timeout INTEGER, perm VARCHAR(1000), filter_select_enabled BOOLEAN, params VARCHAR(1000),
PRIMARY KEY (id),
CHECK (is_featured IN (0, 1)),
CHECK (is_hidden IN (0, 1)),
FOREIGN KEY(created_by_fk) REFERENCES ab_user (id),
FOREIGN KEY(changed_by_fk) REFERENCES ab_user (id),
FOREIGN KEY(cluster_name) REFERENCES clusters (cluster_name),
UNIQUE (datasource_name),
FOREIGN KEY(user_id) REFERENCES ab_user (id)
);
SQLite only supports limited ALTER TABLE, so you can't remove the constaint using ALTER TABLE. What you can do to "drop" the column is to rename the table, create a new table with the same schema except for the UNIQUE constraint, and then insert all data into the new table. This procedure is documented in the Making Other Kinds Of Table Schema Changes section of ALTER TABLE documentation.
I just ran into this myself. An easy solution was using DB Browser for SQLite
It let me remove a unique constraint with just a checkbox in a gui.
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE table_name RENAME TO old_table;
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
);
INSERT INTO table_name SELECT * FROM old_table;
COMMIT;
PRAGMA foreign_keys=on;
Source: https://www.techonthenet.com/sqlite/unique.php
I was just working through this issue on a small database and found it easier to dump the data as SQL statements, it prints out your tables exactly as they are and also adds the INSERT INTO statements to rebuild the DB.
The .help terminal command shows:
.dump ?OBJECTS? Render database content as SQL
and prints the SQL to the terminal, you can update it in a TXT file. For once off changes and tidying this seems like a reasonable solution albeit a little inelegant

Oracle creating Table using super class attribute as primary key

I have a sales_person_type defined as follows:
CREATE OR REPLACE TYPE sales_person_type UNDER person_type (
salesAppointments sales_person_appointments
);
this is a subclass of the person_type defined as such:
CREATE OR REPLACE TYPE person_type AS OBJECT (
personID NUMBER,
forename VARCHAR2(30),
surname VARCHAR2(20),
dateOfBirth DATE
) NOT FINAL;
I'm trying to create a table of sales persons and specifying the primary key as the super class attribute like this:
CREATE TABLE sales_person_table OF sales_person_type (
PRIMARY KEY (personID),
OBJECT IDENTIFIER IS PRIMARY KEY)
NESTED TABLE salesAppointments STORE AS sale_appointment_table (
(PRIMARY KEY(NESTED_TABLE_ID, appointmentID))
ORGANIZATION INDEX COMPRESS)
RETURN AS LOCATOR
But I'm getting this error:
SQL Error: ORA-02330: datatype specification not allowed
02330. 00000 - "datatype specification not allowed"
*Cause: An attempt was made to specify the data type in the column
constraint specification of an object table.
I'm think it's because im trying to assign the primary key as the super class attibute? Is this the correct syntax for this?
Cheers.
EDIT:
Works now, thanks Dimitry.
Check the syntax of CREATE TABLE for OID clause:
SQL> CREATE OR REPLACE TYPE person_type AS OBJECT (
2 personID NUMBER,
3 forename VARCHAR2(30),
4 surname VARCHAR2(20),
5 dateOfBirth DATE
6 ) NOT FINAL;
7 /
SQL> create or replace type sale_appointment is object
2 (
3 appointmentID integer
4 );
5 /
Тип создан.
SQL> create type sales_person_appointments as table of sale_appointment;
2 /
SQL> CREATE OR REPLACE TYPE sales_person_type UNDER person_type (
2 salesAppointments sales_person_appointments
3 );
4 /
SQL> CREATE TABLE sales_person_table OF sales_person_type (
2 PRIMARY KEY (personID)
3 )
4 OBJECT IDENTIFIER IS PRIMARY KEY
5 NESTED TABLE salesAppointments STORE AS sale_appointment_table (
6 (PRIMARY KEY(NESTED_TABLE_ID, appointmentID))
7 ORGANIZATION INDEX COMPRESS)
8 RETURN AS LOCATOR
9 /
Table created.