Postgresql Trying to implement One-To-Many - database

this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner

typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1

Related

INSERT statement conflicted with the FOREIGN KEY constraint? I tried to insert data in the table ''customer'' but I always got this error

So I tried to insert data in the ''customer'' table but I always get this certain error (at the bottom).
Can anyone pinpoint if I miss anything or if it's lacking?
create table rooms
(
roomid int identity(1,1) primary key,
roomNo varchar(250) not null unique,
roomType varchar(250) not null,
bed varchar(250) not null,
price bigint not null,
booked varchar(50) default 'NO'
);
insert into rooms (roomNo, roomType, bed, price) values (010, 'Studio with AC', 'Single', '1000');
create table customer
(
cid int identity(1,1) primary key,
cname varchar(250) not null,
mobile bigint not null,
nationality varchar(250) not null,
gender varchar(50) not null,
dob varchar(50) not null,
idproof varchar(50) not null,
addres varchar(250) not null,
checkIn varchar(250) not null,
checkOut varchar(250),
chekOut varchar(250) not null default 'NO',
roomid int foreign key references rooms(roomid)
);
insert into customer (cname,mobile,nationality,gender,dob,idproof,addres,checkIn,customer.roomid) values ('Kayano Ai', 09238400394, 'Japanese', 'Female', '01-02-1998', '8923giaf', 'Somewhere', 'YES', 20);
the error notif I got is
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__customer__roomid__1F98B2C1". The conflict occurred in database "myHotel", table "dbo.rooms", column 'roomid'.
When you enter row into your customer table, customer.roomid should exist in the rooms table first.
Fist make sure the room exists or insert a new room.
INSERT INTO rooms ( roomid,roomNo, ...) VALUES (1,'room1',...);
Then insert into customer with an custormer.roomid that exists in the room table (1 in the example)
INSERT INTO customer ( cid,cname,roomid ...) VALUES (15,'customer name',1,...);

How to create tables using below statement

Working on small ASP.Net MVC project, and got requirement from business analyst who gave me PDF file with below SQL staff to create in database.
Looking on how to achieve result from the below SQL question.
By the way should all be created using T-SQL
Student - Table
studentNo Identity column INT NOT NULL PK
lastName VARCHAR(30) NOT NULL
firstName VARCHAR(30) NOT NULL
gender CHAR NOT NULL
phoneNumber VARCHAR(20) NOT NULL
salaryAmount INT,
departmentID INT FK
Department - Table
departmentID Identity Column INT NOT NULL PK
name VARCHAR(40) NOT NULL
priceCentreID INT FK
PriceCentre - Table
priceCentreID
name VARCHAR(50)
accountID varchar(50)
As I understand you want help to create the sql code to generate the tables you provided?
Below is the code to create the tables and the relations that you are looking for.
code:
CREATE TABLE PriceCentre(
priceCenterID INT PRIMARY KEY,
name VARCHAR(50),
accountID VARCHAR(50)
);
GO
CREATE TABLE Department(
departmentID INT NOT NULL PRIMARY KEY,
name VARCHAR(40) NOT NULL,
priceCenterID int FOREIGN KEY REFERENCES PriceCentre (priceCenterID)
)
GO
CREATE TABLE Student(
studentNo INT NOT NULL PRIMARY KEY,
lastName VARCHAR(30) NOT NULL,
firstName VARCHAR(30) NOT NULL,
gender CHAR NOT NULL,
phoneNumber VARCHAR(20) NOT NULL,
salaryAmount INT,
departmentID INT FOREIGN KEY REFERENCES Department(departmentID)
);

What's the proper way to create these tables?

