how to create this table in sql server? - sql

i fond it hard to create a table for this problem. can somebody help me?
You are the owner of some tables for Sweeney Tours that have been created for you already. They are:
COUNTRY(country, language, timezone, currency)
REGION(region, landtype, country, scenery, page)
RESORT(resort, region, transfertime, beach, beachnum, page)
HOTELS(hotelid, hotelname, sunbeam, ya, rating, stdbasis, page, resort,
resortloc, roomtotal)
FACILITIES(facid, description, category)
FACINRESORT(resort, facid)
FACINHOTEL(hotelid, facid, numof)
Each hotel has one standard meal basis on offer (stdbasis), always one of Half Board (hb), Bed&Breakfast (bb), Full Board (fb) or Apartment Only (ao). Some hotels are designated "Young and Active" (meaning ideal for 18-30 year olds) (ya). A few resorts cater particularly well for children by running a 'SunBeam Club' (sunbeam) where parents can leave their children. These clubs are associated with particular hotels in the resort. Each hotel has a distance from the centre of the resort included (resortloc). The transfer time from the airport to the resort is included (transfertime).
Resort and/or Hotels have facilities such as swimming pools, discos, horse riding, waiter service, kids playgrounds, telephones in bedrooms etc. Facilities fall into a number of different categories:
(6?)
accommodation a
entertainment e
sport s
meals m
children c
bedroom b

may be this will help you:
CREATE TABLE COUNTRY(
country VARCHAR(255) PRIMARY KEY,
language VARCHAR(255),
timezone TIMESTAMP,
currency FLOAT
)
CREATE TABLE REGION(
region VARCHAR(255) PRIMARY KEY,
landtype VARCHAR(255),
country VARCHAR(255) FOREIGN KEY REFERENCES COUNTRY(country),
scenery VARCHAR(255),
page INTEGER UNIQUE,
)
CREATE TABLE RESORT(
resort VARCHAR(255) PRIMARY KEY,
region VARCHAR(255) FOREIGN KEY REFERENCES REGION(region),
transfertime TIMESTAMP,
beach VARCHAR(255),
beachnum VARCHAR(255),
page INTEGER FOREIGN KEY REFERENCES REGION(page)
)
CREATE TABLE STDBASIS(
id INTEGER AUTO_INCREMENT PRIMARY KEY,
code VARCHAR(3),
description VARCHAR(255)
)
CREATE TABLE HOTELS(
hotelid BIGINT AUTO_INCREMENT PRIMARY KEY,
hotelname VARCHAR(255),
sunbeam VARCHAR(255),
ya VARCHAR(255),
rating VARCHAR(255),
stdbasis VARCHAR(255) FOREIGN KEY REFERENCES STDBASIS(id),
page INTEGER FOREIGN KEY REFERENCES REGION(page),
resort VARCHAR(255) FOREIGN KEY REFERENCES REGION(resort),
resortloc VARCHAR(255),
roomtotal INTEGER,
CONSTRAINT chk_stdbasis CHECK (stdbasis BETWEEN 0 AND 4)
)
CREATE TABLE FACILITIES(
facid VARCHAR(255) PRIMARY KEY,
description VARCHAR(255),
category INTEGER
)
CREATE TABLE FACINRESORT(
resort VARCHAR(255) FOREIGN KEY REFERENCES REGION(resort),
facid VARCHAR(255) FOREIGN KEY REFERENCES FACILITIES(facid),
CONSTRAINT pk_rID PRIMARY KEY (resort,facid)
)
CREATE TABLE FACINHOTEL(
hotelid VARCHAR(255) FOREIGN KEY REFERENCES HOTELS(hotelid),
facid VARCHAR(255) FOREIGN KEY REFERENCES FACILITIES(facid),
numof INTEGER,
CONSTRAINT pk_hID PRIMARY KEY (hotelid,facid)
)
Please change datatypes and primary/foreign keys as per your business problem
you need to insert data in STDBASIS table as below:
INSERT INTO STDBASIS
(code, description)
VALUES
("hb", "Half Board"),
("bb", "Bed&Breakfast"),
("fb", "Full Board"),
("ao", "Apartment Only")
you need to insert data in FACILITIES table as below:
INSERT INTO FACILITIES
(facid , description)
VALUES
("a", "accommodation"),
("e", "entertainment"),
("s", "sport"),
("m", "meals"),
("c", "children"),
("b", "bedroom")

