sql error - no unique constraint matching keys - postgresql

for some reason i am getting there is no unique constraint matching given keys for referenced table "accident_location". I am using postgresql to create the table. what is the error here? as i have set the primary key of ID and address_ID on my accident_location table
CREATE TABLE IF NOT EXISTS Accident(
ID varchar(10) NOT NULL,
Severity INT,
Start_Time varchar(100) NOT NULL,
End_Time varchar(100) NOT NULL,
Description varchar(100),
PRIMARY KEY(ID)
);
CREATE TABLE IF NOT EXISTS Accident_Location(
ID varchar(10),
Address_ID INT,
Start_lat float,
Start_Lng float,
End_Lat float,
End_Lng float,
"Distance(mi)" float,
PRIMARY KEY (ID,Address_ID),
FOREIGN KEY (ID) REFERENCES Accident(ID)
);
CREATE TABLE IF NOT EXISTS Address(
Address_ID INT,
Number INT,
Street varchar(100),
Side varchar(5) ,
City varchar(50) NOT NULL,
County varchar(50) ,
State varchar(10) NOT NULL,
Zipcode varchar(15) NOT NULL,
Country varchar(5) ,
Timezone varchar(30) ,
Airport_code varchar(10),
Location_ID INT NOT NULL,
Weather_ID INT NOT NULL,
PRIMARY KEY (Address_ID),
FOREIGN KEY (Address_ID) REFERENCES Accident_Location(Address_ID)
);

The referenced Address_ID on the Address table should be unique on table Accident_Location.
Change Accident_Location table to
CREATE TABLE IF NOT EXISTS Accident_Location(
ID varchar(10),
Address_ID INT constraint unx_addres_id_location unique,
Start_lat float,
Start_Lng float,
End_Lat float,
End_Lng float,
"Distance(mi)" float,
PRIMARY KEY (ID,Address_ID),
FOREIGN KEY (ID) REFERENCES Accident(ID)
);
Here, I've added a unique constraint on Address_ID
Address_ID INT constraint unx_addres_id_location unique
UPDATED
Since you are referring to Address_ID of Accident_Location table as a foreign key on the Address table, this will force you to make it a unique record. That means any two rows or more should not have the same value of Address_ID. Otherwise, the foreign key Address_ID on the Address table wouldn't know which row you are referring to.
The reason you are not seeing this same error for the Accident table is that by default primary keys are unique.

Related

What is wrong with this Query ? PostgreSQL

I want to create 3 tables and join them with foreign keys. Unfortunately, it doesn't work and I have no idea where is a mistake.
CREATE TABLE Students (
Student_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Date_of_Birth DATE NOT NULL,
Phone INT NOT NULL UNIQUE,
Email VARCHAR(225) NOT NULL UNIQUE,
Course_Id INT
FOREIGN KEY (Course_Id) REFERENCES Course (Course_Id)
);
CREATE TABLE Course (
Course_Id SERIAL PRIMARY KEY,
Student_Id INT NOT NULL,
Teacher_Id INT NOT NULL,
Category VARCHAR (30) NOT NULL,
FOREIGN KEY (Student_Id) REFERENCES Students (Student_Id)
);
CREATE TABLE Teachers (
Teacher_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Phone INT NOT NULL UNIQUE,
Salary INT NOT NULL,
Course_Id INT NOT NULL,
FOREIGN KEY (Teacher_Id) REFERENCES Course (Teacher_Id)
);
I should create a Foreign Key to join all three tables.
I get this error every time: relation "course" does not exist
I can't find where is the mistake. Please help.
It appears like you are attempting to crate a many-to-many (M:M) between Students and Teachers with Course as the resolution table. You are close, however, your definition sets up bi-directional relationships. This is normally not necessary. Define Students and Teachers without the FK to Course. Then define Course with a FK to each.
create table students (
student_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, date_of_birth date not null
, phone int not null unique
, email varchar(225) not null unique
);
create table teachers (
teacher_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, phone int not null unique
, salary int not null
);
create table course (
course_id serial primary key
, student_id int not null
, teacher_id int not null
, category varchar (30) not null
, foreign key (student_id) references students (student_id)
, foreign key (teacher_id) references teachers (teacher_id)
, unique (student_id, teacher_id)
);
If you must define bi-directional FK in Students and Teachers then create the tables without the FK then use alter table after Course is defined to add the FK and make them DEFERRABLE INITIALLY DEFERRED. Necessary for eventual Inserts.
alter table teachers add column course_id int references course(course_id) deferrable initially deferred;
alter table students add column course_id int references course(course_id) deferrable initially deferred;

