Uploaded by Mirumi Mira

Cheat Sheet ICT330 Databases

advertisement
Cheat Sheet ICT330 Databases.
Q1
1.
2.
3.
4.
Identify entities and identifiers first!
Add on with their other details [DO NOT ADD PK/FK]
Draw with cardinality
Don’t forget the relationships
Reliable Tips?
Drivers Motors Services and Repairs owns several workshops which carry out vehicle
servicing and repair work. Each workshop is identified by a workshop code and has an address
and a contact number. A system is required to support the activities of the workshops.
Workshop(CODE, address,contact)
The company wishes to build a knowledge base consisting of online technical specifications
and repair and servicing notes for various vehicle designs, identified by a vehicle make, model
and edition year. Whenever a vehicle arrives at a workshop, mechanics identify the vehicle
design and check whether an entry for the design already exists in the knowledge base. If it
exists, new insights gained are added as repair or servicing notes. If there is no match, a new
entry is first made for the vehicle design. The date of entry creation, date of each note added,
a note description as well as the mechanic who adds the note are captured.
Note(MAKE,MODEL,EDITIONYEAR,DATETIMEADDED,notedescription)
VehicleDesign(MAKE,MODEL,EDITIONYEAR,datecreated,techSpecs)
The company provides several service packages. Each service package is identified by a
service package name, the cost of the package and a list of service items. Some service items
may be offered in more than one service packages e.g., change engine oil with synthetic oil.
A service item is identified by service item code and has a name and a description.
ServicePackage(PACKAGENAME,cost)
ServiceItem(SERVICEITEMCODE,name,desc,cost)
A vehicle visit to a workshop is identified by the vehicle registration number and time of visit.
Each visit may include vehicle servicing with a service package or without a package, in which
case, individually priced service items can be selected. A customer may also select a service
package and then add on more individually priced service items.
VehicleVisit(REGNUMBER,DATETIMEIN,datetimeout,mileage)
ServiceItemAdded(REGNUM,DATEVISIT,SERVICEITEMCODE,cost)
Vehicle(REGNUM,engineNum,chassisNum)
A visit may also include one or more vehicle repair items. When a visit includes repair items,
an overall repair labour cost is included to the total cost of the visit. A repair item is identified
by a running number which is unique to a vehicle visit. A repair item has a description and a
cost which is the total cost of parts used for the repair item. The unit cost of parts and quantity
of parts used for a repair item should be itemised in the customer bill. Each part is identified
by a part code. Each part has a name, description and a unit cost. The charges incurred for a
visit therefore, may include cost of a service package, cost of individually priced service items,
cost of labour for repair work and cost and quantity of parts used in repair items, each itemised
for billing and accounting purposes.
RepairItem(REGNUMBER,DATETTIMEIN,RUNNINGNUMBER,desc)
PartUsed(REGNUMBER,DATETIMEIN,RUNNINGNUMBER,PARTCODE,unitcost,qty)
Part(PARTCODE,name,desc,unitCost)
VehicleVisitWithService(packageCost)
VehicleVisitWithRepair(labourCost)
A team of mechanics, each identified by the team number is assigned to handle all servicing and
repair works for a vehicle visit. A team is headed by a senior mechanic and consists of 2
or more other mechanics, all of whom are attached to the same workshop. When a mechanic
transfers to a new workshop, he joins a new team. Each mechanic is identified by a staff
number, and is described by a name, date joined, and the dates he joins and leaves a team,
where applicable. It is also necessary to record the headship of a team, that is, the date a senior
mechanic starts to head a team and the date on which he steps down as head.
Team(TEAMNUMBER)
HeadAssignment(TEAMNUMBER,STARTDATE,enddate)
Mechanic(STAFFNUM,name,dateJoined,positionType)
TeamAssignment(STAFFNUM,STAFFSTART,dateEnd)
The system should record customer details such as customer name and contact and vehicle
details such as make, model, edition, vehicle registration number, engine number and chassis
number. Other details include the vehicle condition at time of visit (e.g., locations of dents and
scratches), the mileage, the date and time the vehicle is handed over to the workshop and the
date and time the vehicle is returned.
VehicleCondition(REGNUM,DATETIMEIN,RUNNINGNUM,desc)
Customer(CONTACT,name)
Q2
1. Identify using simple relationships, such as IDs.
Subsumed?
Lets say:
1. AttributeA  AttributeB
2. AttributeC, AttributeD  AttributeA
2 subsumed into 1.Why? Because the right hand side, is present as a left-hand side.
2. Relate and draw the dependency graph
3. Get the candidate keys
4. Start doing the BCF.
BCNF Tips/Tricks:
1. Start from the bottom most from the dependency graph.
2. Consider if it is a  Dependency
Id  Name, Info
= TableName(Id, name, info)
= TableName(Id[PK], name, info)
 The PK stays at the original Table, but becomes a FK.
 The rest are “moved” from the original table (Meaning to say, if the original record is a
FK or PK, you move the entirely of the record over, with the FK/PK)
3. Consider if it is a  Dependency
Id Name
= TableName(Id(FK), Name)
 The main value becomes the FK in the table. The original’s becomes the PK
 The rest are “moved” from the original table (Meaning to say, if the original record is a
FK or PK, you move the entirely of the record over, with the FK/PK)
4. Perform explanations
 For  Tables:
o Every determinant in VehManufacturer(vehicleMake(PK), countryEstablished,
yearEstablished) is a candidate key and thus, VehManufacturer is in BCNF.


