Certainly! Below is a comprehensive guide to performing various Oracle SQL operations on the provided Company database schema. This guide covers viewing databases and tables, creating and altering tables (with and without constraints), inserting/updating/deleting records, executing specific queries, and managing views. Each section includes SQL commands along with brief explanations to help you understand and implement the tasks effectively.
Company Database Schema
- EMPLOYEE
(FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO)
- DEPARTMENT
(DNAME, DNO, MGRSSN, MGRSTARTDATE)
- DEPT_LOCATIONS
(DNO, DLOCATION)
- PROJECT
(PNAME, PNO, PLOCATION, DNO)
- WORKS_ON
(ESSN, PNO, HOURS)
- DEPENDENT
(ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP)
2. Database and Table Operations
a. Viewing Databases, Creating a Database, Viewing Tables, Creating Tables, Inserting/Updating/Deleting Records, Commit and Rollback
Note: In Oracle, the concept of "databases" is different from other RDBMS like MySQL or SQL Server. Oracle uses schemas within a single database instance. Each schema is associated with a user. The following commands assume you have the necessary privileges.
1. Viewing All Schemas (Users)
SELECT username FROM all_users;
This query retrieves all user schemas in the Oracle database.
2. Creating a Schema (User)
CREATE USER company_user IDENTIFIED BY strong_password;
GRANT CONNECT, RESOURCE TO company_user;
Creates a new user/schema named company_user with a specified password and grants basic privileges.
3. Viewing All Tables in a Schema
SELECT table_name FROM user_tables;
Retrieves all tables owned by the current user.
For Another Schema:
SELECT table_name FROM all_tables WHERE owner = 'COMPANY_USER';
Replace 'COMPANY_USER' with the actual schema name.
4. Creating Tables
Without Constraints
CREATE TABLE EMPLOYEE (
FNAME VARCHAR2(20),
MINIT CHAR(1),
LNAME VARCHAR2(20),
SSN CHAR(9),
BDATE DATE,
ADDRESS VARCHAR2(50),
SEX CHAR(1),
SALARY NUMBER(10,2),
SUPERSSN CHAR(9),
DNO NUMBER(2)
);
With Constraints
CREATE TABLE DEPARTMENT (
DNAME VARCHAR2(20) NOT NULL,
DNO NUMBER(2) PRIMARY KEY,
MGRSSN CHAR(9),
MGRSTARTDATE DATE,
CONSTRAINT fk_manager FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN)
);
Includes primary key and foreign key constraints.
5. Inserting Records
INSERT INTO EMPLOYEE (
FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO
) VALUES (
'Jane', 'B', 'Smith', '111223333', TO_DATE('1985-07-23','YYYY-MM-DD'),
'456 Maple Ave', 'F', 75000, '222334444', 1
);
Inserts a new employee record.
6. Updating Records
UPDATE EMPLOYEE
SET SALARY = SALARY * 1.10
WHERE DNO = (SELECT DNO FROM DEPARTMENT WHERE DNAME = 'Research');
Gives a 10% raise to employees in the 'Research' department.
7. Deleting Records
DELETE FROM EMPLOYEE
WHERE SSN = '111223333';
Deletes the employee with the specified SSN.
8. Saving Changes (Commit)
COMMIT;
Saves all changes made during the current transaction.
9. Undoing Changes (Rollback)
ROLLBACK;
Reverts all changes made during the current transaction.
3. Altering and Managing Tables
a. Altering Tables, Dropping/Truncating/Renaming Tables, Backing Up/Restoring a Database
1. Altering a Table
-
Adding a Column:
ALTER TABLE EMPLOYEE
ADD (EMAIL VARCHAR2(50));
-
Modifying a Column:
ALTER TABLE EMPLOYEE
MODIFY (SALARY NUMBER(12,2));
-
Dropping a Column:
ALTER TABLE EMPLOYEE
DROP COLUMN EMAIL;
-
Adding a Constraint:
ALTER TABLE EMPLOYEE
ADD CONSTRAINT fk_department FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNO);
2. Dropping a Table
DROP TABLE WORKS_ON CASCADE CONSTRAINTS;
Drops the WORKS_ON table along with any dependent constraints.
3. Truncating a Table
TRUNCATE TABLE DEPENDENT;
Removes all records from the DEPENDENT table quickly without logging individual row deletions.
4. Renaming a Table
RENAME PROJECT TO PROJECTS;
Renames the PROJECT table to PROJECTS.
5. Backing Up and Restoring a Database
Oracle uses Data Pump utilities (expdp and impdp) for backing up and restoring schemas.
-
Exporting (Backing Up) a Schema:
expdp company_user/password@database schemas=company_user directory=DATA_PUMP_DIR dumpfile=company_backup.dmp logfile=export.log
-
Importing (Restoring) a Schema:
impdp company_user/password@database schemas=company_user directory=DATA_PUMP_DIR dumpfile=company_backup.dmp logfile=import.log
Ensure that the DATA_PUMP_DIR directory object is properly configured and points to a valid directory on the server.
4. Creating Tables and Performing Queries
a. Creating Tables
Use the CREATE TABLE statements from Section 2.a as needed for other tables like DEPT_LOCATIONS, PROJECT, WORKS_ON, and DEPENDENT.
b. Simple Queries
-
Retrieve All Employees:
SELECT * FROM EMPLOYEE;
-
Retrieve Specific Columns:
SELECT FNAME, LNAME, SALARY FROM EMPLOYEE;
c. Simple Queries with Aggregate Functions
d. Queries with GROUP BY and HAVING Clauses
-
Total Salary per Department:
SELECT DNO, SUM(SALARY) AS total_salary
FROM EMPLOYEE
GROUP BY DNO;
-
Departments with More Than 10 Employees:
SELECT DNO, COUNT(*) AS employee_count
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*) > 10;
5. Specific Salary Queries
a. Giving a 10% Raise to Employees in the 'Research' Department
UPDATE EMPLOYEE
SET SALARY = SALARY * 1.10
WHERE DNO IN (SELECT DNO FROM DEPARTMENT WHERE DNAME = 'Research');
Increases the salary by 10% for all employees in departments named 'Research'.
b. Aggregate Salary Statistics for the 'Accounts' Department
SELECT
SUM(E.SALARY) AS total_salary,
MAX(E.SALARY) AS max_salary,
MIN(E.SALARY) AS min_salary,
AVG(E.SALARY) AS avg_salary
FROM EMPLOYEE E
JOIN DEPARTMENT D ON E.DNO = D.DNO
WHERE D.DNAME = 'Accounts';
Calculates the total, maximum, minimum, and average salaries for employees in the 'Accounts' department.
6. Advanced Queries Using EXISTS
a. Retrieve Names of Employees Controlled by Department Number 5
Interpretation 1: Employees in Department 5.
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E
WHERE EXISTS (
SELECT 1
FROM DEPARTMENT D
WHERE D.DNO = 5 AND E.DNO = D.DNO
);
Interpretation 2: Employees supervised by managers in Department 5.
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E
WHERE EXISTS (
SELECT 1
FROM EMPLOYEE S
WHERE S.SSN = E.SUPERSSN AND S.DNO = 5
);
Choose the interpretation that best fits your data model.
b. Retrieve Department Names and Number of Employees (At Least 2 Employees)
SELECT D.DNAME, COUNT(E.SSN) AS num_employees
FROM DEPARTMENT D
JOIN EMPLOYEE E ON D.DNO = E.DNO
GROUP BY D.DNAME
HAVING COUNT(E.SSN) >= 2;
Lists departments with two or more employees along with the number of employees in each.
7. Complex Queries
a. Retrieve Project Number, Name, and Number of Employees Working on Each Project
SELECT P.PNO, P.PNAME, COUNT(W.ESSN) AS num_employees
FROM PROJECT P
LEFT JOIN WORKS_ON W ON P.PNO = W.PNO
GROUP BY P.PNO, P.PNAME;
Includes all projects, even those with no employees assigned.
b. Retrieve Names of Employees Born in the 1990s
Using EXTRACT:
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXTRACT(YEAR FROM BDATE) BETWEEN 1990 AND 1999;
Using BETWEEN with Dates:
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE BDATE BETWEEN DATE '1990-01-01' AND DATE '1999-12-31';
Retrieves employees born between January 1, 1990, and December 31, 1999.
8. Departments with More Than Five Employees and High Earners
SELECT E.DNO, COUNT(*) AS num_high_earners
FROM EMPLOYEE E
WHERE E.SALARY > 40000
AND E.DNO IN (
SELECT DNO
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*) > 5
)
GROUP BY E.DNO;
For each department with more than five employees, this query counts how many employees earn more than 40,000.
9. Projects with More Than Two Employees
SELECT P.PNO, P.PNAME, COUNT(W.ESSN) AS num_employees
FROM PROJECT P
JOIN WORKS_ON W ON P.PNO = W.PNO
GROUP BY P.PNO, P.PNAME
HAVING COUNT(W.ESSN) > 2;
Retrieves projects that have more than two employees working on them, along with the count of those employees.
10. Managing Views in Oracle SQL
a. Creating, Dropping, and Selecting from Views
Creating a View Without CHECK OPTION
CREATE VIEW HighSalaryEmployees AS
SELECT FNAME, LNAME, SALARY
FROM EMPLOYEE
WHERE SALARY > 50000;
Creates a view that shows employees with salaries greater than 50,000.
Creating a View With CHECK OPTION
CREATE VIEW HighSalaryEmployees AS
SELECT FNAME, LNAME, SALARY
FROM EMPLOYEE
WHERE SALARY > 50000
WITH CHECK OPTION;
Ensures that any insert or update through the view adheres to the salary condition.
Dropping a View
DROP VIEW HighSalaryEmployees;
Removes the HighSalaryEmployees view from the database.
Selecting from a View
SELECT * FROM HighSalaryEmployees;
Retrieves all records from the HighSalaryEmployees view.
Summary
This guide provides the essential Oracle SQL commands and procedures to manage the Company database effectively. Whether you're creating tables, performing CRUD operations, executing complex queries, or managing views, the commands outlined above should equip you with the necessary tools to handle various database tasks.
Tips:
- Always Backup Before Making Major Changes: Especially before dropping tables or altering schemas.
- Use Transactions Wisely: Encapsulate related SQL statements within
BEGIN TRANSACTION and COMMIT to maintain data integrity.
- Leverage Constraints: Proper use of primary keys, foreign keys, and other constraints ensures data consistency.
- Test Queries Incrementally: Especially complex queries, to ensure they return expected results.
Feel free to adapt and expand upon these examples to suit the specific needs and complexities of your database environment.