Related

Number of referencing columns must match referenced columns

I am relatively new to SQL and I keep getting the following error "The number of columns in the foreign-key referencing list is not equal to the number of columns in the referenced list."
create table client
(name varchar(30),
phone int,
city varchar(20),
state char(2) CHECK(state='MN' OR state='ND' OR state='SD' OR state='WI' or state='IA'),
primary key(name,phone));
create table owns_vehicle
(name varchar(30),
phone int,
vin varchar(10),
primary key(name, phone, vin),
foreign key(name,phone) references client);
create table service_appointment
(mydate date,
vin varchar(10),
mechanic varchar(15),
description varchar(30) NOT NULL,
cost int CHECK (cost>=0),
primary key(mydate,vin),
foreign key(vin) references owns_vehicle);
This is the line that is causing the issue:
foreign key(vin) references owns_vehicle);
Does anyone know why I am getting this error?
You try to reference owns_vehicle, thus you need to reference all of the tables PRIMARY KEY columns, which would be name, phone, vin. But your foreign key has only vin, thus there are two columns (name, phone) missing.
The primary key has three parts. You need to reference all of them. If you are going to use this model, then you need the other two components:
create table service_appointment (
mydate date,
name varchar(30),
phone int,
vin varchar(10),
mechanic varchar(15),
description varchar(30) NOT NULL,
cost int CHECK (cost>=0),
primary key(mydate,vin),
foreign key(name, phone, vin) references owns_vehicle (name, phone, vin)
);
However, I think you data model should change. VINs can change owners. People can change phone numbers. These don't seem like good components of a primary key.
If you assume that a vehicle can only have a single owner at a given time, you can make your current data model work by changing owns_vehicle to have a uniqueness constraint on VIN:
CREATE TABLE OWNS_VEHICLE
(NAME VARCHAR2(30),
PHONE INT,
VIN VARCHAR2(10),
CONSTRAINT PK_OWNS_VEHICLE
PRIMARY KEY(NAME, PHONE, VIN)
USING INDEX,
CONSTRAINT OWNS_VEHICLE_UQ1
UNIQUE(VIN)
USING INDEX,
CONSTRAINT OWNS_VEHICLE_FK1
FOREIGN KEY(NAME,PHONE) REFERENCES CLIENT(NAME, PHONE));

SQL: Foreign key references a composite primary key

I'm new to SQL and there are a lot of things going on that I still don't seem to quite understand. I have the following table
CREATE TABLE Person
(
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
PRIMARY KEY (First_Name, Name, Address)
);
I know want to create another table that has the primary key from the table Person as foreign key and also as primary key:
CREATE TABLE Purchase
(
No_Installments int,
Rate int,
Person varchar(50) NOT NULL PRIMARY KEY,
CONSTRAINT PFK
FOREIGN KEY (Person) REFERENCES Person (First_Name, Name, Address)
);
For some reason this doesn't work and I get an error every time. I've already looked up the other threads here on stackoverflow, but they don't really seem to help me. What am I doing wrong?
If you have a compound PK made up from three columns, then any child table that wants to establish a foreign key relationship must ALSO have all those 3 columns and use all 3 columns to establish the FK relationship.
FK-PK relationship is an all or nothing proposal - you cannot reference only parts of a primary key - either you reference all columns - or you don't reference.
CREATE TABLE Purchase
(
No_Installments int,
Rate int,
Person varchar(50) NOT NULL PRIMARY KEY,
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
CONSTRAINT PFK
FOREIGN KEY (First_Name, Name, Address)
REFERENCES Person (First_Name, Name, Address)
);
Have an integer primary key, using identity, auto_increment, serial or whatever for your database:
CREATE TABLE Person (
PersonId int identity PRIMARY KEY
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
CONSTRAINT unq_person_3 UNIQUE (First_Name, Name, Address)
);
Then use the identity column for the reference:
CREATE TABLE Purchase (
PurchaseId int identity PRIMARY KEY,
No_Installments int,
Rate int,
PersonId int,
CONSTRAINT PFK
FOREIGN KEY (PersonId) REFERENCES Person (PersonId)
);
Notes:
You really don't want to have to deal with a composite primary key. Have you thought about what the joins will look like?
You don't want a primary key where the values are subject to change. What happens when someone changes his/her name? When someone moves?
Person should not be the primary key in Purchases. Are you only allowing someone to make one purchase?
As noted initially, how you generate such a column varies by database; identity happens to be the way that SQL Server does this.
You probably want to assign a unique ID to each person, not relying on their name to be unique or for an address to be required. That ID will be your Primary key and foreign key. Your purchase table should also have its own id for its primary key -- otherwise because primary keys must be unique, each person can only have one purchase.
CREATE TABLE Person (
id serial NOT NULL,
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
PRIMARY KEY (id));
CREATE TABLE Purchase (
id serial NOT NULL,
No_Installments int,
Rate int,
Person int NOT NULL,
FOREIGN KEY (Person) REFERENCES Person (id),
PRIMARY KEY (id));

