Is it possible to create to tables that reference each other without using ALTER? [duplicate] - sql

This question already has an answer here:
Is there any other way to create constraints during SQL table creation?
(1 answer)
Closed 2 years ago.
I am new to databases in general and would like to have an answer to a problem that I am facing.
I would like to know if there is away two create two tables that reference each other without creating one and Altering it later and adding the reference.
CREATE TABLE Cats(
name VARCHAR2(15) CONSTRAINT cat_name_nn NOT NULL,
gender VARCHAR2(1) CONSTRAINT cat_gd CHECK(gender IN('W', 'M')),
nickname VARCHAR2(15) CONSTRAINT cat_pk PRIMARY KEY,
function VARCHAR2(10) CONSTRAINT cat_fn REFERENCES Functions(function),
chief VARCHAR2(15) CONSTRAINT cat_chf REFERENCES Cats(nickname),
in_herd_sinnce DATE DEFAULT SYSDATE,
mice_ration NUMBER(3),
mice_extra NUMBER(3),
band_no NUMBER(2) CONSTRAINT cat_bno REFERENCES Bands(band_no))
CREATE TABLE Bands(
band_no NUMBER(2) CONSTRAINT bd_pk PRIMARY KEY,
name VARCHAR2(20) CONSTRAINT bd_name_nn NOT NULL,
site VARCHAR2(15) CONSTRAINT bd_site_un UNIQUE,
band_chief VARCHAR2(15) CONSTRAINT bd_chf_un UNIQUE
CONSTRAINT bd_chf_nm REFERENCES Cats(nickname)
);
As far as I remember I can not do it; I am right?

No, it cannot be done. Whichever table you CREATE first cannot have a foreign key to the other table as that other table does not exist yet; instead you need to create the tables and then use ALTER TABLE ADD CONSTRAINT to create the constraint from the first table to the second.
For example:
CREATE TABLE Functions ( function VARCHAR2(10) CONSTRAINT fn_fn PRIMARY KEY );
CREATE TABLE Cats(
name VARCHAR2(15) CONSTRAINT cat_name_nn NOT NULL,
gender VARCHAR2(1) CONSTRAINT cat_gd CHECK(gender IN('W', 'M')),
nickname VARCHAR2(15) CONSTRAINT cat_pk PRIMARY KEY,
function VARCHAR2(10) CONSTRAINT cat_fn REFERENCES Functions(function),
chief VARCHAR2(15) CONSTRAINT cat_chf REFERENCES Cats(nickname),
in_herd_sinnce DATE DEFAULT SYSDATE,
mice_ration NUMBER(3),
mice_extra NUMBER(3),
band_no NUMBER(2)
);
CREATE TABLE Bands(
band_no NUMBER(2) CONSTRAINT bd_pk PRIMARY KEY,
name VARCHAR2(20) CONSTRAINT bd_name_nn NOT NULL,
site VARCHAR2(15) CONSTRAINT bd_site_un UNIQUE,
band_chief VARCHAR2(15) CONSTRAINT bd_chf_un UNIQUE
CONSTRAINT bd_chf_nm REFERENCES Cats(nickname)
);
ALTER TABLE CATS ADD CONSTRAINT cat_bno FOREIGN KEY ( band_no )
REFERENCES Bands(band_no);
db<>fiddle here

Related

Oracle SQL missing smth

