SQL - is developing queries based on nonexistent data possible? - sql

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.

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));

Microsoft SQL Server Management Studio - Trying to add FK constraint, getting error: "Invalid column..."

I'm trying to add a foreign key constraint to link my tables, however I keep getting this error:
Msg 1769, Level 16, State 1, Line 1
Foreign key 'fk_customers_titles' references invalid column 'title_id' in referencing table 'customers'.
I've created my tables, along with it's columns and also stated my primary keys using the ALTER TABLE statement. But whenever I try to add a foreign key constraint for any table, I keep getting this error.
This is how I created my tables:
CREATE TABLE customers
(
customer_id char_idtype,
name varchar(50) NOT NULL,
contact_name varchar(30),
address varchar(50),
city varchar(20),
region varchar(15),
country_code varchar(10),
country varchar(15),
phone varchar(20),
fax varchar(20)
);
GO
CREATE TABLE titles
(
title_id char(3) NOT NULL,
description varchar(35) NOT NULL
);
GO
And this is how I added my primary keys:
ALTER TABLE customers
ADD PRIMARY KEY (customer_id);
GO
ALTER TABLE titles
ADD PRIMARY KEY (title_id);
GO
This is how I am adding my foreign key constraint:
ALTER TABLE customers
ADD CONSTRAINT fk_customers_titles
FOREIGN KEY (title_id)
REFERENCES titles(title_id);
I am using Microsoft SQL Server Management Studio 2012.
Your help is appreciated,
Thanks
I think the error is pretty clear: customers does not have a title_id. You need to add it . . .
ALTER TABLE customers ADD title_id char(3);
Or put it in the CREATE TABLE statement.
Your script should be like below mentioned.
CREATE TABLE titles
(
title_id char(3) Primary key NOT NULL,
description varchar(35) NOT NULL
);
GO
CREATE TABLE customers
(
customer_id char(3) primary key,
title_id char(3) foreign key references titles,
name varchar(50) NOT NULL,
contact_name varchar(30),
address varchar(50),
city varchar(20),
region varchar(15),
country_code varchar(10),
country varchar(15),
phone varchar(20),
fax varchar(20)
);
GO

how to create this table in sql server?

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")

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);

I cannot get this .sql file to run successfully in MySQL?

MySQL CMD Client will run this file but get half way through and complain my syntax is wrong i have looked over and changed bits in it all day but just cannot find the issue.
I know again its probably a very easily answered question but after looking at it all day its time for a fresh pair of eyes to have a look for me. Please help!
DROP DATABASE FIFAWC2010;
CREATE DATABASE FIFAWC2010;
USE FIFAWC2010;
CREATE TABLE VENUE(
VENUE_ID CHAR(3),
LOC_COORDS VARCHAR(50),
CITY VARCHAR(20),
VENUE_NAME VARCHAR(20),
MAX_CAPACITY NUMERIC(9),
PRIMARY KEY(VENUE_ID)
);
CREATE TABLE REFEREE(
REF_ID CHAR(10),
REF_FNAME VARCHAR(20),
REF_SNAME VARCHAR(20),
NATIONALITY VARCHAR(20),
PRIMARY KEY(REF_ID)
);
CREATE TABLE MATCH(
MATCH_ID CHAR(11),
VENUE_ID CHAR(3),
MATCH_DATE DATE,
KICK_OFF TIME,
FINAL_SCORE VARCHAR(7),
REF_ID CHAR(10),
VENUE_ATTEN NUMERIC(9),
PRIMARY KEY(MATCH_ID,VENUE_ID) REFERENCES VENUE(VENUE_ID),
);
CREAT TABLE GROUP(
GROUP_ID CHAR(1),
MATCH_ID VARCHAR(28),
PRIMARY KEY(GROUP_ID),
);
CREATE TABLE COUNTRY(
COUNTRY_ID VARCHAR(20),
GROUP_ID CHAR(1),
PRIMARY KEY(COUNTRY_ID),
);
CREATE TABLE PLAYER(
PLAYER_ID CHAR(10),
PLAYER_FNAME VARCHAR(20),
PLAYER_SNAME VARCHAR(20),
POSITION VARCHAR(10),
MATCH_ID CHAR(11),
COUNRTY_ID VARCHAR(20),
PRIMARY KEY(PLAYER_ID),
);
COMMIT;
Thank you! :) Ash.
UPDATE:
Sorry i pasted the wrong code, this is the code i am using and having issues with:
DROP DATABASE FIFAWC2010;
CREATE DATABASE FIFAWC2010;
USE FIFAWC2010;
CREATE TABLE VENUE(
VENUE_ID CHAR(3),
LOC_COORDS VARCHAR(50),
CITY VARCHAR(20),
VENUE_NAME VARCHAR(20),
MAX_CAPACITY NUMERIC(9),
PRIMARY KEY(VENUE_ID)
);
CREATE TABLE REFEREE(
REF_ID CHAR(10),
REF_FNAME VARCHAR(20),
REF_SNAME VARCHAR(20),
NATIONALITY VARCHAR(20),
PRIMARY KEY(REF_ID)
);
CREATE TABLE MATCH(
MATCH_ID CHAR(11),
VENUE_ID CHAR(3),
MATCH_DATE DATE,
KICK_OFF TIME,
FINAL_SCORE VARCHAR(7),
REF_ID CHAR(10),
VENUE_ATTEN NUMERIC(9),
PRIMARY KEY(MATCH_ID,VENUE_ID) REFERENCES VENUE(VENUE_ID),
FOREIGN KEY(REF_ID) REFERENCES REFEREE(REF_ID)
);
CREAT TABLE GROUP(
GROUP_ID CHAR(1),
MATCH_ID VARCHAR(28),
PRIMARY KEY(GROUP_ID),
FOREIGN KEY(MATCH_ID) REFERENCES MATCH(MATCH_ID)
);
CREATE TABLE COUNTRY(
COUNTRY_ID VARCHAR(20),
GROUP_ID CHAR(1),
PRIMARY KEY(COUNTRY_ID),
FOREIGN KEY(GROUP_ID) REFERENCES GROUP(GROUP_ID)
);
CREATE TABLE PLAYER(
PLAYER_ID CHAR(10),
PLAYER_FNAME VARCHAR(20),
PLAYER_SNAME VARCHAR(20),
POSITION VARCHAR(10),
MATCH_ID CHAR(11),
COUNRTY_ID VARCHAR(20),
PRIMARY KEY(PLAYER_ID),
FOREIGN KEY(COUNTRY_ID) REFERENCES COUNTRY(COUNTRY_ID),
FOREIGN KEY(MATCH_ID) REFERENCES MATCH(MATCH_ID)
);
COMMIT;
I get Error 1064 (42000) 4 times, and its on MATCH, GROUP, (MATCH_ID), (GROUP_ID).
Is this a syntax error with the Primary keys?
My guess : having a , on the last line of a list... like this one:
PRIMARY KEY(MATCH_ID,VENUE_ID) REFERENCES VENUE(VENUE_ID),
change to
PRIMARY KEY(MATCH_ID,VENUE_ID) REFERENCES VENUE(VENUE_ID)
you have 4 of them.
I have managed to fix the error my self, it would seem that MATCH and GROUP are actually keywords that MySQL / SQL uses and cannot be used as the names of my tables, I installed MySQL WorkBench and it will underline errors for you.
Also to create a composite key with a Foreign Key, you first create the variable for the data to sit in, use the foreign key syntax to get the data into the variable, then use the usual syntax for a composite key with the Foreign Key variable in place.
Thank you everyone for your help!
Ash.