Correct SQL Create Table Statement? - sql
I've been stuck on this final table/data dictionary that I'm working on and I'm not quite sure on the syntax of the create table statement.
Data Dictionary:
TABLE NAME: Enrollment
Sid (Column Name)
NUMBER(Data Type)
5(Length)
blank(not null)
Y(PK)
Y(FK)
Blank(Check)
Csecid(Column Name)
NUMBER(Data Type)
8(Length)
blank(not null)
Y(PK)
Y(FK)
Blank(Check)
Grade(Column Name)
CHAR(Data Type)
1(Length)
blank(not null)
Blank(PK)
Blank(FK)
A,B,D,D,F,I,W(Checks).
Notes:
Sid is also defined as the PK on the STUDENT table.
Csecid is also defined as the PK on the COURSE_SECTION table.
I don't know how to define both Sid and Csecid in the Create table statement as both PK and FK. Please help. Thanks!
In my understanding you need to create a mapping table Enrollment for tables Student and Course_Section, because Student and Course_Section have many-to-many relationship.
Following lists the sample schema and create table queries:
-- Create Student Table
create table student(sid number(5) primary key, sname varchar2(100),
dob date);
-- Insert some data
insert into student values(1,'student1','01-feb-1990');
insert into student values(2,'student2','01-mar-1990');
insert into student values(3,'student3','01-apr-1990');
insert into student values(4,'student4','01-may-1990');
commit;
-- Create Course_Section Table
create table course_section(csecid number(8) primary key,
csname varchar2(30));
-- Insert some data
insert into course_section values(115,'CS1');
insert into course_section values(116,'CS2');
insert into course_section values(117,'CS3');
insert into course_section values(118,'CS4');
insert into course_section values(119,'CS5');
commit;
-- Since student and course_section have many-to-many relationship
-- One student can enroll to many courses
-- One course can be associated with many students
-- They need to be related using separate table
create table enrollment(sid number(5) not null,
csecid number(8) not null,
grade char(1) not null,
constraint e_pk primary key(sid, csecid),
foreign key (sid) references student(sid),
foreign key (csecid) references course_section(csecid),
constraint gc_constraint check (grade in ('A','B','C','D','F','I','W')));
-- Insert some records in enrollment
insert into enrollment values(1,115,'D');
insert into enrollment values(2,118,'C');
insert into enrollment values(1,118,'C');
insert into enrollment values(2,117,'A');
insert into enrollment values(4,116,'B');
insert into enrollment values(3,118,'I');
insert into enrollment values(4,118,'W');
commit;
Check this sqlfiddle to know more.
Related
How do you insert information in a table if you have a unary relationship
create table Employee( staff_id_employee int primary key , gender char(1) check (gender in('F','M')), staff_id int foreign key REFERENCES Staff(staff_id), manager_id int foreign key references Employee(staff_id_employee) ); How do I insert the information in this table.The text to this is that an employee manages other employees.If anyone could give me some sort of example cuz I don't know what to write instead of the question marks '????'.WHat is the value to manager_id in this case INSERT into Employee(staff_id_employee, gender, staff_id, manager_id) VALUES (30000,'F',6007,????)
If you need to look-up the manager's Id then you want an insert select INSERT into Employee(staff_id_employee, gender, staff_id, manager_id) SELECT 30000,'F',6007, staff_id_employee from Employee where staff_id = [Manager's staff ID]
If Employee 3000 doesn't have a manager, you would typically insert a null INSERT into Employee(staff_id_employee, gender, staff_id, manager_id) VALUES (30000,'F',6007, null) Otherwise insert the manager's ID.
Print multiple rows in some order as different columns
/* Note: on update/delete, no action (restriction) is the default. (SQL Server & Oracle) */ CREATE TABLE Faculty ( FacNo CHAR(11) NOT NULL, FacFirstName VARCHAR(30) NOT NULL, FacLastName VARCHAR(30) NOT NULL, FacCity VARCHAR(30) NOT NULL, FacState CHAR(2) NOT NULL, FacDept CHAR(6) NULL, FacRank CHAR(4) NULL, FacSalary DECIMAL(10,2) NULL, FacSupervisor CHAR(11) NULL, FacHireDate DATETIME NULL, FacZipCode CHAR(10) NOT NULL, CONSTRAINT FacultyPK PRIMARY KEY (FacNo), CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty ) go /* Note: on update cascade for FacSupervisor caused the following error in SQL Server 2004: Introducing FOREIGN KEY CONSTRAINT 'SupervisorFK' on table 'Faculty' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY CONSTRAINTs. */ CREATE TABLE Course ( CourseNo CHAR(6) NOT NULL, CrsDesc VARCHAR(50) NOT NULL, CrsUnits INTEGER NULL, CONSTRAINT CoursePK PRIMARY KEY (CourseNo) ) go CREATE TABLE Offering ( OfferNo INTEGER NOT NULL, CourseNo CHAR(6) NOT NULL, OffTerm CHAR(6) NOT NULL, OffYear INTEGER NOT NULL, OffLocation VARCHAR(30) NULL, OffTime VARCHAR(10) NULL, FacNo CHAR(11) NULL, OffDays CHAR(4) NULL, CONSTRAINT OfferingPK PRIMARY KEY (OfferNo), CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course, CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty ) go CREATE TABLE Student ( StdNo CHAR(11) NOT NULL, StdFirstName VARCHAR(30) NOT NULL, StdLastName VARCHAR(30) NOT NULL, StdCity VARCHAR(30) NOT NULL, StdState CHAR(2) NOT NULL, StdZip CHAR(10) NOT NULL, StdMajor CHAR(6) NULL, StdClass CHAR(2) NULL, StdGPA DECIMAL(3,2) NULL, CONSTRAINT StudentPk PRIMARY KEY (StdNo) ) go CREATE TABLE Enrollment ( OfferNo INTEGER NOT NULL, StdNo CHAR(11) NOT NULL, EnrGrade DECIMAL(3,2) NULL, CONSTRAINT EnrollmentPK PRIMARY KEY (OfferNo, StdNo), CONSTRAINT OfferingFK FOREIGN KEY (OfferNo) REFERENCES Offering ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT StudentFK FOREIGN KEY (StdNo) REFERENCES Student ON DELETE CASCADE ON UPDATE CASCADE ) go INSERT INTO Faculty VALUES ('543210987','VICTORIA','EMMANUEL','BOTHELL','WA','MS','PROF',120000.00,NULL,'4/15/2005','98011-2242') go INSERT INTO Faculty VALUES ('765432109','NICKI','MACON','BELLEVUE','WA','FIN','PROF',65000.00,NULL,'4/11/2006','98015-9945') go INSERT INTO Faculty VALUES ('654321098','LEONARD','FIBON','SEATTLE','WA','MS','ASSC',70000.00,'543210987','5/1/2003','98121-0094') go INSERT INTO Faculty VALUES ('098765432','LEONARD','VINCE','SEATTLE','WA','MS','ASST',35000.00,'654321098','4/10/2004','98111-9921') go INSERT INTO Faculty VALUES ('876543210','CRISTOPHER','COLAN','SEATTLE','WA','MS','ASST',40000.00,'654321098','3/1/2008','98114-1332') go INSERT INTO Faculty VALUES ('987654321','JULIA','MILLS','SEATTLE','WA','FIN','ASSC',75000.00,'765432109','3/15/2009','98114-9954') go INSERT INTO Course VALUES ('FIN300','FUNDAMENTALS OF FINANCE',4) go INSERT INTO Course VALUES ('FIN450','PRINCIPLES OF INVESTMENTS',4) go INSERT INTO Course VALUES ('FIN480','CORPORATE FINANCE',4) go INSERT INTO Course VALUES ('IS320','FUNDAMENTALS OF BUSINESS PROGRAMMING',4) go INSERT INTO Course VALUES ('IS460','SYSTEMS ANALYSIS',4) go INSERT INTO Course VALUES ('IS470','BUSINESS DATA COMMUNICATIONS',4) go INSERT INTO Course VALUES ('IS480','FUNDAMENTALS OF DATABASE MANAGEMENT',4) go INSERT INTO Offering VALUES (1111,'IS320','SUMMER',2017,'BLM302','10:30:00',NULL,'MW') go INSERT INTO Offering VALUES (1234,'IS320','FALL',2016,'BLM302','10:30:00','098765432','MW') go INSERT INTO Offering VALUES (2222,'IS460','SUMMER',2016,'BLM412','13:30:00',NULL,'TTH') go INSERT INTO Offering VALUES (3333,'IS320','SPRING',2017,'BLM214','8:30:00','098765432','MW') go INSERT INTO Offering VALUES (4321,'IS320','FALL',2016,'BLM214','15:30:00','098765432','TTH') go INSERT INTO Offering VALUES (4444,'IS320','WINTER',2017,'BLM302','15:30:00','543210987','TTH') go INSERT INTO Offering VALUES (5555,'FIN300','WINTER',2017,'BLM207','8:30:00','765432109','MW') go INSERT INTO Offering VALUES (5678,'IS480','WINTER',2017,'BLM302','10:30:00','987654321','MW') go INSERT INTO Offering VALUES (5679,'IS480','SPRING',2017,'BLM412','15:30:00','876543210','TTH') go INSERT INTO Offering VALUES (6666,'FIN450','WINTER',2017,'BLM212','10:30:00','987654321','TTH') go INSERT INTO Offering VALUES (7777,'FIN480','SPRING',2017,'BLM305','13:30:00','765432109','MW') go INSERT INTO Offering VALUES (8888,'IS320','SUMMER',2017,'BLM405','13:30:00','654321098','MW') go INSERT INTO Offering VALUES (9876,'IS460','SPRING',2017,'BLM307','13:30:00','654321098','TTH') go INSERT INTO Student VALUES ('123456789','HOMER','WELLS','SEATTLE','WA','98121-1111','IS','FR',3.00) go INSERT INTO Student VALUES ('124567890','BOB','NORBERT','BOTHELL','WA','98011-2121','FIN','JR',2.70) go INSERT INTO Student VALUES ('234567890','CANDY','KENDALL','TACOMA','WA','99042-3321','ACCT','JR',3.50) go INSERT INTO Student VALUES ('345678901','WALLY','KENDALL','SEATTLE','WA','98123-1141','IS','SR',2.80) go INSERT INTO Student VALUES ('456789012','JOE','ESTRADA','SEATTLE','WA','98121-2333','FIN','SR',3.20) go INSERT INTO Student VALUES ('567890123','MARIAH','DODGE','SEATTLE','WA','98114-0021','IS','JR',3.60) go INSERT INTO Student VALUES ('678901234','TESS','DODGE','REDMOND','WA','98116-2344','ACCT','SO',3.30) go INSERT INTO Student VALUES ('789012345','ROBERTO','MORALES','SEATTLE','WA','98121-2212','FIN','JR',2.50) go INSERT INTO Student VALUES ('876543210','CRISTOPHER','COLAN','SEATTLE','WA','98114-1332','IS','SR',4.00) go INSERT INTO Student VALUES ('890123456','LUKE','BRAZZI','SEATTLE','WA','98116-0021','IS','SR',2.20) go INSERT INTO Student VALUES ('901234567','WILLIAM','PILGRIM','BOTHELL','WA','98113-1885','IS','SO',3.80) go INSERT INTO Enrollment VALUES (1234,'123456789',3.30) go INSERT INTO Enrollment VALUES (1234,'234567890',3.50) go INSERT INTO Enrollment VALUES (1234,'345678901',3.20) go INSERT INTO Enrollment VALUES (1234,'456789012',3.10) go INSERT INTO Enrollment VALUES (1234,'567890123',3.80) go INSERT INTO Enrollment VALUES (1234,'678901234',3.40) go INSERT INTO Enrollment VALUES (4321,'123456789',3.50) go INSERT INTO Enrollment VALUES (4321,'124567890',3.20) go INSERT INTO Enrollment VALUES (4321,'789012345',3.50) go INSERT INTO Enrollment VALUES (4321,'876543210',3.10) go INSERT INTO Enrollment VALUES (4321,'890123456',3.40) go INSERT INTO Enrollment VALUES (4321,'901234567',3.10) go INSERT INTO Enrollment VALUES (5555,'123456789',3.20) go INSERT INTO Enrollment VALUES (5555,'124567890',2.70) go INSERT INTO Enrollment VALUES (5678,'123456789',3.20) go INSERT INTO Enrollment VALUES (5678,'234567890',2.80) go INSERT INTO Enrollment VALUES (5678,'345678901',3.30) go INSERT INTO Enrollment VALUES (5678,'456789012',3.40) go INSERT INTO Enrollment VALUES (5678,'567890123',2.60) go INSERT INTO Enrollment VALUES (5679,'123456789',2.00) go INSERT INTO Enrollment VALUES (5679,'124567890',3.70) go INSERT INTO Enrollment VALUES (5679,'678901234',3.30) go INSERT INTO Enrollment VALUES (5679,'789012345',3.80) go INSERT INTO Enrollment VALUES (5679,'890123456',2.90) go INSERT INTO Enrollment VALUES (5679,'901234567',3.10) go INSERT INTO Enrollment VALUES (6666,'234567890',3.10) go INSERT INTO Enrollment VALUES (6666,'567890123',3.60) go INSERT INTO Enrollment VALUES (7777,'876543210',3.40) go INSERT INTO Enrollment VALUES (7777,'890123456',3.70) go INSERT INTO Enrollment VALUES (7777,'901234567',3.40) go INSERT INTO Enrollment VALUES (9876,'124567890',3.50) go INSERT INTO Enrollment VALUES (9876,'234567890',3.20) go INSERT INTO Enrollment VALUES (9876,'345678901',3.20) go INSERT INTO Enrollment VALUES (9876,'456789012',3.40) go INSERT INTO Enrollment VALUES (9876,'567890123',2.60) go INSERT INTO Enrollment VALUES (9876,'678901234',3.30) go INSERT INTO Enrollment VALUES (9876,'901234567',4.00) go Schema for example. Get all the faculty numbers (FacNo) and last names (FacLastName) of two different faculty who offered courses in the same offering year (OffYear). There must be no duplicates in the output. *Note: For instance, if both P1 Smith and P2 Peters offered courses in 2021, then [P1, Smith, P2, Peters] (or [P2, Peters, P1, Smith], but not both) must be selected. So, the output must look like this: FacNo FacLastName FacNo FacLastName ===== =========== ===== =========== P1 Smith P2 Peters ... ... ... ... ===== =========== ===== ===========* I am trying to do something like this and I can't even think where to start? How do I approach this problem? I tried something like this SELECT f1.FacNo, f1.FacLastName FROM Offering o1 INNER JOIN Faculty f1 on o1.FacNo = f1.FacNo INNER JOIN Offering o2 on o1.OffYear = o2.OffYear
You are on the right track. Joining the Offering table twice on the OffYear correctly gets you the combinations of courses in the same year. Since you want the names of the two faculty members, you also need to join the Faculty table twice: SELECT f1.FacNo, f1.FacLastName, f2.FacNo, f2.FacLastName FROM Offering o1 INNER JOIN Faculty f1 on o1.FacNo = f1.FacNo INNER JOIN Offering o2 on o2.OffYear = o1.Offyea INNER JOIN Faculty f2 on o2.FacNo = f2.FacNo This will however include exact duplicate rows (e.g. when two faculty members had two courses in the same year), combinations of faculty members with themselves and duplicate combinations of names in reverse order (both [P1, Smith, P2, Peters] and [P2, Peters, P1, Smith]). To get rid of the exact duplicates, use SELECT DISTINCT instead of SELECT. The other two problems can be easily fixed with one WHERE condition: By limiting results so that the first member's FacNo is smaller than the other's, unwanted combinations are filtered out. SELECT DISTINCT f1.FacNo, f1.FacLastName, f2.FacNo, f2.FacLastName FROM Offering o1 INNER JOIN Faculty f1 on o1.FacNo = f1.FacNo INNER JOIN Offering o2 on o2.OffYear = o1.Offyear INNER JOIN Faculty f2 on o2.FacNo = f2.FacNo WHERE f1.FacNo < f2.FacNo See this dB<>fiddle.
Same primary keys for relation
Lets say I have two many-to-many relations called Tutors and Assits. They are both connected courses. If they are both inheritance of relation called Staff they both have the same primary keys. That would mean the many-to-many relation will also have the same primary keys. If I have two relations with the same primary keys what do I do? Here is an example of the table:
It should be pretty simple to add those two relationships. For example: create table staff ( id int primary key not null, name varchar(20) ); create table tutor ( id int primary key not null, office_number varchar(10), foreign key (id) references staff (id) ); create table assistant ( id int primary key not null, title varchar(20), foreign key (id) references staff (id) ); create table course ( course_id int not null, year int not null, semester int not null, primary key (course_id, year, semester), tutor_id int not null references tutor (id), assistant_id int not null references assistant (id) ); Now, if you insert some data: insert into staff (id, name) values (1, 'Alice'); insert into staff (id, name) values (2, 'Victor'); insert into tutor (id, office_number) values (1, '101-A'); insert into assistant (id, title) values (2, 'Adjunct Professor'); insert into course (course_id, year, semester, tutor_id, assistant_id) values (101, 2020, 1, 1, 2); You can run a query over it: select c.course_id, c.year, c.semester, ts.name as tutor, t.office_number, ta.name as assistant, a.title from course c join tutor t on c.tutor_id = t.id join staff ts on ts.id = t.id join assistant a on c.assistant_id = a.id join staff ta on ta.id = a.id Result: course_id year semester tutor office_number assistant title ---------- ----- --------- ------ -------------- ---------- ----------------- 101 2020 1 Alice 101-A Victor Adjunct Professor See running example at DB Fiddle.
If the relation course - tutor is a many-to-many relation you will need an extra xref table: course -|---|< course_tutor >0---|- tutor The same thing for assistant. Even when the same person is tutor and assistant in the same course there will be a record in course_tutor and course_assistant with the same course_id and staff_id but that is not a problem.
Cross Referencing Table Value for Another Value to allow Insert
How do I look at one table and use it to check another table for data integrity? I have two SQL Tables. One that is a person table CREATE TABLE PERSON ( ID INT IDENTITY(10000,1) NOT NULL, Firstname VARCHAR(15), Lastname VARCHAR(25) NOT NULL, Birthdate DATE, Gender VARCHAR(1), CHECK ( GENDER IN ('M', 'F')), Street VARCHAR(50), City VARCHAR(15), State VARCHAR(2), CHECK (State IN ('FL','GA','PA')), Zip INT, Phone VARCHAR(10), Employee VARCHAR(1), CHECK ( Employee IN('Y','N')), Member VARCHAR(1), CHECK ( Member IN('Y','N')), CHECK (Member IN ('Y') or Employee IN ('Y')), CONSTRAINT PERSON_PK PRIMARY KEY (ID)); And Employee Table CREATE TABLE EMPLOYEE ( ID INT NOT NULL, Datehired DATE DEFAULT GETDATE(), Status VARCHAR(1), CHECK ( Status IN ('F','C')), Position VARCHAR(25), EmpType VARCHAR(25), CONSTRAINT EMPLOYEE_PK PRIMARY KEY (ID), CONSTRAINT EMPLOYEE_PERSON_FK FOREIGN KEY (ID) REFERENCES PERSON); Let's say someone isn't an employee. I can still insert them into the Employee Table. INSERT INTO EMPLOYEE (ID, Status, Position, EmpType) VALUES ('10000','C','Teaching Classes','Instructor'); How Do I prevent this from happening.
One method is to have a redundant key: alter table person contraint unq_person_id_employee unique (id, employee); Then add a computed column to employee: alter table employee add employee as ('Y') persisted; Finally, add the constraint: alter table employee add constraint fk_employee_person foreign key (id, employee) references person(id, employee); Now, you are guaranteed that only employees are in the Employee table.
Foreign Key Not Populating with Primary Key Values
I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-generated I assumed the FK in table 1 would populate with the value that is auto-generated from table 2 but it is not working. The FK in table 1 ends up null. Here is my SQL code for creating table 1: CREATE TABLE Employee_tbl ( EmployeeID int PRIMARY KEY IDENTITY, LastName varchar(20) not null, FirstName varchar(20) not null, Age varchar(3) not null, JobID int FOREIGN KEY REFERENCES JobTitle_tbl(JobID), ) and here is table 2: create table JobTitle_tbl( JobID int PRIMARY KEY IDENTITY, EEO1Classification varchar(50) not null, Exempt_nonexempt_status varchar(20) not null, ) I also have some insert statements: INSERT INTO Employee_tbl (LastName, FirstName, Age) Values ('Smith', 'John', '50'), ... and: INSERT into JobTitle_tbl (EEO1Classification, Job_title, ) VALUES ('Office/Clerical', 'Accounting Clerk', ), Why is the FK value showing null when I query table 1?
The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use ##identity if using sql server) select id from JobTitle_tbl where Job_title = '' Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first. SET IDENTITY_INSERT JobTitle_tbl ON into the JobTitle_tbl (id, title) values (1, 'Manager') SET IDENTITY_INSERT JobTitle_tbl OFF In either case, you'll need to then update your first insert statements with the ID that you have. insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)