Trying to build these tables and there's always an error or missing something, can someone help me?
Where's max_mice i'm checking if it's inbetween those values and doesn't work why?
Don't know what's wrong, already searched everywhere, don't know why they won't be created...
updated: now i got problems on table incidents...
update: the error was that i had: CONSTRAINT fun_maxmi_ch CHECK (200 > max_mice >= min_mice) instead of the code below.
CREATE TABLE Functions (
function VARCHAR(10) CONSTRAINT fun_fu_pk PRIMARY KEY,
min_mice NUMBER(3) CONSTRAINT fun_minmi_ch CHECK (min_mice > 5),
max_mice NUMBER(3),
CONSTRAINT fun_maxmi_ch CHECK (max_mice >= min_mice and max_mice < 200)
);
BUT still have a problem creating table Incidents don't know what's the problem!!!
CREATE TABLE Incidents (
nickname VARCHAR2(15),
enemy_name VARCHAR2(15),
incident_date DATE CONSTRAINT inc_indate_nn NOT NULL,
incident_desc VARCHAR2(50),
CONSTRAINT inc_con_pk PRIMARY KEY (nickname, enemy_name),
CONSTRAINT inc_nic_fk FOREIGN KEY (nickname) REFERENCES Cats(nickname),
CONSTRAINT inc_enname_fk FOREIGN KEY (enemy_name) REFERENCES Enemies(enemy_name),
);
Here's the full code:
CREATE TABLE Enemies (
enemy_name VARCHAR2(15),
hostility_degree NUMBER(2) CONSTRAINT hos_degree_ch CHECK (hostility_degree BETWEEN 1 AND 10),
species VARCHAR2(15),
bride VARCHAR2(20),
CONSTRAINT ene_name_pk PRIMARY KEY(enemy_name)
);
CREATE TABLE Functions (
function VARCHAR(10) CONSTRAINT fun_fu_pk PRIMARY KEY,
min_mice NUMBER(3) CONSTRAINT fun_minmi_ch CHECK (min_mice > 5),
max_mice NUMBER(3),
CONSTRAINT fun_maxmi_ch CHECK (max_mice >= min_mice and max_mice < 200)
);
CREATE TABLE Bands (
Band_no NUMBER(2) CONSTRAINT ban_no_pk PRIMARY KEY,
name VARCHAR2(20) CONSTRAINT ban_name_nn NOT NULL,
site VARCHAR2(15) CONSTRAINT ban_site_un UNIQUE,
band_chief VARCHAR(15) CONSTRAINT ban_chief_un UNIQUE
);
CREATE TABLE Cats (
name VARCHAR2(15) CONSTRAINT cat_name_nn NOT NULL,
gender VARCHAR2(1) CONSTRAINT cat_gen_ch CHECK (gender IN('M', 'W')),
nickname VARCHAR2(15) CONSTRAINT cat_pk PRIMARY KEY,
function VARCHAR2(10),
chief VARCHAR2(15),
in_herd_since DATE DEFAULT SYSDATE CONSTRAINT cat_inherd_nn NOT NULL,
mice_ration NUMBER(3),
mice_extra NUMBER(3),
band_no NUMBER(2),
CONSTRAINT cat_banno_fk FOREIGN KEY (band_no) REFERENCES Bands(band_no),
CONSTRAINT cat_chief_fk FOREIGN KEY (chief) REFERENCES Cats(nickname),
CONSTRAINT cat_fun_fk FOREIGN KEY (function) REFERENCES Functions(function)
);
ALTER TABLE Bands
ADD CONSTRAINT ban_chief_fk FOREIGN KEY (band_chief) REFERENCES Cats(nickname);
CREATE TABLE Incidents (
nickname VARCHAR2(15),
enemy_name VARCHAR2(15),
incident_date DATE CONSTRAINT inc_indate_nn NOT NULL,
incident_desc VARCHAR2(50),
CONSTRAINT inc_con_pk PRIMARY KEY (nickname, enemy_name),
CONSTRAINT inc_nic_fk FOREIGN KEY (nickname) REFERENCES Cats(nickname),
CONSTRAINT inc_enname_fk FOREIGN KEY (enemy_name) REFERENCES Enemies(enemy_name),
);
here's max_mice i'm checking if it's in between those values and doesn't work why?
When it comes to the first table in your code, Functions, the problem is with the declaration of the last check constraint:
max_mice NUMBER(3) CONSTRAINT fu_maxmi_ch CHECK (200 > max_mice >= min_mouse)
Issues:
the double inequality condition is not supported
a multi-column check constraint need to be declared at table level rather than at column level
This works:
CREATE TABLE Functions (
function VARCHAR(10) CONSTRAINT fu_fu_pk PRIMARY KEY,
min_mice NUMBER(3) CONSTRAINT fu_minmi_ch CHECK (min_mice > 5),
max_mice NUMBER(3),
CONSTRAINT fu_maxmi_ch CHECK (max_mice >= min_mice and max_mice < 200)
);
Note: I would not recommend naming a column function, since it obviously conflicts with a SQL keyword.

Trying to do an assignment but stuck at ORA-00906: missing left parenthesis