When I run this code a syntax error keeps appearing but I am unable to find where it would be

When I run this code, I receive a very vague syntax error: database: syntax error at or near "(". I am unable to find where this syntax error would be.
I have also been told that animal_adoption_history is not an associative entity when it was designed as one.
What have I done wrong when writing it?
The code:
DROP TABLE IF EXISTS customer;
DROP TABLE IF EXISTS animal;
DROP TABLE IF EXISTS animal_adoption_history;
create table customer (
customer_id CHAR(9) NOT NULL,
c_first_name VARCHAR(25),
c_last_name VARCHAR(50),
c_gender CHAR(1),
c_phone_number VARCHAR(20),
c_email_address VARCHAR(45),
c_date_of_birth DATE,
c_address_number VARCHAR(10),
c_street_name VARCHAR(30),
c_city VARCHAR(50),
c_state CHAR(3),
c_postcode CHAR(4),
c_has_adopted_before CHAR(1),
constraint customer_PK PRIMARY KEY (customer_id)
);
create table animal (
animal_id CHAR(9) NOT NULL,
a_animal_type VARCHAR(20) ,
a_breed VARCHAR(50),
a_colour VARCHAR(30),
a_size VARCHAR(20),
a_weight_kg VARCHAR(10),
a_description VARCHAR(75),
a_name VARCHAR(30),
a_date_of_birth DATE,
a_sex CHAR(1),
a_animal_cost INT(10),
a_microchip_status CHAR(1),
a_vaccination_status CHAR(1),
constraint animal_PK PRIMARY KEY (animal_id)
);
create table animal_adoption_history (
health_conditions VARCHAR(100),
is_available_to_adopt CHAR(1),
has_been_adopted_previously CHAR(1),
reason_for_entry VARCHAR(75),
date_entered DATE,
animal_id CHAR(9) NOT NULL,
customer_id CHAR(9) NOT NULL,
constraint animal_adoption_history_PK PRIMARY KEY (animal_id, customer_id),
constraint animal_adoption_history_FK1 FOREIGN KEY (animal) references animal(animal_id)
constraint animal_adoption_history_FK2 FOREIGN KEY (customer_id) references customer(customer_id)
);
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,c_street_name,c_city,c_state,c_postcode,c_has_adopted_before)
VALUES ('C00000001','Olivia','Smith','F','0422425392','olivia.smith#gmail.com','1980-06-22','2','Henderson Street','Bondi','NSW','2092','Yes');
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,c_street_name,c_city,c_state,c_postcode,c_has_adopted_before)
VALUES ('C00000002','Taylor','Brown','F','0422435394','taylor.brown#gmail.com','1999-02-24','62','Ultimo Avenue','Bondi','NSW','2092','No');
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,c_street_name,c_city,c_state,c_postcode,c_has_adopted_before)
VALUES ('C00000003','Sarah','Li','F','0422425342','sarah.li#gmail.com','1997-02-22','27','Winchester Street','Epping','NSW','2092','Yes');
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,c_street_name,c_city,c_state,c_postcode,c_has_adopted_before)
VALUES ('C00000004','Charlie','Swift','M','0432425392','charlie.swift#gmail.com','1998-02-22','22','Henderson Lane','Lindfield','NSW','2092','No');
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,c_street_name,c_city,c_state,c_postcode,c_has_adopted_before)
VALUES ('C00000005','Heath','Davidson','M','0422425911','heath.davidson#gmail.com','2003-01-22','22','Station Street','Manly','NSW','2092','Yes');
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,a_sex,a_animal_cost,a_microchip_status,a_vaccination_status)
VALUES ('A00000001','Dog','Pug','Light brown','Small','5','Playful yet enjoys cuddles','Mia','2020-02-22','F','3100','Y','Y');
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,a_sex,a_animal_cost,a_microchip_status,a_vaccination_status)
VALUES ('A00000002','Cat','Tabby','Orange','Small','4','Quiet and loves the sun','Garfield','2010-04-28','M','1400','Y','N');
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,a_sex,a_animal_cost,a_microchip_status,a_vaccination_status)
VALUES ('A00000003','Bird','Budgie','Green and yellow','Extra Small','0.035','Very loud when hungry','Roody','11-14','F','1200','N','Y');
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,a_sex,a_animal_cost,a_microchip_status,a_vaccination_status)
VALUES ('A00000004','Rabbit','Holland Lop','Light brown and white','Small','5','Fluffy and enjoys lettuce snacks','Thumper','2018-19-04','F','900','N','N');
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,a_sex,a_animal_cost,a_microchip_status,a_vaccination_status)
VALUES ('A00000005','Dog','Golden Retriever','Dark blonde','Large','32','Loves going for long walks','Milo','2014-05-30','M','2500','Y','Y');
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,date_entered,animal_id,customer_id)
VALUES ('None','Y','Y','Owner moved away','2021-08-18','A00000001','C00000001');
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,date_entered,animal_id,customer_id)
VALUES ('None','N','N','Newborn looking for home','2022-07-13','A00000003','C00000005');
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,date_entered,animal_id,customer_id)
VALUES ('Diabetes','Y','Y','Owner passed away','2019-11-01','A00000004','C00000001');
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,date_entered,animal_id,customer_id)
VALUES ('None','Y','N','Previous household abuse','2014-09-19','A00000002','C00000004');
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,date_entered,animal_id,customer_id)
VALUES ('Arthritis','Y','Y','Newborn looking for home','2016-04-26','A00000005','C00000002');
Thanks!
INT(10) is not valid datatype:
a_animal_cost INT(10)
There are other issues as well, you have to fix this.
You have a number of errors in your code. When running PostgreSQL only lists the first one, which in this case is the line a_animal_cost INT(10),. Integers are a fixed size so it is wrong to attempt to specify a size for it.
Also do not use char(1) for Yes ('Y') No ('N') fields. PostgreSQL has a native boolean data type for this purpose, so use it.
When deleting tables, you need to delete the lowest tables in the hierarchy first (foreign key etc).
Finally, you can chain multiple inserts as values together.
Putting all this together, I would recommend that you use something like this:
DROP TABLE IF EXISTS animal_adoption_history;
DROP TABLE IF EXISTS animal;
DROP TABLE IF EXISTS customer;
create table customer (
customer_id CHAR(9) NOT NULL,
c_first_name VARCHAR(25),
c_last_name VARCHAR(50),
c_gender CHAR(1),
c_phone_number VARCHAR(20),
c_email_address VARCHAR(45),
c_date_of_birth DATE,
c_address_number VARCHAR(10),
c_street_name VARCHAR(30),
c_city VARCHAR(50),
c_state CHAR(3),
c_postcode CHAR(4),
c_has_adopted_before boolean,
constraint customer_PK PRIMARY KEY (customer_id)
);
create table animal (
animal_id CHAR(9) NOT NULL,
a_animal_type VARCHAR(20) ,
a_breed VARCHAR(50),
a_colour VARCHAR(30),
a_size VARCHAR(20),
a_weight_kg VARCHAR(10),
a_description VARCHAR(75),
a_name VARCHAR(30),
a_date_of_birth DATE,
a_sex CHAR(1),
a_animal_cost INT,
a_microchip_status boolean,
a_vaccination_status boolean,
constraint animal_PK PRIMARY KEY (animal_id)
);
create table animal_adoption_history (
health_conditions VARCHAR(100),
is_available_to_adopt boolean,
has_been_adopted_previously boolean,
reason_for_entry VARCHAR(75),
date_entered DATE,
animal_id CHAR(9) NOT NULL,
customer_id CHAR(9) NOT NULL,
constraint animal_adoption_history_PK PRIMARY KEY (animal_id, customer_id),
constraint animal_adoption_history_FK1 FOREIGN KEY (animal_id) references animal(animal_id),
constraint animal_adoption_history_FK2 FOREIGN KEY (customer_id) references customer(customer_id)
);
INSERT INTO customer (customer_id,c_first_name,c_last_name,c_gender,c_phone_number,c_email_address,c_date_of_birth,c_address_number,
c_street_name,c_city,c_state,c_postcode,c_has_adopted_before) VALUES
('C00000001','Olivia','Smith','F','0422425392','olivia.smith#gmail.com','1980-06-22','2',
'Henderson Street','Bondi','NSW','2092',true),
('C00000002','Taylor','Brown','F','0422435394','taylor.brown#gmail.com','1999-02-24','62',
'Ultimo Avenue','Bondi','NSW','2092',false),
('C00000003','Sarah','Li','F','0422425342','sarah.li#gmail.com','1997-02-22','27',
'Winchester Street','Epping','NSW','2092',true),
('C00000004','Charlie','Swift','M','0432425392','charlie.swift#gmail.com','1998-02-22','22',
'Henderson Lane','Lindfield','NSW','2092',false),
('C00000005','Heath','Davidson','M','0422425911','heath.davidson#gmail.com','2003-01-22','22',
'Station Street','Manly','NSW','2092',true);
INSERT INTO animal (animal_id,a_animal_type,a_breed,a_colour,a_size,a_weight_kg,a_description,a_name,a_date_of_birth,
a_sex,a_animal_cost,a_microchip_status,a_vaccination_status) VALUES
('A00000001','Dog','Pug','Light brown','Small','5','Playful yet enjoys cuddles','Mia','2020-02-22',
'F','3100',true,true),
('A00000002','Cat','Tabby','Orange','Small','4','Quiet and loves the sun','Garfield','2010-04-28',
'M','1400',true,false),
('A00000003','Bird','Budgie','Green and yellow','Extra Small','0.035','Very loud when hungry','Roody','2020-11-14',
'F','1200',false,true),
('A00000004','Rabbit','Holland Lop','Light brown and white','Small','5','Fluffy and enjoys lettuce snacks','Thumper','2018-04-19',
'F','900',false,false),
('A00000005','Dog','Golden Retriever','Dark blonde','Large','32','Loves going for long walks','Milo','2014-05-30',
'M','2500',true,true);
INSERT INTO animal_adoption_history (health_conditions,is_available_to_adopt,has_been_adopted_previously,reason_for_entry,
date_entered,animal_id,customer_id) VALUES
('None',true,true,'Owner moved away','2021-08-18','A00000001','C00000001'),
('None',false,false,'Newborn looking for home','2022-07-13','A00000003','C00000005'),
('Diabetes',true,true,'Owner passed away','2019-11-01','A00000004','C00000001'),
('None',true,false,'Previous household abuse','2014-09-19','A00000002','C00000004'),
('Arthritis',true,true,'Newborn looking for home','2016-04-26','A00000005','C00000002');