For  Tables:
o Every determinant in PartNeeded(problemCode(FK), componentCode) is a candidate
key and so, PartNeeded is in BCNF. The only attributes in PartNeeded are also those in
the multivalued dependency and so PartNeeded is in 4NF.
For ongoing translation tables:
o
However, not every determinant of RepairWork_4 (vehicleRegNumber(FK),
dateRepair ,problemCode, problemCategory, componentCode, problemStatus)
is a candidate key.
o Process shall be continued.
5. Finally, list out the final tables.
General Idea is FKs don’t exist in current table, so they need to exist in their own tables first.
PKs are generally all good, since they are in the same table.
a. For PK relationships.
 ModelList (vehicleModel (PK), vehicleMake (FK))
where ModelList.vehicleMake must exist in VehManufacturer.vehMake

Vehicle(vehicleRegNumber(PK), vehicleModel(FK))
where Vehicle.vehicleModel must exist in ModelList.vehicleModel
b. For FK relationships
•
RepairWork_7(vehicleRegNumber(PK1.1/FK),dateRepair(PK1.2)
,problemCode(PK1.3/FK), problemStatus) where RepairWork_7.vehicleRegNumber must exist in
Vehicle.vehicleRegNumber and RepairWork_7.problemCode must exist in ProblemList.problemCode
Q3
1. Convert the Diagram into Logical Diagram
*Most of the time, the many side is where the FK is.
MUST DRAW DIAGRAM.
2. Identify the PK and FKs
3. Create Tables with constraints.
If field requirement indicates an exact, use CHAR().
If no exact, use VARCHAR().
Didn’t see before but, if only date, can use date.
No need to use datetime.
Delete/Update Cascade is easy.
If Cascade is allowed…
ON UPDATE CASCADE
ON DELETE CASCADE
If either one is not?
ON UPDATE NO ACTION
OR
ON DELETE NO ACTION
4. Start hoping the best for the SQL.
Commonly used SQL fragments:
Create View:
CREATE VIEW getClaimsPrevYear
AS
SELECT Dependent.staffNumber, Dependent.childBirthOrder
FROM Dependent
LEFT JOIN Claim c1 ON Dependent.staffNumber = c1.staffNumber and Dependent.childBirthOrder
= c1.childBirthOrder
WHERE YEAR(c1.dateOfClaim) = YEAR(GETDATE()) - 1
GROUP BY Dependent.staffNumber, Dependent.childBirthOrder
Create Trigger:
CREATE TRIGGER verifyBooking
ON Meeting
FOR INSERT, UPDATE
AS
BEGIN
DECLARE
@venueRoom int,
@venueBuilding char(1),
@bookDateTime datetime,
@meetingDuration int,
@meetingEndTime datetime,
@deptName char(20),
@currMtg datetime
SELECT
@meetingDuration = inserted.duration,
@bookDateTime = inserted.datetimeMeeting,
@deptName = inserted.department,
@venueRoom = inserted.RoomNumber,
@venueBuilding = inserted.BuildingName
FROM inserted
SET @meetingEndTime = DATEADD(hh,@meetingDuration,@bookDateTime)
IF exists
(
SELECT TOP 1 mt.datetimeMeeting from Meeting mt
WHERE mt.department = @deptName and (@bookDateTime BETWEEN
mt.datetimeMeeting and DATEADD(hh,mt.duration,mt.datetimeMeeting)
or @meetingEndTime BETWEEN mt.datetimeMeeting and
DATEADD(hh,mt.duration,mt.datetimeMeeting))
)
BEGIN
ROLLBACK
RAISERROR('Department has already a meeting at the same time frame.',16,1)
END
ELSE IF exists
(
SELECT TOP 1 * FROM Venue v
LEFT JOIN Meeting mt ON v.BuildingName = mt.BuildingName and
v.RoomNumber = mt.RoomNumber
WHERE @venueRoom = v.RoomNumber and @venueBuilding = v.BuildingName
and (@bookDateTime BETWEEN mt.datetimeMeeting and
DATEADD(hh,mt.duration,mt.datetimeMeeting)
or @meetingEndTime BETWEEN mt.datetimeMeeting and
DATEADD(hh,mt.duration,mt.datetimeMeeting))
)
BEGIN
ROLLBACK
RAISERROR('Venue has already a meeting at the same time frame.',16,1)
END
ELSE
BEGIN
PRINT 'Booking saved/updated'
END
END
Q4
1. Isolation Levels / Locks
Locks:
Lost Update: https://sqlskull.com/2021/06/27/lost-update-problem-in-concurrenttransations/
2. Permissions
Make sure to mention to the detailed level of which column and which row.
Eg: Allowed on UPDATE on Table1 on Status Column.
3. Checkpoint/Failure
State
Not committed at crash
Rollback before crash
Rollback after checkpoint
Rollback before checkpoint
Commit after Checkpoint
Commit before Checkpoint
Commit before Crash
Explanations
Apply before image and
rollback. Need to restart
transaction.
Roll backwards using reverse
pointer and apply before
image. Don’t restart.
Roll backwards using reverse
pointer and apply before
image.
Nothing needed to be done.
Roll forward using forward
pointer and apply after image.
Roll forward is to be done for
each database operations
after the last checkpoint.
Nothing needed to be done.
Roll forward using forward
pointer and apply after image.
ACID
Restarting ensures
Atomicity
Can ensure durability
through rolling
backwards from end of
Transaction past
checkpoint to beginning
of transaction.
N.A?
Can ensure durability
through roll forward
after checkpoint to end
of transaction.
4. ACID Properties
Download