Insert row into a table with foreign key - sql

I have created two tables (SupplierName and SupplierAddress) in the address_book database.
Table SupplierName has one row inserted as shown in the insert statement below. I am struggling how to insert data into the table called SupplierAddress.
Please note that the SupplierID (primary key) from the SupplierName table is the foreign key in the SupplierAddress table. If my table design is incorrect please opine on that as well. I am just trying to create a simple database to learn SQL.
CREATE TABLE SupplierName
(
SupplierID int Primary Key identity(1,1) NOT NULL,
CompanyName varchar(50) NOT NULL,
EIN char(9) NOT NULL UNIQUE
)
CREATE TABLE SupplierAddress
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Address varchar(50),
City varchar(50),
State char(2),
ZipCode char(5),
Phone varchar(10),
SupplierAddressID int FOREIGN KEY REFERENCES SupplierName(SupplierID)
)
INSERT INTO SupplierName (CompanyName, EIN)
VALUES ('Clarks Electronics, Inc.', '123456789');
INSERT INTO SupplierAddress (Address, City, State, ZipCode, Phone)
VALUES ('2020 Garnet Road', 'York', 'PA', '17403', '717-123-4567')
SELECT
SupplierName.SupplierID, SupplierAddress.SupplierAddressID
FROM
SupplierName
INNER JOIN
SupplierAddress ON SupplierAddressID=SupplierID

Remove the hyphens from the phone number, or create table with more characters in phone
Look at http://www.dpriver.com/pp/sqlformat.htm to pretty format the sql
CREATE TABLE supplieraddress
(
id INT PRIMARY KEY IDENTITY(1, 1) NOT NULL,
address VARCHAR(50),
city VARCHAR(50),
state CHAR(2),
zipcode CHAR(5),
phone VARCHAR(10), -- make this longer
supplieraddressid INT FOREIGN KEY REFERENCES suppliername(supplierid)
)
INSERT INTO supplieraddress
(address,
city,
state,
zipcode,
phone)
-- add supplieraddressid and its value so that the FK is created
VALUES ('2020 Garnet Road',
'York',
'PA',
'17403',
'717-123-4567') -- or remove hyphens
SELECT suppliername.supplierid,
supplieraddress.supplieraddressid
FROM suppliername
INNER JOIN supplieraddress
ON supplieraddressid = supplierid

Related

Getting duplicate data when using the select statements

