I am getting ORA-00955 error which is name is already used by an existing object. I know it is in the foreign key constraint im trying to use. It happens in both foreign key constraints. I cant figure out why its happening. I tried renaming them to anything possible and I cant understand why it wont work.
DROP TABLE STUDENT;
CREATE TABLE STUDENT
(stuID VARCHAR (7) PRIMARY KEY NOT NULL,
major VARCHAR (15) NOT NULL,
firstName VARCHAR (15) NOT NULL,
lastName VARCHAR (15) NOT NULL,
yr VARCHAR(8) NOT NULL
);
DROP TABLE ENROLL;
CREATE TABLE ENROLL
(stuID VARCHAR (7) NOT NULL,
grade VARCHAR (1) NOT NULL,
courseID VARCHAR(7) NOT NULL,
CONSTRAINT fk_STUDENT
FOREIGN KEY (stuID)
REFERENCES STUDENT(stuid)
);
DROP TABLE CLASS;
CREATE TABLE CLASS
(instructorID VARCHAR(7) NOT NULL,
classRoomNumber VARCHAR(7) NOT NULL,
dateStarts DATE NOT NULL,
courseID VARCHAR(7) PRIMARY KEY NOT NULL,
description CHAR(100) NOT NULL,
CONSTRAINT fk_INSTRUCTOR
FOREIGN KEY (instructorID)
REFERENCES INSTRUCTOR(instructorid)
);
DROP TABLE INSTRUCTOR;
CREATE TABLE INSTRUCTOR
(firstName VARCHAR (15) NOT NULL,
lastName VARCHAR (15) NOT NULL,
departmentName VARCHAR (15) NOT NULL,
instructorID VARCHAR(7) PRIMARY KEY NOT NULL
);
In a comment, you said that there's still an error.
If you create (and/or drop) tables in a correct order, everything is OK. I prefer dropping them separately.
At first, tables don't exist so I'll just create them:
SQL> CREATE TABLE student (
2 stuid VARCHAR(7) PRIMARY KEY NOT NULL,
3 major VARCHAR(15) NOT NULL,
4 firstname VARCHAR(15) NOT NULL,
5 lastname VARCHAR(15) NOT NULL,
6 yr VARCHAR(8) NOT NULL
7 );
Table created.
SQL> CREATE TABLE enroll (
2 stuid VARCHAR(7) NOT NULL,
3 grade VARCHAR(1) NOT NULL,
4 courseid VARCHAR(7) NOT NULL,
5 CONSTRAINT fk_student FOREIGN KEY ( stuid )
6 REFERENCES student ( stuid )
7 );
Table created.
SQL> CREATE TABLE instructor (
2 firstname VARCHAR(15) NOT NULL,
3 lastname VARCHAR(15) NOT NULL,
4 departmentname VARCHAR(15) NOT NULL,
5 instructorid VARCHAR(7) PRIMARY KEY NOT NULL
6 );
Table created.
SQL> CREATE TABLE class (
2 instructorid VARCHAR(7) NOT NULL,
3 classroomnumber VARCHAR(7) NOT NULL,
4 datestarts DATE NOT NULL,
5 courseid VARCHAR(7) PRIMARY KEY NOT NULL,
6 description CHAR(100) NOT NULL,
7 CONSTRAINT fk_instructor FOREIGN KEY ( instructorid )
8 REFERENCES instructor ( instructorid )
9 );
Table created.
Drop tables in reverse order, so that detail is dropped before its master
SQL> DROP TABLE enroll;
Table dropped.
SQL> DROP TABLE student;
Table dropped.
SQL> DROP TABLE class;
Table dropped.
SQL> DROP TABLE instructor;
Table dropped.
SQL>
Table INSTRUCTOR is referenced by table CLASS, hence you heed to create table INSTRUCTOR before you create table CLASS.
Also, you should use DROP TABLE ... CASCADE CONSTRAINTS instead of just DROP TABLE .... This allows foreign and primary keys to be properly dropped at the same time as the table, and might avoid error name already used by existing object that you are currently getting.
Related
I have a SQL table based on hotel data. I have two tables and a bridge table to relate them. I'm still learning so I'm sure some of this is not ideal or has potential risks.
Guest Table
CREATE TABLE Guest
(
Guest_ID INT PRIMARY KEY IDENTITY (1, 1),
GuestName NVARCHAR(60) NOT NULL,
Street NVARCHAR(50) NOT NULL,
City NCHAR(30) NOT NULL,
[State] CHAR(2) NOT NULL,
CONSTRAINT [State.State]
FOREIGN KEY ([State]) REFERENCES [State]([State]),
Zip CHAR(5) NOT NULL,
Phone VARCHAR(15) NOT NULL
);
Room Table
CREATE TABLE Room
(
Room_ID SMALLINT PRIMARY KEY,
Room_Type_ID SMALLINT NOT NULL,
CONSTRAINT Room_Type_ID
FOREIGN KEY (Room_Type_ID) REFERENCES Room_Type([Type_ID]),
Amenity_Type_ID SMALLINT NOT NULL,
CONSTRAINT Amenity_Type_ID
FOREIGN KEY (Amenity_Type_ID) REFERENCES Amenity_Type([Type_ID])
);
Bridge Table (Reservations)
CREATE TABLE Guest_Bridge_Rooms
(
Guest_ID INT NOT NULL,
CONSTRAINT Guest_ID
FOREIGN KEY (Guest_ID) REFERENCES Guest(Guest_ID),
Room_ID SMALLINT NOT NULL,
CONSTRAINT Room_ID
FOREIGN KEY (Room_ID) REFERENCES Room(Room_ID),
Date_Start DATE NOT NULL,
Date_End DATE NOT NULL,
Occ_Adults SMALLINT NOT NULL,
Occ_Children SMALLINT NOT NULL,
Price_Total DECIMAL(13,2) NOT NULL
);
Now with these tables, I would like to write a script to DELETE all rows where a reservation (bridged table) has a specific guest NAME by somehow relating the given Guest_ID to its GuestName in the related table. I could simply use Guest_ID but that is not the goal here.
For example something like
DELETE FROM Guest_Bridge_Rooms
WHERE Guest[ID].GuestName = 'John Doe';
Is there a simple way to do this?
You can use a subquery:
DELETE FROM Guest_Bridge_Rooms
WHERE Guest_ID = (SELECT g.Guest_Id FROM Guests g WHERE g.GuestName = 'John Doe');
Note: The exact syntax might vary, depending on the database. This also assumes that GuestName is unique in Guests.
I tried to create several tables, but only the server table was created. Please fix my work!
CREATE TABLE server
(
SERVER_ID varchar(25) NOT NULL,
SERVER_IP varchar(15) NOT NULL,
SERVER_LOCATION varchar(25) NOT NULL,
SERVER_BRAND varchar(15) NOT NULL,
CONSTRAINT server_pk
PRIMARY KEY (SERVER_ID)
);
CREATE TABLE application
(
APP_ID varchar(25) NOT NULL,
ACCOUNT_NUM varchar(25) NOT NULL,
RECORD_ID varchar(10) NOT NULL,
VERSION_ID varchar(10) NOT NULL,
LAST_UPDATED date NOT NULL,
CONSTRAINT application_pk
PRIMARY KEY (APP_ID),
CONSTRAINT application _fk_account
FOREIGN KEY (ACCOUNT_NUM)
REFERENCES account (ACCOUNT_NUM),
CONSTRAINT application _fk_record
FOREIGN KEY (RECORD_ID)
REFERENCES record (RECORD_ID)
);
CREATE TABLE record
(
RECORD_ID varchar(25) NOT NULL,
VIN_NUM varchar(25) NOT NULL,
SERVER_ID varchar(25) NOT NULL,
CONSTRAINT record_pk
PRIMARY KEY (RECORD_ID, VIN_NUM, SERVER_ID),
CONSTRAINT record_fk_vehicle
FOREIGN KEY (VIN_NUM)
REFERENCES vehicle (VIN_NUM),
CONSTRAINT record_fk_server
FOREIGN KEY (SERVER_ID)
REFERENCES server (SERVER_ID)
);
CREATE TABLE vehicle
(
VIN_NUM varchar(25) NOT NULL,
V_MILEAGE int NOT NULL,
V_GASUSED varchar(25) NOT NULL,
V_ELECTRICALMILES int NOT NULL,
DRIVER_ID varchar(25) NOT NULL,
CONSTRAINT vehicle_pk
PRIMARY KEY (VIN_NUM),
CONSTRAINT vehicle_fk_driver
FOREIGN KEY (DRIVER_ID)
REFERENCES driver (DRIVER_ID)
);
CREATE TABLE driver
(
DRIVER_ID varchar(25) NOT NULL,
LICENSE_NUM varchar(25) NOT NULL,
FIRST_NAME varchar(25) NOT NULL,
LAST_NAME varchar(25) NOT NULL,
INSURANCE_POLICY varchar(25) NOT NULL,
ACCOUNT_NUM int NOT NULL,
CONSTRAINT driver_pk
PRIMARY KEY (DRIVER_ID),
CONSTRAINT driver_fk_account
FOREIGN KEY (ACCOUNT_NUM)
REFERENCES account (ACCOUNT_NUM)
);
CREATE TABLE account
(
ACCOUNT_NUM int NOT NULL,
DRIVER_ID varchar(25) NOT NULL,
DEVICE_ID varchar(25) NOT NULL,
DATE_CREATED date NOT NULL,
ACCOUNT_STATUS varchar(10) NOT NULL,
CONSTRAINT account_pk
PRIMARY KEY (ACCOUNT_NUM, DRIVER_ID),
CONSTRAINT account_fk_driver
FOREIGN KEY (DRIVER_ID)
REFERENCES driver (DRIVER_ID)
);
There are several issues here.
You should create tables in order that matches foreign key constraint dependencies, i.e. you can't create detail table first, and then its master table because there's no table (or its primary key) which is to be referenced.
A good workaround for that is to remove foreign key constraints from create table and create them separately (using alter table ... add constraint) after all tables are created.
There's no problem if two tables reference each other (such as driver and account do), if there's a good reason to do it. However, as I previously said - you can't do it within create table statements; at least one foreign key has to be moved out.
If primary key consists of several columns (so it is a composite key), foreign key also must contain the same number & datatypes of columns that reference it. That's what you have for driver and account tables.
account's primary key is (account_num, driver_id)
driver's foreign key can't be just (account_num) - it has to contain driver_id as well
Finally, application table: its foreign keys can't be created because it references
account table whose primary key is (account_num, driver_id), but - application doesn't contain driver_id column at all which might mean that you wrongly set account's primary key (or application table)
record table which has a composite primary key on (record_id, vin_num, server_id), while application has only record_id. Remark I wrote for account is valid here as well
Now, if we fix what I mentioned, tables are created, but application misses all its foreign key constraints.
SQL> CREATE TABLE server
2 (
3 SERVER_ID varchar2(25) NOT NULL,
4 SERVER_IP varchar2(15) NOT NULL,
5 SERVER_LOCATION varchar2(25) NOT NULL,
6 SERVER_BRAND varchar2(15) NOT NULL,
7 CONSTRAINT server_pk
8 PRIMARY KEY (SERVER_ID)
9 );
Table created.
SQL>
SQL> CREATE TABLE driver
2 (
3 DRIVER_ID varchar2(25) NOT NULL,
4 LICENSE_NUM varchar2(25) NOT NULL,
5 FIRST_NAME varchar2(25) NOT NULL,
6 LAST_NAME varchar2(25) NOT NULL,
7 INSURANCE_POLICY varchar2(25) NOT NULL,
8 ACCOUNT_NUM int NOT NULL,
9 CONSTRAINT driver_pk
10 PRIMARY KEY (DRIVER_ID)
11 --CONSTRAINT driver_fk_account
12 --FOREIGN KEY (ACCOUNT_NUM)
13 --REFERENCES account (ACCOUNT_NUM)
14 );
Table created.
SQL>
SQL> CREATE TABLE account
2 (
3 ACCOUNT_NUM int NOT NULL,
4 DRIVER_ID varchar2(25) NOT NULL,
5 DEVICE_ID varchar2(25) NOT NULL,
6 DATE_CREATED date NOT NULL,
7 ACCOUNT_STATUS varchar2(10) NOT NULL,
8 CONSTRAINT account_pk
9 PRIMARY KEY (ACCOUNT_NUM, DRIVER_ID),
10 CONSTRAINT account_fk_driver
11 FOREIGN KEY (DRIVER_ID)
12 REFERENCES driver (DRIVER_ID)
13 );
Table created.
SQL>
SQL> alter table driver add constraint driver_fk_account
2 foreign key (account_num, driver_id)
3 references account (account_num, driver_id);
Table altered.
SQL>
SQL> CREATE TABLE vehicle
2 (
3 VIN_NUM varchar2(25) NOT NULL,
4 V_MILEAGE int NOT NULL,
5 V_GASUSED varchar2(25) NOT NULL,
6 V_ELECTRICALMILES int NOT NULL,
7 DRIVER_ID varchar2(25) NOT NULL,
8 CONSTRAINT vehicle_pk
9 PRIMARY KEY (VIN_NUM),
10 CONSTRAINT vehicle_fk_driver
11 FOREIGN KEY (DRIVER_ID)
12 REFERENCES driver (DRIVER_ID)
13 );
Table created.
SQL>
SQL> CREATE TABLE record
2 (
3 RECORD_ID varchar2(25) NOT NULL,
4 VIN_NUM varchar2(25) NOT NULL,
5 SERVER_ID varchar2(25) NOT NULL,
6 CONSTRAINT record_pk
7 PRIMARY KEY (RECORD_ID, VIN_NUM, SERVER_ID),
8 CONSTRAINT record_fk_vehicle
9 FOREIGN KEY (VIN_NUM)
10 REFERENCES vehicle (VIN_NUM),
11 CONSTRAINT record_fk_server
12 FOREIGN KEY (SERVER_ID)
13 REFERENCES server (SERVER_ID)
14 );
Table created.
SQL>
SQL> CREATE TABLE application
2 (
3 APP_ID varchar2(25) NOT NULL,
4 ACCOUNT_NUM varchar2(25) NOT NULL,
5 RECORD_ID varchar2(10) NOT NULL,
6 VERSION_ID varchar2(10) NOT NULL,
7 LAST_UPDATED date NOT NULL,
8 CONSTRAINT application_pk
9 PRIMARY KEY (APP_ID)
10 --CONSTRAINT application_fk_account
11 --FOREIGN KEY (ACCOUNT_NUM)
12 --REFERENCES account (ACCOUNT_NUM),
13 --CONSTRAINT application_fk_record
14 --FOREIGN KEY (RECORD_ID)
15 --REFERENCES record (RECORD_ID)
16 );
Table created.
SQL>
You have to add a / after every table definition end -
CREATE TABLE server
(
SERVER_ID varchar(25) NOT NULL,
SERVER_IP varchar(15) NOT NULL,
SERVER_LOCATION varchar(25) NOT NULL,
SERVER_BRAND varchar(15) NOT NULL,
CONSTRAINT server_pk
PRIMARY KEY (SERVER_ID)
);
/ ----> Here
CREATE TABLE application
(
APP_ID varchar(25) NOT NULL,
.....
I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );
I have Oracle database. I want to create INDEX:
CREATE INDEX indexID ON Employee(id_employee);
But it writes -> SQL Error: ORA-01408: such column list already indexed
So before create index I put:
DROP INDEX indexID;
But it writes -> SQL Error: ORA-01418: specified index does not exist
my Employee table:
CREATE TABLE Employee (
id_employee NUMBER(5) NOT NULL,
name VARCHAR(25) NOT NULL,
surname VARCHAR(25) NOT NULL,
day_of_birth DATE NOT NULL,
salary NUMBER(6) NOT NULL,
PRIMARY KEY(id_employee)
);
Have you some idea? it looks like index does not create.
You have a different index on that column.
Say you create the table like this:
SQL> CREATE TABLE Employee (
2 id_employee NUMBER(5) NOT NULL ,
3 name VARCHAR(25) NOT NULL,
4 surname VARCHAR(25) NOT NULL,
5 day_of_birth DATE NOT NULL,
6 salary NUMBER(6) NOT NULL
7 );
Table created.
Then you add the PK constraint:
SQL> alter table employee add primary key(id_employee);
Table altered.
Now Oracle already created a unique index on the PK field, so you already have it, with no need for manual creation.
SQL> select index_name, column_name
2 from user_ind_columns c
3 inner join user_indexes i
4 using (index_name)
5 where i.table_name = 'EMPLOYEE';
INDEX_NAME COLUMN_NAME
-------------------- --------------------
SYS_C007892 ID_EMPLOYEE
In your example:
SQL> CREATE TABLE Zamestnanec (
2 id_zamestnance NUMBER(5) PRIMARY KEY ,
3 jmeno VARCHAR(25) NOT NULL,
4 prijmeni VARCHAR(25) NOT NULL,
5 datum_narozeni DATE NOT NULL,
6 prava CHAR(3) CHECK(prava IN ('ano', 'ne')) NOT NULL,
7 plat NUMBER(6) NOT NULL
8 );
Table created.
SQL> select index_name, column_name
2 from user_ind_columns c
3 inner join user_indexes i
4 using (index_name)
5 where i.table_name = 'ZAMESTNANEC';
INDEX_NAME COLUMN_NAME
-------------------- --------------------
SYS_C007899 ID_ZAMESTNANCE
I slightly modified your syntax; besides, you can avoid the NOT NULL constraint on a PK field: the PK will force the field to be NOT NULL.
See here for a similar problem.
The CREATE TABLE for ZAMESTNANEC is
CREATE TABLE Zamestnanec (
id_zamestnance NUMBER(5) NOT NULL,
jmeno VARCHAR(25) NOT NULL,
prijmeni VARCHAR(25) NOT NULL,
datum_narozeni DATE NOT NULL,
prava CHAR(3) CHECK(prava IN ('ano', 'ne')) NOT NULL,
plat NUMBER(6) NOT NULL,
PRIMARY KEY(id_zamestnance)
);
You've created a primary key constraint for ID_ZAMESTNANCE, which by default creates an index on ID_ZAMESTNANCE; thus you don't need to create another index on ID_ZAMESTNANCE.
I would suggest a freakish solution, but I guarantee you that it will work.
Drop the primary key constraint from the table.
ALTER TABLE Employee
DROP CONSTRAINT pk_id_employee
Drop the index, then…
Create the primary key constraint
the Staff table references the branch table
CREATE TABLE Staff(
StaffNo VARCHAR(5) NOT NULL,
firstName VARCHAR(15) NOT NULL UNIQUE,
lastName VARCHAR(15) NOT NULL,
position VARCHAR(10) NOT NULL,
salary INTEGER
DEFAULT 3000,
CHECK (salary BETWEEN 3000 AND 25000),
email VARCHAR(25),
branchNo CHAR(6) NOT NULL,
PRIMARY KEY (StaffNo),
FOREIGN KEY (branchNo) REFERENCES Branch (branchNo));
and at the same time the branch table references the Staff table
create table Branch(
branchNo char(6) not null primary key,
street varchar(30) not null,
city varchar(20),
postCode char(5) not null,
ManagerNo varchar(5) not null,
foreign key (ManagerNo) references Staff(StaffNo));
Since your tables reference each other in the Foreign Keys you will get an error on either table creation if the other table has not been created yet. I would suggest that you remove the creation of the FOREIGN KEYs to separate ALTER TABLE statements:
CREATE TABLE Staff(
StaffNo VARCHAR(5) NOT NULL,
firstName VARCHAR(15) NOT NULL UNIQUE,
lastName VARCHAR(15) NOT NULL,
position VARCHAR(10) NOT NULL,
salary INTEGER
DEFAULT 3000,
CHECK (salary BETWEEN 3000 AND 25000),
email VARCHAR(25),
branchNo CHAR(6) NOT NULL,
PRIMARY KEY (StaffNo)
);
create table Branch(
branchNo char(6) not null primary key,
street varchar(30) not null,
city varchar(20),
postCode char(5) not null,
ManagerNo varchar(5) not null
);
alter table staff
add constraint fk1_branchNo foreign key (branchNo) references Branch (branchNo);
alter table branch
add constraint fk1_ManagerNo foreign key (ManagerNo) references Staff (StaffNo);
See SQL Fiddle with Demo
You can remove one reference from one table and keep the other.then you can retrieve data using the remainig reference.Is there any problem with that?