SQL, Delete Records Based On Related Fields In Other Table - sql

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.

Related

How primary key in one table connect to other table with the same primary key?

How primary key in one table connect to another table with the same primary key?
I am trying to make it like this, which those two primary key in the table of CustomerCreditCard is connect to the table of Customer and table of Credit card]
https://i.stack.imgur.com/lIBUE.png
--3
CREATE TABLE Customer
(
CustomerID INT IDENTITY PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
);
--5
CREATE TABLE CreditCard
(
CreditCardNumber VARCHAR(16) PRIMARY KEY,
CreditCardOwnerName VARCHAR(50) NOT NULL,
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT IDENTITY NOT NULL,
PRIMARY KEY(CreditCardNumber, CustomerID)
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT NOT NULL,
CONSTRAINT pk_CustomerCreditCard
PRIMARY KEY(CreditCardNumber,CustomerID ),
CONSTRAINT fk_CustomerCreditCard_CreditCardNumber
FOREIGN KEY(CreditCardNumber)
REFERENCES CreditCard(CreditCardNumber)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_CustomerCreditCard_CustomerID
FOREIGN KEY(CustomerID)
REFERENCES Customer(CustomerID)
ON DELETE CASCADE ON UPDATE CASCADE
);
To solve the problem of this question, add the foreign key to the table that has two primary keys, then reference to other tables that you want to connect with the same primary key.

SQL Missing left/right parenthesis

I keep getting a missing right or left parenthesis error when I try to create my tables with a foreign key, but when I remove the foreign key my code has no problem creating the tables. I need the code to run with the foreign keys.
--deletes respective tables previously created
drop table DEPARTMENT;
drop table POSITION;
drop table EMPLOYEE;
drop table COMPANY;
drop table DEGREE;
drop table GRAD_INFO;
drop table STUDENT;
CREATE TABLE Department
(
Dept_Name varchar(255) PRIMARY KEY, --primary key
Dept_Phone_Num numeric(35) not null
);
CREATE TABLE Position
(
Position_Name varchar(255) NOT NULL PRIMARY KEY, --primary key
Position_Salary decimal(10, 2) not null,
Employee_num numeric(35) not null,
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department (Dept_Name) --foreign key
);
CREATE TABLE Employee
(
EmployeeID INT NOT NULL PRIMARY KEY, --primary key
Employee_Salary DECIMAL(10,2) DEFAULT NULL,
Employee_FName VARCHAR(30) DEFAULT NULL,
Employee_LName VARCHAR(30) NOT NULL,
Employee_Address VARCHAR(30) DEFAULT NULL,
Employee_Phone_Num INT(10) DEFAULT NULL,
Employee_Email VARCHAR(30) NOT NULL,
Employee_Status VARCHAR(10) NOT NULL,
CONSTRAINT Position_Name
FOREIGN KEY Position_Name REFERENCES Position(Position_Name), --foreign key
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department(Dept_Name) --foreign key
);
CREATE TABLE Company
(
Comp_Name VARCHAR(20) NOT NULL PRIMARY KEY, --primary key
Position_Offer VARCHAR(30) NOT NULL,
Salary_Offer DECIMAL(10,2) NOT NULL,
Signing_Bonus DECIMAL(10,2) DEFAULT NULL,
Comp_Phone_Num INT(10) NOT NULL,
Comp_Address VARCHAR(30) NOT NULL,
CONSTRAINT fk_Employee_ID
FOREIGN KEY Employee_ID REFERENCES Employee (Employee_ID), --foreign key
CONSTRAINT fk_Dept_Name
FOREIGN KEY Dept_Name REFERENCES Department (Dept_Name) --foreign key
);
CREATE TABLE Degree
(
Degree_Type varchar(255) PRIMARY KEY, --primary key
Academic_Status varchar(255) not null,
Academic_Level varchar(255) not null,
Major varchar(255) not null,
Minor varchar(255) default null
);
CREATE TABLE Gead_Info
(
Grad_Status VARCHAR(255) NOT NULL PRIMARY KEY, --primary key
College_Name VARCHAR(255) NOT NULL,
Num_Of_Degrees NUMERIC(10) NOT NULL,
Grad_Date NUMERIC(6) NOT NULL,
CONSTRAINT fk_Degree_Type
FOREIGN KEY Degree_Type REFERENCES Degree(Degree_Type) --foreign key
);
CREATE TABLE Student
(
Student_ID NUMERIC(10) NOT NULL PRIMARY KEY, --primary key
Student_FName VARCHAR(20) NOT NULL,
Student_LName VARCHAR(20) NOT NULL,
Student_Address VARCHAR(20) NOT NULL,
Student_Email VARCHAR(20) NOT NULL,
Student_Phone_Num VARCHAR(10) NOT NULL,
CONSTRAINT fk_Comp_Name
FOREIGN KEY Comp_Name REFERENCES Company(Comp_Name), --foreign key
CONSTRAINT fk_Grad_Status
FOREIGN KEY Grad_Status REFERENCES Gead_Info(Grad_Status) --foreign key
);
The degree table is the only table where I don't get an error.
Should I use an alter table instead after I create all the tables or is there another way to solve my problem?
edit: updated code
I think your most immediate issue is with the Department table not having a comma between the two CONSTRAINT clauses. You might also run into issues with your Position table's CONSTRAINT clause referencing the Position table instead of the Employee table, although honestly I don't think you need that relationship defined at all since the Employee table already has a foreign key constraint with Position. And like what was stated earlier, your table definitions aren't in the right order so you have some tables referencing other tables before those others are created.
Give this a shot to see if the syntax works. I've added the column definition for the foreign key in Position, put parentheses around the foreign key column name in the CONSTRAINT clause, and removed the space between Department and the left paren in the CONSTRAINT clause. If this script works, make the same changes to your other table defs.
CREATE TABLE Department(
Dept_Name varchar(255) Primary Key, --primary key
Dept_Phone_Num numeric(35) not null
);
CREATE TABLE Position(
Position_Name varchar(255) not null Primary Key, --primary key
Position_Salary decimal(10, 2) not null,
Employee_num numeric(35) not null,
Dept_Name varchar(255) not null,
CONSTRAINT fk_Dept_Name FOREIGN KEY (Dept_Name) REFERENCES Department(Dept_Name) --foreign key
);