SQL - is developing queries based on nonexistent data possible?

Is it possible to develop a query from nonexistent data? for example, I have this schema :
-- ZIP code database
BEGIN TRANSACTION;
CREATE TABLE city (
city_id INT,
city_name VARCHAR(80),
city_county VARCHAR(80),
city_state VARCHAR(5),
city_country VARCHAR(5),
city_region VARCHAR(5),
longitude INT,
latitude INT,
timezone varchar(80),
PRIMARY KEY (city_id)
);
CREATE TABLE zipcode (
zipcode CHAR(5),
ziptype VARCHAR(36),
active BOOLEAN,
primary_city_id INT NOT NULL,
notes TEXT,
PRIMARY KEY (zipcode),
FOREIGN KEY (primary_city_id) REFERENCES city(city_id)
);
CREATE TABLE acceptable (
zipcode CHAR(5),
city_id INT,
acceptable BOOLEAN,
PRIMARY KEY (zipcode, city_id),
FOREIGN KEY (zipcode) REFERENCES zipcode(zipcode),
FOREIGN KEY (city_id) REFERENCES city(city_id)
);
CREATE TABLE zip_areacode (
zipcode CHAR(5),
areacode VARCHAR(5),
PRIMARY KEY (zipcode, areacode),
FOREIGN KEY (zipcode) REFERENCES zipcode(zipcode),
FOREIGN KEY (areacode) REFERENCES areacode(prefix)
);
COMMIT;
//from here, would I be able to filter out results by the zip code with the highest population? This isn't possible, right? I don't see any data regarding population
No, you cant. Because you have no information about population. Thus your queries will be on non existent relations. That's not possible.
You can create temporary tables (relations) if you want. And fill it with random data. But I don't think you'll find out something useful.

SQL Constraints Confusion