Im doing a course on DB, this is one of the first assignments, I'm about to be done, but there is an issue somewhere in my REL_CURSOS_ALUMNOS query which ends up with the ORA-00906 error.
REL_CURSOS_ALUMNOS is a relationship table for "one to many" 1 ' CURSOS(Id_Curso) to many ALUMNOS(NIF_Alumno).
This is my query till now:
CREATE TABLE PROFESORES(
NIF_Profesor VARCHAR2(15) CONSTRAINT Prof_NIF_PK PRIMARY KEY,
Nombre VARCHAR2(30),
Apellido1 VARCHAR2(30),
Apellido2 VARCHAR2(30),
Direccion VARCHAR2(4000),
Titulacion VARCHAR2(500),
Salario FLOAT(10) CONSTRAINT Prof_sal_NN NOT NULL
);
CREATE TABLE ALUMNOS(
NIF_Alumno VARCHAR2(15) CONSTRAINT Alum_NIF_PK PRIMARY KEY,
Nombre VARCHAR2(30),
Apellido1 VARCHAR2(30),
Apellido2 VARCHAR2(30),
Direccion VARCHAR2(4000),
Sexo CHAR(1),
Fecha_Nacimiento DATE
);
CREATE TABLE CURSOS (
Id_Curso VARCHAR2(15) CONSTRAINT Curs_Id_PK PRIMARY KEY,
Nombre VARCHAR2(400) UNIQUE,
NIF_Profesor VARCHAR2(15) REFERENCES PROFESORES (NIF_Profesor),
Max_Alumnos NUMBER(5),
Inicio_Fecha DATE,
Final_Fecha DATE,
Num_Horas NUMBER(10) NOT NULL,
CONSTRAINT Curs_FechasIncorrectas CHECK (Final_Fecha > Inicio_Fecha));
CREATE TABLE REL_CURSOS_ALUMNOS (
Id_Curso VARCHAR2(15) REFERENCES CURSOS(Id_Cursos),
NIF_Alumno VARCHAR2(15) REFERENCES ALUMNOS(NIF_Alumno) CONSTRAINT RCA_NIFAlum_UQ UNIQUE,
UNIQUE KEY (Id_Curso, NIF_Alumno));
Thank you.
You have a couple of small errors in the final table definition:
CREATE TABLE REL_CURSOS_ALUMNOS (
Id_Curso VARCHAR2(15) REFERENCES CURSOS(Id_Curso),
NIF_Alumno VARCHAR2(15) REFERENCES ALUMNOS(NIF_Alumno) CONSTRAINT RCA_NIFAlum_UQ UNIQUE,
UNIQUE (Id_Curso, NIF_Alumno)
);
Your specific problem is caused by KEY. That is not needed for a unique constraint definition. Further, the reference for CURSOS is id_curso, not id_cursos.
I left both unique definitions. But if NIF_Alumno is unique, then the pair (Id_Curso, NIF_Alumno) is also unique, so that constraint is redundant.

query not working for foreign key as a composite primary key of another table oracle SQL

I am trying to add two foreign keys for an associative entity in SQL Oracle. The primary key that I am referring from another table is a composite primary key. When I try to enter the SQL it says
no matching unique or primary key for this column-list
The code that I used to create the tbl_customer
CREATE TABLE tbl_Customer(
customer_id NUMBER(4)
CONSTRAINT pk_customer PRIMARY KEY,
CustomerName VARCHAR2(50) NOT NULL,
Telephone VARCHAR2(10),
CusEmail VARCHAR2(20),
CONSTRAINT cus_email UNIQUE(CusEmail),
location_id NUMBER(4)
CONSTRAINT fk_location_id references tbl_Location(location_id));
SQL to create tbl_Vehicle
CREATE TABLE tbl_Vehicle(
vehicle_id NUMBER(4),
PlateNo VARCHAR2(10),
CONSTRAINT pk_v PRIMARY KEY(vehicle_id,PlateNo),
Brand VARCHAR2(20),
Model VARCHAR2(10),
TotalNoSeats NUMBER(2),
Class VARCHAR2(4) NOT NULL,
CONSTRAINT no_seats CHECK (TotalNoSeats<100),
driver_id NUMBER(4)
CONSTRAINT fk_driveridV references tbl_Driver(driver_id),
location_id NUMBER(4)
CONSTRAINT fk_locationV references tbl_Location(location_id));
The associative table is
CREATE TABLE tbl_Customer_Vehicle(
customer_id NUMBER(4)
CONSTRAINT fk_customer_id references tbl_Customer(customer_id),
vehicle_id NUMBER(4)
CONSTRAINT fk_vehicle_id references tbl_Vehicle(vehicle_id)
);
where the error is in this line
CONSTRAINT fk_vehicle_id references tbl_Vehicle(vehicle_id)
*
Is this error because vehicle_id is a composite primary key?
Please help!!
You need to add PlateNo column in tbl_Customer_Vehicle table and define foreign key on it.
CREATE TABLE tbl_Customer_Vehicle
(
customer_id NUMBER(4)
CONSTRAINT fk_customer_id references tbl_Customer(customer_id),
vehicle_id NUMBER(4),
PlateNo VARCHAR2(10),
CONSTRAINT fk_vehicle_id_PlateNo FOREIGN KEY(vehicle_id,PlateNo)
references tbl_Vehicle(vehicle_id,PlateNo)
);

foreign key Oracle