Postgresql. Create function get_ticket

Create a function to Get Ticket (for a Reservation).Ticket a booked reservation when the passenger pays the total amount.
Create a trigger, called line disruption, that adjusts all the tickets to the immediate next line when a line is closed due to an accident or maintenance, unless the customer specified no substitutions/adjustments in which case the ticket is canceled.
I created the tables, but I have some mistakes on my function: Please show me the mistakes and explain your solutions.
CREATE OR REPLACE FUNCTION get_ticket (reservation_id int, id int, price int)
RETURNS SETOF ticket
AS $$
BEGIN
INSERT INTO Ticket (ticket_id, reservation_id, price);
END;
$$ LANGUAGE plpgsql;
CREATE TABLE Customer (
id int PRIMARY KEY,
fname varchar,
lname varchar,
street varchar,
town varchar,
postal_code varchar
);
CREATE TABLE Station (
id int PRIMARY KEY,
name varchar,
open_time varchar,
close_time varchar,
stop_delay int,
street varchar,
town varchar,
postal_code varchar
);
CREATE TABLE Train (
id int PRIMARY KEY,
name varchar,
description varchar,
seat_avail int,
top_speed int,
cost_per_km int
);
CREATE TABLE Rail_Line (
line_id int PRIMARY KEY,
speed_limit int
);
CREATE TABLE Passes_Thru_SRL (
line_id int PRIMARY KEY,
station_id int PRIMARY KEY,
distance int,
CONSTRAINT FK1_SRL FOREIGN KEY (line_id) REFERENCES Rail_Line (line_id) ON DELETE CASCADE,
CONSTRAINT FK2_SRL FOREIGN KEY (station_id) REFERENCES Station (id) ON DELETE CASCADE
);
CREATE TABLE Route (
route_id int PRIMARY KEY
);
CREATE TABLE Passes_Thru_SR (
route_id int PRIMARY KEY,
station_id int PRIMARY KEY,
stops bool,
CONSTRAINT FK1_SR FOREIGN KEY (route_id) REFERENCES Route (route_id) ON DELETE CASCADE,
CONSTRAINT FK2_SR FOREIGN KEY (station_id) REFERENCES Station (id) ON DELETE CASCADE
);
CREATE TABLE Route_Schedule (
route_id int PRIMARY KEY,
day varchar,
time varchar,
train_id int PRIMARY KEY,
CONSTRAINT FK1_RS FOREIGN KEY (route_id) REFERENCES Route (route_id) ON DELETE CASCADE,
CONSTRAINT FK2_RS FOREIGN KEY (train_id) REFERENCES Train (id) ON DELETE CASCADE
);
CREATE TABLE Reservation (
reservation_id int PRIMARY KEY,
price int PRIMARY KEY,
id int,
CONSTRAINT FK_RS FOREIGN KEY (id) REFERENCES Customer (id) ON DELETE CASCADE
);
CREATE TABLE Ticket (
ticket_id int PRIMARY KEY,
reservation_id int,
id int, price int,
CONSTRAINT FK_RS1 FOREIGN KEY (reservation_id) REFERENCES Reservation (reservation_id) ON DELETE CASCADE,
CONSTRAINT FK_RS2 FOREIGN KEY (id) REFERENCES Customer (id) ON DELETE CASCADE,
CONSTRAINT FK_RS3 FOREIGN KEY (price) REFERENCES Reservation (price) ON DELETE CASCADE
);