"Incorrect syntax near 'DESCRIBE'. [41,1]" No other context, can't find syntax error

New to SQL, can't figure out what is wrong in my given code. all it says is:
Incorrect syntax near 'DESCRIBE'. [41,1]
I have tried taking off the semi-colons. I really just don't know what it wants from me.
Here is my code. Anything helps, thank you!
-- Write the query to create the 4 tables below.
CREATE TABLE client (
id INT NOT NULL IDENTITY(1,1),
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
PRIMARY KEY (id),
CONSTRAINT (full_name) UNIQUE (first_name, last_name)
);
CREATE TABLE employee (
id INT NOT NULL IDENTITY(1,1),
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
date_joined DATE NOT NULL,
CONSTRAINT (full_name) UNIQUE (first_name, last_name),
PRIMARY KEY (id)
);
CREATE TABLE project (
id INT NOT NULL IDENTITY(1,1),
cid INT NOT NULL,
name VARCHAR(255) NOT NULL,
notes TEXT,
UNIQUE (name),
FOREIGN KEY (cid) REFERENCES client(id)
);
CREATE TABLE works_on (
eid INT NOT NULL,
pid INT NOT NULL,
start_date DATE NOT NULL,
PRIMARY KEY (eid, pid),
FOREIGN KEY (eid) REFERENCES employee(id),
FOREIGN KEY (pid) REFERENCES project(id)
);
-- Leave the queries below untouched. These are to test your submission correctly.
-- Test that the tables were created
DESCRIBE client;
DESCRIBE employee;
DESCRIBE project;
DESCRIBE works_on;
-- Test that the correct foreign keys were created
SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = 'grade';
For MariaDB (and MySQL) the correct syntax for IDENTITY(1,1), is AUTO_INCREMENT, and CONSTRAINT names are not enclosed in (). Any column that is defined as AUTO_INCREMENT must also be declared as a PRIMARY KEY (this is only an issue with the project table). So your CREATE TABLE commands should look like this:
CREATE TABLE client (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
PRIMARY KEY (id),
CONSTRAINT full_name UNIQUE (first_name, last_name)
);
CREATE TABLE employee (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
date_joined DATE NOT NULL,
CONSTRAINT full_name UNIQUE (first_name, last_name),
PRIMARY KEY (id)
);
CREATE TABLE project (
id INT NOT NULL AUTO_INCREMENT,
cid INT NOT NULL,
name VARCHAR(255) NOT NULL,
notes TEXT,
PRIMARY KEY (id),
UNIQUE (name),
FOREIGN KEY (cid) REFERENCES client(id)
);
CREATE TABLE works_on (
eid INT NOT NULL,
pid INT NOT NULL,
start_date DATE NOT NULL,
PRIMARY KEY (eid, pid),
FOREIGN KEY (eid) REFERENCES employee(id),
FOREIGN KEY (pid) REFERENCES project(id)
);
Demo on dbfiddle