I'm in a bit of a mix right now, I have a Table called Avatars, which has a foreign key called Family. Now, in the family table, I have two Foreign Keys called Mother and Father - Now this is the confusing bit, in both the Mother and Father Tables, there is a Foreign key called Avatar_ID which is of course the Primary Key to the Avatars table. I'm not sure if that's even allowed in SQL PLUS.
Whenever I try and enter the tables 'Family, Mother or Father', I keep getting the error:ORA-02291: integrity constraint (SG304.FK_FATHER_ID) violated - parent key not found.
Is there any way around this? Or will I have to change my code completely? A sample of the code is below.
CREATE TABLE Avatars (
Avatar_ID VARCHAR(10) NOT NULL,
Avatar_Name VARCHAR(30),
AvA_DOB DATE,
Age VARCHAR(30),
Gender VARCHAR(30),
Strength_Indicated INT,
Hoard INT,
Avatar_Level VARCHAR(30),
Skill VARCHAR(30),
Original_Owner VARCHAR(30),
Family_ID VARCHAR(10) NOT NULL,
Species_ID VARCHAR(10) NOT NULL,
Inventory_ID VARCHAR(30) NOT NULL,
Weapon_ID VARCHAR(10),
Player_ID VARCHAR(10) NOT NULL,
PRIMARY KEY (Avatar_ID));
CREATE TABLE Family (
Family_ID VARCHAR(10) NOT NULL,
Mother_ID VARCHAR(10) NOT NULL,
Father_ID VARCHAR(10) NOT NULL,
primary key(Family_ID)
);
CREATE TABLE Mother (
Mother_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Mother_ID)
);
CREATE TABLE Father (
Father_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Father_ID)
);
ALTER TABLE Avatars
ADD CONSTRAINT fk_Family_ID
FOREIGN KEY (Family_ID)
REFERENCES Family(Family_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Mother_ID
FOREIGN KEY (Mother_ID)
REFERENCES Mother(Mother_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Father_ID
FOREIGN KEY (Father_ID)
REFERENCES Father(Father_ID);
ALTER TABLE Father
ADD CONSTRAINT fk_Avatar_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
ALTER TABLE Mother
ADD CONSTRAINT fk_Avatars_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
INSERT INTO Avatars (Avatar_ID,Avatar_Name,AvA_DOB,Age,Gender,Strength_Indicated,Hoard,Avatar_Level, Skill, Original_Owner, Family_ID,Species_ID,Inventory_ID,Player_ID) VALUES
('Ava01','Verda','20-JAN-2014','1 year 2 months','Female','100','20','Master','Leader',' - ',' - ','DRA1','MasterInventory','Player07');
Thanks in advance for any help given! (:
Foreign key refers to a record in parent table. In your INSERT statement you are inserting value ' - ' into a column parent_id. In this error message oracle informs you that there is no record with value ' - ' in a column family_id of a table family. As I can understand, you are trying to use ' - ' as 'absence of value'. There is special value for that - NULL. So you need to write your statement as:
INSERT INTO Avatars (Avatar_ID, Avatar_Name, AvA_DOB,
Age, Gender, Strength_Indicated, Hoard, Avatar_Level, Skill,
Original_Owner, Family_ID, Species_ID, Inventory_ID, Player_ID)
VALUES ('Ava01', 'Verda', '20-JAN-2014', '1 year 2 months' ,'Female',
'100', '20', 'Master', 'Leader', NULL, NULL, 'DRA1',
'MasterInventory', 'Player07');
Also I can recommend some changes to your schema. First of all, use number data type for primary keys - it allows you to use sequences to generate unique values. Also, I don't know details of the problem, but "family relations" in your tables look a bit complicated. You can describe it in a single table:
create table family_tree (
person_id number primary key,
father_id number,
mother_id number,
sex char(1),
name varchar2(50),
family_name varchar2(50));
add constraint fk_mother_id foreign key (mother_id)
references family_tree (person_id);
add constraint fk_father_id foreign key (father_id)
references family_tree (person_id);

sql 3NF Normalization

is this in 3NF ?
create table movies(
id numeric primary key not null default autoincrement,
name varchar(50) not null,
release-date Date,
price numeric,
rating numeric,
length numeric,
description varchar(1500)
);
create table movies(
id numeric primary key,
name varchar(20)
);
create table genre(
name varchar(20) primary key
);
create table directors(
id numeric primary key not null default autoincrement,
first-name varchar(32) not null,
last-name varchar(32) not null,
gender varchar(8),
dob Date,
biography varchar(1000)
);
create table movie-Star(
id numeric primary key not null default autoincrement,
first-name varchar(20) not null,
last-name varchar(20) not null,
gender varchar(8),
dob Date,
hometown varchar(20)
);
create table movies-cast(
movie-id numeric references movies(id),
actor-id numeric references movie-Star(id),
role varchar(32),
primary key (movie-id, actor-id)
);
Create table Studio(
studio-id numeric references directors(id)
Directer-name varchar(20) not null
name varchar(20) primary key
);
create table directors(
id numeric primary key not null default autoincrement,
first-name varchar(32) not null,
last-name varchar(32) not null,
gender varchar(8),
dob Date,
biography varchar(1000)
);
It looks pretty well structured. I don't see any normalization problems. However:
Movies and Directors tables are created twice.
Genre table is not used for anything (presumably should be in movies).
Same with Studios.
Current arrangement allows only one director per studio. This should probably be A) one studio per director (add studio_id column to directors) or more likely B) many-to-many relationship between studio and director (add new studio_directors table).
Current arrangement does not associate Director with Movie.
You might consider combining Director and Movie-Start into one table called Talent. You have data duplication in which a star is also a director. This is the biggest normalization issue with your design.
if all can not be duplicated again then it is included 3NF.
make sure there are not duplicate data again
It has e PK, so it's in 1NF. It's PK is not composite, so it's in 2NF. All the columns are dependent on nothing but the key, so it's in 3NF. There no keys other than PK, so it's in BCNF.