I'm getting duplicate data when trying to use the select statements, I have 9 rooms but I'm getting around 50-70 rooms when trying to display them. Help please?
I'm trying to insert data and display it using the select statement.
create table gym (
GymName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table Spa (
spaName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table customer (
CustomerID int primary key,
Firstname varchar(200) not null,
LastName varchar(200) not null,
DOB date not null check (DATEDIFF(year,DOB,getdate ()) > 18) ,
Gender char(4) not null check(Gender ='M' or Gender = 'F'),
Address varchar(200) not null default 'Jordan',
spaName VARCHAR(200) foreign key references Spa(spaName),
GymName VARCHAR(200) foreign key references gym(GymName),
);
Create table CustomerPhoNo (
CustomerID int foreign key references customer(CustomerID),
PhoneNo bigint not null,
);
create table Room (
roomNo int primary key,
Availability char(4) not null,
NoOfBeds int not null,
Rate int not null,
CheckIn date,
CheckOut date,
Price Decimal not null,
Breakfast char(4),
CustomerID int foreign key references customer(CustomerID),
);
create table LocationOfRoom (
roomNo int foreign key references Room(roomNo),
seaview char(4),
Location varchar(20) not null,
);
create table RoomType (
roomNo int foreign key references Room(roomNo),
familyRoom char(4),
doubleRoom char(4),
singleRoom char(4),
);
create table Gservice (
GymName VARCHAR(200) foreign key references gym(GymName),
Service VARCHAR(500) not null,
MachineType VARCHAR(500) not null,
);
create table PaymentCard (
CardID int primary key,
issueDate date not null,
Expirydate date not null,
CustomerID int foreign key references customer(CustomerID),
);
insert into customer values (325,'Mohammad','Alasharan','06-04-1984','M','Amman', 'BeautySpa', 'StrongBody')
insert into customer values (348,'John','Shelby','10-18-1998','M','Birmingham', 'LushLife', 'SilverGym')
insert into customer values (495,'Thomas','Hoffman','04-26-1968','M','Johannesburg', 'RelaxationTherapy', 'SilverGym')
insert into customer values (194,'Anne','Frank','07-22-2001','F','Frankfurt', 'BeautySpa', 'StrongBody')
insert into customer values (628,'Katie','Swan','02-10-1997','F','New South Wales', 'LushLife', 'FitnessHeroes')
insert into customer values (246,'Mahmoud','Alkutaifan','04-21-1994','M','Amman', 'BeautySpa', 'FitnessHeroes')
insert into customer values (864,'Karl-Heinz','Rummenigge','09-25-1955','M','Lippstadt', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (824,'Dennis','Law','09-21-1979','M','london', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (463,'Carles','Puyol','06-17-1973','M','madrid', 'LushLife', 'FitnessHeroes')
insert into Room values (124,'yes','1','4',null,null,'30','yes',null)
insert into Room values (135,'no','2','5','05-06-2022','05-09-2022','55','yes',495)
insert into Room values (121,'yes','1','3',null,null,'40','yes',null)
insert into Room values (139,'no','3','4','05-10-2022','05-14-2022','110','no',194)
insert into Room values (131,'no','3','3','05-18-2022','05-22-2022','130','yes',348)
insert into Room values (136,'no','4','4','04-14-2022','04-24-2022','120','yes',194)
insert into Room values (179,'yes','4','5',null,null,'95','no',null)
insert into Room values (138,'no','3','3','04-02-2022','04-06-2022','75','no',246)
insert into Room values (146,'no','3','5','05-10-2022','05-14-2022','80','yes',864)
insert into LocationOfRoom values (124,'no','south')
insert into LocationOfRoom values (135,'yes','north')
insert into LocationOfRoom values (121,'yes','south')
insert into LocationOfRoom values (139,'no','north')
insert into LocationOfRoom values (131,'no','East')
insert into LocationOfRoom values (136,'yes','west')
insert into LocationOfRoom values (179,'no','south')
insert into LocationOfRoom values (138,'no','west')
insert into LocationOfRoom values (146,'yes','north')
insert into RoomType values (124,'no','no','yes')
insert into RoomType values (135,'no','yes','no')
insert into RoomType values (121,'yes','no','no')
insert into RoomType values (139,'no','no','yes')
insert into RoomType values (131,'no','no','yes')
insert into RoomType values (136,'no','no','yes')
insert into RoomType values (179,'no','no','yes')
insert into RoomType values (138,'no','yes','no')
insert into RoomType values (146,'no','no','yes')
-- display Total number of customers who booked a single room with sea view option
select count(Firstname)
from LocationOfRoom, customer, RoomType, Room
where seaview='yes' and singleRoom='yes'
Any help would be greatly appreciated, thank you in advance!
Your FROM clause is missing the join condition for each table. In other words you are getting the cartesian product (every combination of rows) of the tables. Even distinct won't help (it will get the wrong answer). Use join conditions to link the keys of each table to each other. I'll leave this an exercise for you to try out, but this should be enough information to help you out.
I believe the solution for your problem is that you need to use DISTINCT:
SELECT COUNT(DISTINCT(Firstname))
FROM LocationOfRoom, customer, RoomType, Room
WHERE seaview='yes' AND singleRoom='yes'
I have tested it and it retrieves 9 Rooms.

MIN/MAX VALUES GROUP BY ID

Find the names and addresses of the customers with the highest balance and the people with the lowest loan in each branch.
Tables:
CREATE TABLE Branch(
BranchID INT NOT NULL,
Address varchar(100),
ManagerSsn varchar(100),
Branch_name varchar(255),
PRIMARY KEY (BranchID)
);
CREATE TABLE Has_Account(
Assn Int,
ANo CHAR(16),
Opened_date date,
PRIMARY KEY(Assn),
FOREIGN KEY(Assn) REFERENCES Customer(Ssn),
FOREIGN KEY(ANo) REFERENCES Account(AccountNo)
);
CREATE TABLE Account(
AccountNo CHAR(16) NOT NULL,
BranchID Int,
Balance Int,
PRIMARY KEY(AccountNo),
FOREIGN KEY(BranchID) REFERENCES Branch(BranchID)
);
CREATE TABLE Customer(
Ssn Int CHECK(0101000000000 < Ssn < 3112999995999) NOT NULL,
Address VARCHAR(100),
Name VARCHAR(100),
EmployerID Int,
PRIMARY KEY(Ssn)
);
CREATE TABLE Loan(
LoanNo CHAR(16) NOT NULL,
BranchID Int,
Amount Int,
PRIMARY KEY(LoanNo),
FOREIGN KEY(BranchID) REFERENCES Branch(BranchID)
);
CREATE TABLE Has_Loan(
LNo CHAR(16),
Lssn Int,
Repay_date date,
PRIMARY KEY (LNo),
FOREIGN KEY(Lno) REFERENCES Loan(LoanNo),
FOREIGN KEY(Lssn) REFERENCES Customer(Ssn)
);
Populating the tables
INSERT INTO CUSTOMER
VALUES('2004980890999', ‘Kanaribakken 2B’, ‘Paul Stolten’, ‘’);
INSERT INTO CUSTOMER
VALUES(‘1010968250234’, ‘Parkveien 5’, ‘Anders Nilsson’, ‘’, );
INSERT INTO CUSTOMER
VALUES(‘2104996495987’, ‘Kongeveien 24B’, ‘Karoline Torskerud’, ‘123’, );
INSERT INTO CUSTOMER
VALUES(‘2910943135444’, ‘Gåsesmauet 3’, ‘Bente Arildsen’, ‘555’, );
INSERT INTO CUSTOMER
VALUES(‘1304980890678’, ‘Knallebakken 30’, ‘Knut Solberg’, ‘555’,);
INSERT INTO CUSTOMER
VALUES('1019730000234', ‘Laksebakken 40’, ‘Harald Olsen’, ‘’);
INSERT INTO BRANCH
VALUES (‘123’, ‘Børsveien 49’, ‘1412963670786’, ‘Nesttun’,);
INSERT INTO BRANCH
VALUES(‘555’, ‘Vimpelveien 24’, ‘2412983905999’, ‘DNB’,);
INSERT INTO ACCOUNT
VALUES (‘1234567890087620’, ‘123’, ‘459’,);
INSERT INTO ACCOUNT
VALUES (‘8402849284910340’, ‘123’, ‘35120’,);
INSERT INTO ACCOUNT
VALUES (‘3452948293817280’, ‘555’, ‘69’,);
INSERT INTO HAS_ACCOUNT
VALUES(‘1010968250234’, ‘1234567890087620’, ‘17.04.2012’,);
INSERT INTO HAS_ACCOUNT
VALUES (‘2104996495987’, ‘8402849284910340’, ‘20.09.2000’,);
INSERT INTO HAS_ACCOUNT
VALUES (‘2910943135444’, ‘3452948293817280’, ‘29.01.2006’,);
INSERT INTO LOAN
VALUES (‘2291928394039280’, ‘555’, ‘50000’,);
INSERT INTO LOAN
VALUES (‘1295829384932100’, ‘123’, ‘400000’,);
INSERT INTO LOAN
VALUES ('1295829384932222', ‘123’, ‘40000’);
INSERT INTO HAS_LOAN
VALUES (‘2910943135444’, ‘2291928394039280’, ‘09.09.2019’,);
INSERT INTO HAS_LOAN
VALUES (‘2104996495987’, ‘1295829384932100’, ‘14.03.2022’,);
INSERT INTO HAS_LOAN
VALUES ('2004980890999', '1295829384932222', '01.02.2021');
Draft so far:
SELECT DISTINCT Customer.Name, Customer.Address
FROM Customer, Account, Loan, Has_Account, Has_Loan
WHERE Customer.Ssn = Has_Account.Assn AND Has_Account.Assn = Has_Loan.Lssn
(SELECT Account.Balance MAX(Balance) GROUP BY(BranchID)) AND
Loan.AMOUNT(SELECT Loan.Amount MIN(Amount) GROUP BY(BranchID));
I think it is correct that we need to group our output by BranchID, and max/min is ok. Looks like the statement formalities are wrong somehow.
Any help or hint is much appreciated!

SQL Error Missing Right Paretheses

I am just learning SQL and when I try to create the "Order" table I get the error "missing right parentheses". When I remove the FK constraint I get the error "invalid identifier"
DROP TABLE CUSTOMER;
CREATE TABLE CUSTOMER
(
CUST_ID INT PRIMARY KEY,
COMP_NAME VARCHAR(40),
CONT_LNAME VARCHAR(30),
CONT_FNAME VARCHAR(30),
PHONE VARCHAR(30),
EMAIL VARCHAR(40),
ADDRESS VARCHAR(40),
CITY VARCHAR(30),
ZIP NUMBER
);
INSERT INTO CUSTOMER (CUST_ID, COMP_NAME, CONT_LNAME, CONT_FNAME, PHONE, EMAIL, ADDRESS, CITY,ZIP) VALUES
(1,'Atomic Liqours','Signor','Rose','518-990-8765','rose#atomicliqours.com','76 Hackett Blvd','Albany','12204');
INSERT INTO CUSTOMER (CUST_ID, COMP_NAME, CONT_LNAME, CONT_FNAME, PHONE, EMAIL, ADDRESS, CITY,ZIP) VALUES
(2,'HBD Bar','Capozolli','Rose','889-908-6666','rose#hbd.com','888 Project Rd','Troy','12180');
INSERT INTO CUSTOMER (CUST_ID, COMP_NAME, CONT_LNAME, CONT_FNAME, PHONE, EMAIL, ADDRESS, CITY,ZIP) VALUES
(3,'Lee Harvey','Smith','Seth','675-888-9999','seth#lh.com','78 Healy Ave','Troy','12222');
-- CREATING ORDER TABLE
CREATE TABLE ORDERS
(
ORD_ID INT PRIMARY KEY,
CUST_ID INT FOREIGN KEY REFERENCES Customers (CUST_ID),
ORD_DATE DATE,
DEL_DATE DATE,
);
Looks like your have a typo in your script. Your table name is CUSTOMER, but in CREATE TABLE you references to CUSTOMERS. So, I think that your create table statement must looks like:
CREATE TABLE ORDERS
(
ORD_ID INT PRIMARY KEY,
CUST_ID INT FOREIGN KEY REFERENCES Customer (CUST_ID),
ORD_DATE DATE,
DEL_DATE DATE,
);

Integrity constraint (JAVAUSER.SYS_C007925) violated - parent key not found

SQL Error
I'm not sure what I did wrong here
Here is the DDL I used to create my tables
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
Create Table Country (CountryAbbreviation char(2) Primary Key,
CountryName varchar(35));
Create Table Employee (EmployeeID Integer Primary Key NOT NULL,
FirstName varchar(20),
LastName varchar(30),
MI char(1),
HomeAddress varchar(30),
Zip char(5),
DateOfBirth date,
HireDate date,
TerminationDate date,
AnnualSalary number(20,2),
LicenseDate date,
StateAbbreviation char(2),
CountryAbbreviation char(2),
Foreign Key (StateAbbreviation) references HomeState,
Foreign Key (CountryAbbreviation) references Country);
Create Table Truck (VinNumber Integer Primary Key,
Make varchar(25),
Model varchar(30),
Year Integer,
PurchasePrice number(20,2),
LicenseNumber varchar(15));
Create Table EmployeeTruck (EmployeeID Integer,
VinNumber Integer,
Primary Key(EmployeeID,VinNumber),
Foreign Key (EmployeeID) references Employee,
Foreign Key (VinNumber) references Truck);
Create Table Accident (AccidentID Integer Primary Key,
DateOfAccident date,
AccidentDescription varchar(200),
AccidentLocation varchar(100),
EmployeeID Integer,
Foreign Key (EmployeeID) references Employee);
and here is the command i used to try and fill in the employee table
insert into employee
values ('1','brian','kim','j','adfasdf',
'1234','24-nov-1993','24-sep-1993','24-sep-1993',
'1234','24-sep-1993','as','as')
but it always gives me the error i put as the title of this question...
In the table "Employee", you say that Foreign Key (StateAbbreviation) references HomeState, and Foreign Key (CountryAbbreviation) references Country). The values you insert into Employee.HomeState and Employee.CountryAbbreviation have to exist in the tables HomeState and Country before you can insert into Employee.
Insert rows into HomeState and Country before you insert into Employee.
You have other problems, too. Here's an example.
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
insert into HomeState values ('AL', 'Alabama');
insert into HomeState values ('AM', 'Alabama');
insert into HomeState values ('AN', 'Alabama');
All those insert statements succeed. They shouldn't. In this case, StateName is also a candidate key.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Let's take this a little further.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Create Table Country (
CountryAbbreviation char(2) Primary Key,
CountryName varchar(35) not null unique
);
insert into HomeState values ('CA', 'California');
insert into Country values ('AF', 'Afghanistan');
insert into Employee (EmployeeID, StateAbbreviation, CountryAbbreviation)
values (-42, 'CA', 'AF');
The state "California, US" makes sense. The state "California, Afghanistan" doesn't.
An employee having no name doesn't make sense. Declare FirstName, LastName, and HireDate not null.
Bet on this: whatever nonsense your database allows will appear. It's just a matter of time.

Beginner learning sql joins in mySQL

I have created 3 tables: dog, customer and owner. It is a many to one relationship with many dogs owned by 1 customer.
CREATE TABLE dog
(
DogID int(6) NOT NULL,
DogName varchar(15),
medicalID int (6),
Gender character(1) check(gender in ('m', 'f')),
Age int(2),
Breed varchar(15),
size character (1) check(size in ('s', 'm', 'l')),
primary key (DogID));
CREATE TABLE Owns
(
DogID int (6)primary key,
CustomerID int (6),
foreign key (CustomerID) references customer (CustomerID),
foreign key (DogID) references dog (DogID));
CREATE TABLE customer
(
CustomerID int(6) NOT NULL,
FirstName varchar(15),
Surname varchar(15),
Address varchar(225),
email varchar (30),
TelNo varchar (15),
MobNo Varchar (15),
EmergencyName varchar (40),
EmergencyPhoneNo varchar(15),
primary key (CustomerID));
I have queried with but nothing is returned.
select dog.dogName
from dog, owns, customer
where owns.dogID = dog.dogId
and customer.customerID = owns.customerID
and customer.FirstName = "CustomersName";
You created the tables, now you need to INSERT the data.
INSERT INTO dog(<fields>) VALUES(<values>);
If you have successfully created the tables the next step is to put some data in them. Otherwise you won't get anything back from your query. You need to insert a record into the dog and customer tables and associate them via the owns table. After performing those 3 inserts you should be able to join on their keys and query for data.
For example:
insert into dog(DogID, DogName, medicalID, Gender, Age, Breed, Size) values ('111111', 'Spike', '111111', '12', 'Wolf', 'l' );
insert into customer ( CustomerID, FirstName, Surname, Address, email, TelNo, MobNo, EmergencyName, EmergencyPhoneNo ) values ( '222222', 'Abe', 'Lincoln', '123 Street', 'blah#blah.com', '8675309', '8675309', 'Bob', '8675309' );
insert into owns ( DogID, CustomerID ) values ( '111111', '222222' );
select DogName from dog as d
join owns as o on o.DogID = d.DogID
join customer as c on c.CustomerId = o.CustomerID
where c.FirstName = 'Abe';
Note that your syntax may be slightly different. I've been using Oracle for a while.