I'm reverse engineering a script that creates a payroll database from my textbook. I'm rebuilding it into a library management system instead. To start I've drawn out a diagram of the tables/columns and their relationships here. Now following the script from the textbook I use the authors technique to create all the tables except for the BooksIssued table and InvoiceItems table. This is my code
USE master
GO
/******Check to see if database exists******/
IF DB_ID('SET2133810') IS NOT NULL
DROP DATABASE SET2133810
GO
/******Object: Database SET2133810******/
CREATE DATABASE SET2133810
GO
USE SET2133810
GO
/******Object: table*****/
CREATE TABLE VendorsList(
VendorID int IDENTITY(1,1) NOT NULL,
VendorName varchar(50) NOT NULL,
VendorPhone varchar(50) NULL,
VendorContactLName varchar(50) NULL,
VendorContactFName varchar(50) NULL,
VendorAddress varchar(50) NULL,
VendorCity varchar(50) NOT NULL,
VendorState char(2) NOT NULL,
VendorZipCode varchar(20) NOT NULL,
CONSTRAINT PK_VendorsList PRIMARY KEY CLUSTERED (
VendorID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE InvoicesList(
InvoiceID int IDENTITY(1,1) NOT NULL,
VendorID int NOT NULL,
InvoiceNumber varchar(50) NOT NULL,
InvoiceDate smalldatetime NOT NULL,
InvoiceTotal money NOT NULL,
PaymentTotal money NOT NULL,
PaymentDate smalldatetime NULL,
CONSTRAINT PK_InvoicesList PRIMARY KEY CLUSTERED(
InvoiceID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE BookList(
BookID int IDENTITY(1,1) NOT NULL,
BookISBN varchar(50) NOT NULL,
BookTitle varchar(50) NOT NULL,
BookAuthor varchar(50) NOT NULL,
BookPublisher varchar(50) NOT NULL,
BookGenre varchar(50) NULL
CONSTRAINT PK_BookList PRIMARY KEY CLUSTERED(
BookID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE MembersList(
MemberID int IDENTITY(1,1) NOT NULL,
MemberLName varchar(50) NOT NULL,
MemberFName varchar(50) NOT NULL,
MemberAddress varchar(50) NULL,
MemberCity varchar(50) NOT NULL,
MemberState char(2) NOT NULL,
MemberZipCode varchar(20) NOT NULL,
MemberPhone varchar(50) NOT NULL,
MemberEmail varchar(50) NOT NULL,
CONSTRAINT PK_MembersList PRIMARY KEY CLUSTERED(
MemberID ASC
)
)
GO
I'm confused on how I would create these tables in the same way? Since they both depend on the other tables and the information thats already in them. I've looked around and found Join statements, but none of them were used in a way that would help me with this problem.
Following should be the order to create tables.
BookList
MemeberList
Book Issued
VendorList
InvoiceList
InvoiceItems
Invoice list shoul be created in last as it have references to vendor and invoice items and BookIssues should be created after MemberList and Book List

Foreign key reference mismatched data type error

The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO

What does the constraint mean?

I am new to SQL and I am trying to create a table with a constraint but I have not used the constrant before and I am not actually certain what this constraint does uc_ID on PId, LastName?
I want to create a constraint that will only allow alpha numeric values in a column?
Code:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT uc_ID UNIQUE (PId,LastName)
)
CREATE TABLE E
(
PId int identity(1,1) NOT NULL,
LastName varchar (25) NOT NULL,
FirstName varchar (25) NOT NULL,
Address1 varchar (25) NOT NULL,
City varchar (25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9]%')
)
Another Example (is not):
CREATE TABLE EEE
(
PId int identity(1,1) NOT NULL,
FirstName varchar (50) NOT NULL,
CONSTRAINT CHECK ([FirstName] LIKE '%[A-Za-z]%')
)
Means that the combination of Pid + LastName must be unique.
Since Pid is an identity, in normal circumstances it cannot be duplicated, so that constraint seems somehow redudant.
Try:
ALTER TABLE TableName ADD CONSTRAINT Only_Characters_And_Numbers CHECK ColumnName NOT LIKE '%[^A-Z0-9 ]%'
If you want a constraint that allows only alphanumeric characters in a column you can use this (for example for FirstName:
ALTER TABLE [Persons] ADD CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
Disclaimer: taken from here (and tested).
If you want the constraint to be added when the table is created:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
)
Note that constraint names are unique per database.
Alternatively, you can create an AFTER INSERT and AFTER UPDATE trigger to make this validation, but a constraint works just fine in this case.

Resources