'there is no unique constraint matching given keys for referenced table' where i dont want something to be unique

In Postgres I have written the following code:
CREATE TABLE students (
student_id BIGINT PRIMARY KEY,
first_name VARCHAR(15),
surname VARCHAR(35),
enrollment_year INT);
CREATE TABLE teachers (
bsn BIGINT PRIMARY KEY,
first_name VARCHAR(15),
surname VARCHAR(35),
salary REAL,
scale INT,
CONSTRAINT salary CHECK(salary < (25 * scale) AND salary > (20 * scale))
);
CREATE TABLE course (
course_code VARCHAR(10) PRIMARY KEY,
course_name VARCHAR(20) UNIQUE,
study_points INT);
CREATE TABLE study_program (
course_name VARCHAR(20) PRIMARY KEY,
level VARCHAR(15),
duration VARCHAR(10),
FOREIGN KEY(course_name) REFERENCES course(course_name));
CREATE TABLE assignment (
assignment_code VARCHAR(10) UNIQUE,
course_name VARCHAR(20),
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE records (
student_id BIGINT,
course_name VARCHAR(20),
PRIMARY KEY(student_id, course_name),
FOREIGN KEY(student_id) REFERENCES students(student_id),
FOREIGN KEY(course_name) REFERENCES course(course_name));
CREATE TABLE make (
student_id BIGINT,
assignment_code VARCHAR(20),
PRIMARY KEY(student_id, assignment_code),
FOREIGN KEY(student_id) REFERENCES students(student_id),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code));
CREATE TABLE prerequisit (
assignment_code VARCHAR(20),
course_name VARCHAR(20),
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE records_2 (
assignment_code VARCHAR(20),
course_name VARCHAR(20),
bsn BIGINT,
mandatory BOOLEAN,
year INT,
week INT,
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE designes (
course_code VARCHAR(15),
bsn BIGINT,
study_points INT,
course_name VARCHAR(20),
PRIMARY KEY(course_code, bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(study_points) REFERENCES course(study_points),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE reviews (
bsn BIGINT PRIMARY KEY,
course_code VARCHAR(15),
study_points INT,
course_name VARCHAR(20),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code),
FOREIGN KEY(study_points) REFERENCES course(study_points),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
The error I get is
ERROR: there is no unique constraint matching given keys for referenced table "course"
This error is fixed by adding the UNIQUE constraint to study points, however I do not want study points to be unique because I need different courses to have the same amount of study points.
Referencing study_points makes no sense whatsoever. In fact referencing three different columns of a single table makes no sense whatsoever.
You only need FOREIGN KEY(course_code) REFERENCES course(course_code) and you don't need the columns course_name and study_points in the reviews table as they are implicitly defined through the foreign key to the course table.
Which means the table should look something like this:
CREATE TABLE reviews
(
bsn BIGINT PRIMARY KEY,
course_code VARCHAR(15),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code)
);
Which then begs the question: what is that table supposed to do? You can only have a single row per teacher in there because bsn is the primary key (thus can't be repeated). So that is a one-to-one (or one-to-zero/one) relationship. Which in turn means you could move the column course_code to the teachers table, e.g. as reviewed_course.
However, I guess you meant to create a many-to-many relationship between teachers and course which then should be something like this:
CREATE TABLE reviews
(
bsn BIGINT,
course_code VARCHAR(15),
primary key (bsn, course_code),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code)
);
That makes the combination of bsn and course_code unique. Which means each teacher can review each course exactly once, but a teacher can review multiple courses and a single course can be reviewed by multiple teachers.

Postgresql Creating a Schema with tables in it

Here's my script.
CREATE SCHEMA testSchema
create table REF_PRODUCT (
id int8 not null,
created_date timestamp,
CODE varchar(255),
DESCRIPTION varchar(255),
LOCATION varchar(255),
MANUFACTURER varchar(255),
NAME varchar(255),
COST numeric(19, 2),
DEALERS_PRICE numeric(19, 2),
SUGGESTED_RETAIL_PRICE numeric(19, 2),
STOCK int4,
PRODUCT_TYPE varchar(255),
picture_id int8,
primary key (id)
)
create table TXN_LINE_ITEM (
id int8 not null,
created_date timestamp,
cancelled boolean,
cost numeric(19, 2),
dp numeric(19, 2),
itemCode varchar(255),
itemName varchar(255),
priceType varchar(255),
qty int4,
refunded boolean,
srp numeric(19, 2),
total numeric(19, 2),
transactionRecord_id int8,
primary key (id)
)
create table TXN_PRODUCT_PICTURE (
id int8 not null,
created_date timestamp,
picture bytea,
primary key (id)
)
create table TXN_TRANSACTION_RECORD (
id int8 not null,
created_date timestamp,
total numeric(19, 2),
transaction_date timestamp,
TRANSACTION_NUMBER varchar(255),
VALID boolean,
primary key (id)
)
alter table REF_PRODUCT
add constraint FK_sjugahpelk16qj5h3w8dli42l
foreign key (picture_id)
references TXN_PRODUCT_PICTURE;
alter table TXN_LINE_ITEM
add constraint FK_o5mslaahpil9d3g9rl2s22rpm
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD;
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
);
The problem is the fk relationships specified in alter table statement is not being created
Because of this error.
[WARNING ] CREATE SCHEMA testSchema
create table REF_PRODUCT (
id int8 not null,
created_date timestamp,
CODE varchar(255),
DESCRIPTION varchar(255),
LOCATION varchar(255),
MANUFACTURER varchar(255),
NAME varchar(255),
COST numeric(19, 2),
DEALERS_PRICE numeric(19, 2),
SUGGESTED_RETAIL_PRICE numeric(19, 2),
STOCK int4,
PRODUCT_TYPE varchar(255),
picture_id int8,
primary key (id)
)
create table TXN_LINE_ITEM (
id int8 not null,
created_date timestamp,
cancelled boolean,
cost numeric(19, 2),
dp numeric(19, 2),
itemCode varchar(255),
itemName varchar(255),
priceType varchar(255),
qty int4,
refunded boolean,
srp numeric(19, 2),
total numeric(19, 2),
transactionRecord_id int8,
primary key (id)
)
create table TXN_PRODUCT_PICTURE (
id int8 not null,
created_date timestamp,
picture bytea,
primary key (id)
)
create table TXN_TRANSACTION_RECORD (
id int8 not null,
created_date timestamp,
total numeric(19, 2),
transaction_date timestamp,
TRANSACTION_NUMBER varchar(255),
VALID boolean,
primary key (id)
)
alter table REF_PRODUCT
add constraint FK_sjugahpelk16qj5h3w8dli42l
foreign key (picture_id)
references TXN_PRODUCT_PICTURE
ERROR: syntax error at or near "alter"
LINE 53: alter table REF_PRODUCT
^
[WARNING ] alter table TXN_LINE_ITEM
add constraint FK_o5mslaahpil9d3g9rl2s22rpm
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD
ERROR: relation "txn_line_item" does not exist
[WARNING ] create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
)
ERROR: relation "seq_entity_id" already exists
NOTE THAT: There's no existing tables on the said Schema I have made. What have I missed?
I think you have two ways of doing this.
The first one: don't run one create schema statement, but run individual statements for each part (this is what I prefer). You can still do that as a single transaction:
begin transaction;
CREATE SCHEMA testSchema; -- only create the namespace
-- make the new schema the default schema
-- so the the tables do not need to be full qualified
set search_path = testschema;
create table REF_PRODUCT (
...
);
create table TXN_LINE_ITEM (
...
);
create table TXN_PRODUCT_PICTURE (
...
);
create table TXN_TRANSACTION_RECORD (
...
);
alter table REF_PRODUCT
add constraint fk_product_picture
foreign key (picture_id)
references TXN_PRODUCT_PICTURE;
alter table TXN_LINE_ITEM
add constraint FK_line_item_trans_record
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD;
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
);
commit;
The other option is to move the foreign keys into the table definition, but then you need to re-order your create table statements:
CREATE SCHEMA testSchema
create table TXN_PRODUCT_PICTURE (
...
)
create table TXN_TRANSACTION_RECORD (
...
)
create table REF_PRODUCT (
...,
constraint fk_product_picture
foreign key (picture_id)
references TXN_PRODUCT_PICTURE
)
create table TXN_LINE_ITEM (
...
constraint FK_line_item_trans_record
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD
)
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
)
;
Unrelated, but:
What is this SEQ_ENTITY_ID table for? Why don't you use native Postgres sequences. They will be much faster, more scalable and more robust than anything you can do in your application to generate unique numbers