database assignment 2
database assignment 2
Exercise 14
Show all employees working at location - Dallas. Run and Save your query as simplejoin2.sql
#Query
SELECT e.empno, e.ename, e.job, e.sal, e.deptno
FROM emp e
JOIN dept d ON e.deptno = d.deptno
WHERE d.loc = 'DALLAS';
Query Output
Exercise 18
Select all employees that have no commission. You will need to use IS NULL function. Run and
Save this query as Isnull1.
#Query
SELECT empno, ename, job, sal, comm
FROM emp
WHERE comm IS NULL;
Query Output
Exercise 29
Show the following details for all employees who earns a salary greater than the average for
their department:
#Query
SELECT e.empno, e.ename, e.job, e.sal, e.deptno
FROM emp e
JOIN dept d ON e.deptno = d.deptno
WHERE e.sal > (
SELECT AVG(sal)
FROM emp
WHERE deptno = e.deptno
)
ORDER BY e.deptno;
Query Output
Exercise 35
List lowest paid employees working for each manager. Exclude any groups where the salary is
less than 1000. Sort the output by salary. Use Group By and Having here.
#Query
SELECT e.mgr, e.empno, e.ename, e.job, e.sal
FROM emp e
WHERE e.sal >= 1000
GROUP BY e.mgr, e.empno, e.ename, e.job, e.sal
HAVING e.sal = (
SELECT MIN(sal)
FROM emp
WHERE mgr = e.mgr
)
ORDER BY e.sal;
Query Output
Exercise 36
List all employees by name and number along with their manager's name and number. This is a
self-join statement. This statement is most often used on a table with a recursive relationship, as
in this case study – Emp table. Run and Save it as selfjoin.sql
#Query
SELECT e.empno, e.ename, e.job, e.mgr, m.empno AS mgr_empno, m.ename AS mgr_name
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
ORDER BY e.empno;
Query Output
Exercise 40
Find any jobs that were filled in the first half of 1983 and were also filled during the same period
1984. Save your query as union2.sql
#Query
SELECT job
FROM emp
WHERE hiredate BETWEEN '1983-01-01' AND '1983-06-30'
INTERSECT
SELECT job
FROM emp
WHERE hiredate BETWEEN '1984-01-01' AND '1984-06-30';
Query Output
2. PLSQL - Trigger Tasks
Complete Exercises 3 and 4 from the PLSQL – TRIGGERS Workbook. Ensure you test
it appropriately and provide a discussion on value of each trigger and how the testing you have
used ensures a full testing strategy.
You can create a trigger to make sure that a value a user enters in a column corresponds an
existing value in another table’s column. Make sure you are saving your code, call it FK trigger.
First we will drop (in case you already have this table), than create a temp_emp table,
using SQL statements in SQL command.
To check the data in the new table tmpemp, write an SQL statement
The trigger is working. It has “fired” and prevented you from entering wrong data in the
tmpemp table. The following message will inform you that deptno 50 does not exist in
the dept table
Lesson learned here is that you have to create your trigger(s) before you insert any data
in the table. You could repeat this task, so that deptno 50 is never allowed in the tmp
table. How would you do this?
Once bad data is in the table, the trigger will not retroactively remove it. This is why triggers shouldbe
created before any data insertion.
ename TEXT,
job TEXT,
mgr INTEGER,
hiredate TEXT,
sal REAL,
comm REAL,
deptno INTEGER
);
BEGIN
SELECT CASE
END;
END;
-- This will fail because deptno = 50 does NOT exist in the dept table
Clear all bad data from the tmpemp table before pressing the trigger.
From now on, make sure you only enter valid data.
DELETE FROM tmpemp WHERE deptno NOT IN (SELECT deptno FROM dept);
BEGIN
SELECT CASE
END;
END;
SELECT CASE
END;
END;
Problem
Check Constraint Triggers can enforce integrity rules other than referential integrity. For
example, this trigger performs a complex check before allowing the triggering statement to
execute. Comments within the code explain the functionality of the trigger.
You are in charge here. How would you run and test this code? What does the code do? Include
your own comments in the code. Could you use this code in your Assignment?
Trigger Code:
Trigger Added
Test Code:
Now try to insert or update a salary for job CLERK to have a value of 4000.
Exercise: Complex Security Authorisations
Triggers are commonly used to enforce complex security authorisations for table data. Only use
triggers to enforce complex security authorisations that cannot be defined using the database
security features provided with ORACLE. For example, a trigger can prohibit updates to salary
data of the EMP table during weekends, holidays, and non-working hours.
When using a trigger to enforce a complex security authorisation, it is best to use a BEFORE
statement trigger. Using a BEFORE statement trigger has these benefits:
The security check is done before the triggering statement is allowed to execute so that
no wasted work is done by an unauthorised statement.
The security check is performed only once for the triggering statement, not for each row
affected by the triggering statement.
Type in the following code, run it and test the trigger. Create an INSERT OR DELETE OR
UPDATE statement to test your trigger code.
Create table company holidays with a column date. E.g. CREATE TABLE
COMPANY_HOLIDAYS (DAY DATE);
Insert one row of data with date that is today’s date. E.G INSERT INTO
COMPANY_HOLIDAYS VALUES ('12/11/21');
Company Holidays Table: We created the company_holidays table to store restricted dates for
updates.
Trigger logic: The trigger ensures that updating the emp table outside of holidays, weekends,
and business hours is prohibited.
Testing: We tested the trigger using the INSERT, UPDATE, and DELETE statements to verify that
the logic worked as expected.
Interactive Report functionality allows users to filter employees by job type (such as CLERK, MANAGER,
or SALESMAN) and sort them by salary. This allows users to be flexible in searching for employee data,
making it easier to spot trends and trends. The ability to organize and filter data in real time enhances
the user experience by allowing viewing of customized employee data based on specific needs or criteria
Additionally, the application includes dynamic Bar and Pie Charts for effectively visualizing employee
accounts. The bar chart represents the breakdown of salaries for each department, providing users with
quick overview of the distribution of salaries across departments. However, a pie chart shows the
number of employees in each occupation, allowing the employee structure to be visualized. Both charts
are interactive, allowing users to filter the data and update the visualization based on their selection,
increasing application usability and providing a clear visualization of the data, a graphic image
In summary, this application efficiently integrates multiple functions in a user-friendly web platform. It
provides powerful tools for managing and visualizing employee data, providing dynamic filtering, sorting
and graphical representation. The integration of master detail forms, interactive reports and charts
ensures that users can easily analyze and interpret complex data, thereby improving decision-making
and overall user engagement involvement is effective The design is flexible and practical, allowing
devices to be accessible and easy to use.
2)
Using the tables created in Assignment 1 select 4-6 related tables for this
assignment. Review these carefully and consider all types of declarative
constraints for those tables and data. Create a view based on your table(s) and
write a code to test it. Use SQL Scripts Environment for the whole task.
[10 Marks]
Task Create a View Using 4-6 Related Tables from Assignment
1
To complete this task, we will follow the steps needed to create a view and test it
with SQL scripts. The view will be created by selecting relevant data from the
Assignment 1 through 6 tables We will also demonstrate how to add declarative
constraints to the view and test the functionality
Step 1: Selected Tables
Cr Cri Cri Cri Cri Crim Offi Offi Depa Suspect Suspect Offe Date
im me_ me me me e_L cer cer rtme _Status _Histor nse_ _of_
e_ Na _Ty _St _Da ocat _Na _Ra nt_N y Hist Arre
ID me pe atu te ion me nk ame ory st
s Date
_of_
Arre
st
C0 Rob Pri Ope 202 Leed Dav Con Cyber Unde 5 Theft 2024
01 bery mar n 4- s e sta crime r Yea , -10-
y 10- Smi ble Cust rs Robb 23
20 th ody ery
Output:
No rows returned
Crime_Status
Open
Close
Summary
View Name: Crime_Case_View
Joint Table: Crime, Location, Officer, Department, Suspect, Perpetrator
Purpose: Provides an overview of crime, including officer, suspect, and
criminal profiles.
Restriction: Only offenses that occur after 2023, with Open/Closed status,
are included.
This approach improves data analysis and allows for more flexible reporting of
criminal cases.
3)
Produce a Database Application, Reports, to include four Apex Reports. Your
SQL statements used to build Apex Reports should be of an intermediate and
advanced level.
[10 Marks]
Output:
SELECT
c.Crime_ID,
c.Crime_Name,
c.Status,
COALESCE(sc.Solve_Date, 'Pending') AS Solve_Date,
COALESCE(sc.Penalty, 'None') AS Penalty,
o.Name AS Solved_By_Officer
FROM
Crime c
LEFT JOIN Solved_Crime sc ON c.Crime_ID = sc.Solved_CrimeID
LEFT JOIN Officer o ON sc.Solved_CrimeID = o.OfficerID
ORDER BY
sc.Solve_Date DESC;
Report 3: Criminal Activity Report
Objective: Record an offender’s risk level, offense rate, and date of most recent arrest.
Complex SQL: COUNT, MAX, GROUP BY, DATE functions
SELECT
cr.Criminal_ID,
cr.Risk_Level,
COUNT(c.Crime_ID) AS Number_of_Offenses,
MAX(cr.Date_of_Arrest) AS Latest_Arrest
FROM
Criminal cr
JOIN Crime c ON cr.Criminal_ID = c.Crime_ID
GROUP BY
cr.Criminal_ID, cr.Risk_Level
ORDER BY
Latest_Arrest DESC;
UNION
SELECT
c.Crime_ID,
c.Crime_Name,
'Witness' AS Role,
w.Witness_ID AS Person_ID,
w.Statement AS Role_Details
FROM
Crime c
JOIN Witness w ON c.Crime_ID = w.Witness_ID
ORDER BY
c.Crime_ID, Role;
Summary of Reports
4)
BEGIN
END IF;
RAISE(ABORT, 'Cannot update salary outside working hours (9:00 AM - 6:00 PM).');
END IF;
END;
Testing Trigger 1
UPDATE Officer
SET salary = 6000
UPDATE Officer
UPDATE Officer
Purpose: Ensure that any Officer_ID assigned to a crime in the Crime table must exist in the Officer
table.
Tables Used: Crime, Officer
BEGIN
RAISE(ABORT, 'Invalid OfficerID. This Officer does not exist in the Officer table.');
END IF;
END;
Testing Trigger 2
-- Try to insert a crime with an OfficerID that does not exist in the Officer table
UPDATE Crime
Summary of Triggers
Evidence of Testing
Summary
This project included creating and testing two trigger systems to ensure data consistency and application
of business rules to the database. The first trigger, Prevent_Salary_Update, prevents salary updates for
police officers on weekends and after working hours (before 9:00 am and after 6:00 pm). This ensures
that payroll information is updated only during standard business hours, increasing control and security
on critical payroll adjustments. The trigger was tested by attempting to update police pay during
restricted hours, resulting in an error message, while the update worked fine during business hours
The second trigger, Enforce_FK_Officer, ensures that every OfficerID used in the Crime table is in the
Officer table. This maintains referential integrity between officer and crime tables, and ensures that no
unregistered officer can link it to a crime. Tests of this trigger include inserting the OfficerID into the
Crime table and updating it along with valid and invalid IDs. If an incorrect ID was used, the system
raised an error message, while valid input and update operations completed successfully.
These barriers ensure data integrity, accuracy, and security. They demonstrate the real-world business
sense needed to ensure that updates are made only when appropriate and that relationships between
tables remain valid.