I'm working with Oracle Database and I have this script :
create table Guardians (
noCage number(3),
nomE varchar2(20),
CONSTRAINT nc_ne1 PRIMARY KEY(noCage, nomE)
);
create table Animals(
nomA varchar2(20) PRIMARY KEY,
type varchar2(15) NOT NULL,
country varchar2(20) NOT NULL,
noCage number(3),
CONSTRAINT fk_anim_cage0 FOREIGN KEY(noCage) REFERENCES Guardians(noCage)
);
Upon executing the script, the table guardians is created, an error is prompted and the table Animals is not created. I did some manipulations and i think that it's got to do with the
CONSTRAINT nc_ne1 PRIMARY KEY(noCage, nomE)
Since Guardians Table has composite primary key you need to include both the columns in foreign key.
CONSTRAINT fk_anim_cage0 FOREIGN KEY(noCage,nomA) REFERENCES Guardians(noCage, nomE)
Your Animals table would be like this
create table Animals(
nomA varchar2(20) PRIMARY KEY,
type varchar2(15) NOT NULL,
country varchar2(20) NOT NULL,
noCage number(3),
CONSTRAINT fk_anim_cage0 FOREIGN KEY(noCage,nomA)
REFERENCES Guardians(noCage, nomE)
);

SQL: ORA-00904: invalid identifier

I am new to SQL and I get this error in Navicat for Oracle.
ORA-00904: : invalid identifier
DROP TABLE Series CASCADE CONSTRAINTS;
DROP TABLE User1 CASCADE CONSTRAINTS;
DROP TABLE Following CASCADE CONSTRAINTS;
DROP TABLE Episode CASCADE CONSTRAINTS;
--DROP TABLE BUNGALOW CASCADE CONSTRAINTS;
--DROP TABLE Watched CASCADE CONSTRAINTS;
CREATE TABLE Series
( SeriesID NUMBER(5) primary key,
Name VARCHAR2(100) NOT NULL,
Status VARCHAR2(15),
Genre VARCHAR2(100),
Country VARCHAR2(100),
Network VARCHAR2(100),
Runtime VARCHAR2(25)
);
CREATE TABLE User1(
UserID NUMBER(5) primary key,
Username VARCHAR2(100) NOT NULL,
Country1 varchar2(100),
Gender VARCHAR2(10) NOT NULL,
Birthday VARCHAR2(100),
Timezone VARCHAR2(100),
About_me VARCHAR2(300),
Password VARCHAR2(100) NOT NULL
);
CREATE TABLE Following (
UserID NUMBER(5) NOT NULL,
SeriesID NUMBER(5) NOT NULL,
Ignore1 CHAR(1) NOT NULL,
constraint Following_pk primary key(UserID, SeriesID),
constraint Following_fk1 foreign key(UserID) REFERENCES User1(UserID),
constraint Following_fk2 foreign key(SeriesID) REFERENCES Series(SeriesID)
);
CREATE TABLE Episode(
SeriesID NUMBER(5) NOT NULL,
Season NUMBER(2) NOT NULL,
Episode NUMBER(2) NOT NULL,
Name varchar2(100) NOT NULL,
Airdate DATE,
Summary varchar2(500),
constraint episode_pk primary key(SeriesID, Season, Episode),
constraint episode_fk foreign key(SeriesID) REFERENCES Series(SeriesID)
);
CREATE TABLE Watched(
UserID NUMBER(5) NOT NULL,
SeriesID NUMBER(5) NOT NULL,
Season NUMBER(2) NOT NULL,
Episode NUMBER(2) NOT NULL,
constraint watched_pk primary key(UserID, SeriesID, Season, Episode),
constraint watched_fk1 foreign key(UserID) REFERENCES User1(UserID),
constraint watched_fk2 foreign key(SeriesID) REFERENCES Episode(SeriesID),
constraint watched_fk3 foreign key(Season) REFERENCES Episode(Season),
constraint watched_fk4 foreign key(Episode) REFERENCES Episode(Episode),
);
The error comes up when creating the Watched table. I guess it has something to do with the multiple foreign keys from the Episode-table but i can't seem to figure it out.
You have a one comma to many, at the last constraint definition, try this:
CREATE TABLE Watched(
UserID NUMBER(5) NOT NULL,
SeriesID NUMBER(5) NOT NULL,
Season NUMBER(2) NOT NULL,
Episode NUMBER(2) NOT NULL,
constraint watched_pk primary key(UserID, SeriesID, Season, Episode),
constraint watched_fk1 foreign key(UserID) REFERENCES User1(UserID),
constraint watched_fk4 foreign key(Episode, season, seriesid) REFERENCES Episode(SeriesID, Season, Episode)
);
Also, you had too many foreign keys - instead of 3 foreign keys to reference the EPISODE table, you should have only one with 3 columns.