i used the program SQL Fiddle and it keeps telling me that the table doesn't exist,what can i do to fix the two tables referencing each other?

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?

SQL Table Datastructure, is this wrong? Using CASCADING Delete

Here are the 3 tables I am having problems with:
Table: Opportunities - Holds various opportunity(job) descriptions
Table: Opportunities_Applicants - Holds various applicants applying for opportunities. 1 Applicant can only apply for 1 opportunity, however 1 opportunity can have many applicants
Table: Opportunities_Category - Holds category name and type. 1 Category can relate to many Opportunities.
I am trying to perform a CASCADING Delete when a Opportunity Category is deleted, it will delete corresponding Opportunities and Applicants for those Opportunities.
Is this structure appropriate or should I setup database differently? How should my table relationships be setup in order for the CASCADING Delete to work when a Opportunity Category is deleted?
Should I even be using CASCADING Delete?
create table Opportunities_Category
(
CategoryID int identity(1,1) not null
constraint PK_CategoryID primary key clustered,
[Name] varchar(150) not null,
[Type] varchar(100) not null --Pay, Volunteer, Volunteer Yearly
)
create table Opportunities
(
OpportunityID int identity(1,1) not null
constraint PK_OpportunityID primary key clustered,
CategoryID int not null
constraint FK_CategoryID foreign key references Opportunities_Category(CategoryID) ON DELETE CASCADE,
Title varchar(300) not null,
PostingDate datetime not null,
ClosingDate datetime not null,
Duration varchar(150) not null, --Part Time, Full Time, Seasonal, Contract
Compensation varchar(150) not null, --Hourly, Volunteer, Salary
[Description] varchar(5000) not null,
Qualifications varchar(5000) not null,
Show int not null
)
create table Opportunities_Applicant
(
ApplicantID int identity(1,1) not null
constraint PK_ApplicantID primary key clustered,
OpportunityID int not null
constraint FK_OpportunityID foreign key references Opportunities(OpportunityID) ON DELETE CASCADE,
[First] varchar(150) not null,
[Last] varchar(150) not null,
Phone varchar(20) not null,
Cell varchar(20) not null,
EMail varchar(200) not null,
CoverLetterResume varchar(300) null,
[Timestamp] datetime not null
)
It turns out that my tables are setup properly:
Yesterday, i had been trying to do: DELETE FROM Opportunities WHERE CategoryID = #CategoryID. This was only deleting the records from Opportunities and Opportunities_Applicants.
Today, i changed to: DELETE FROM Opportunities_Categoies WHERE CategoryID = #CategoryID and all 3 tables are deleting their corresponding records!
ALTER TABLE [dbo].[Opportunities] WITH CHECK ADD CONSTRAINT [FK_OpportunitiesCategory_Opportunities] FOREIGN KEY([CategoryID])
REFERENCES [dbo].[Opportunities_Category] ([CategoryID])
ON DELETE CASCADE
GO
Good Luck...