Skill Experiment 3 - Solution
Skill Experiment 3 - Solution
Aim/Objective:
Pre-Requisites:
Pre-Lab:
A database is a structured system for storing, managing, and retrieving large amounts of data,
often used by multiple users simultaneously. Unlike spreadsheets, databases are designed to
handle relationships between data across multiple tables and provide advanced querying and
scaling capabilities.
2. Define the following terms: Primary Key, Foreign Key, and Index. Provide examples for each.
Primary Key: A unique identifier for each record in a table, e.g., StudentID in a student
table.
Foreign Key: A field in one table that links to the primary key of another table, e.g.,
CourseID in an enrollment table referencing a courses table.
Index: A data structure that improves query performance, e.g., an index on LastName in
an employee’s table for faster searches.
SQL (Structured Query Language) is a standard programming language used to interact with
databases. It allows users to query, manipulate, and manage data efficiently, ensuring data
retrieval and modifications meet business needs.
4. Explain the difference between a SELECT statement and an INSERT statement in SQL.
In-Lab:
Procedure/Program:
Solution:
Installing the DBMS
Download from PostgreSQL official website.
Install with components like pgAdmin (a GUI tool for managing the database).
Set up a username and password for the superuser (default postgres).
Solution:
CREATE DATABASE test_db;
CREATE USER 'test_user' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON test_db.* TO 'test_user';
Solution:
Solution:
VALUES
('Human Resources'),
('IT'),
('Finance'),
('Marketing');
VALUES
Solution:
UPDATE Employees
SET DepartmentID = 3
WHERE FirstName = 'Jane' AND LastName = 'Smith';
Check Constraints:
SELECT conname AS ConstraintName, contype AS ConstraintType
FROM pg_constraint
WHERE conrelid = 'employees'::regclass;
ALTER TABLE Employees
ADD CONSTRAINT CheckSalary CHECK (Salary > 30000);
1. What is the purpose of a primary key in a database, and can a table have more than one primary
key?
Purpose: A primary key uniquely identifies each record in a table and ensures that no
duplicate or null values exist for the key column(s).
Multiple Primary Keys: A table cannot have more than one primary key, but it can
have a composite primary key, which combines multiple columns into a single primary
key.
2. Write an SQL query to retrieve the data using where command with a condition.
DELETE:
TRUNCATE:
JOIN Operation: Combines rows from two or more tables based on related columns
(usually through foreign keys).
INNER JOIN: Retrieves only the matching records from both tables.
LEFT JOIN: Retrieves all records from the left table and matching records from the right
table, filling unmatched rows with NULL.
5. Why is it important to enforce constraints like NOT NULL and UNIQUE in a database schema?
NOT NULL: Ensures essential data is not left blank, improving data integrity.
UNIQUE: Prevents duplicate entries, ensuring data consistency for attributes like email
or username.
Constraints enforce data reliability and prevent errors or inconsistencies in relational
databases.
Post-Lab:
1. Advanced Query Practice such as Writing subqueries, Using window functions , joins
2. Schema Optimization Exercise includes analyze and normalize their database schema to at least
the third normal form (3NF) and document the changes made.
3. Error Debugging: Fix a query where a foreign key constraint violation occurs.
4. Real-world Application Report
Procedure/Program:
1. Advanced Query Practice such as Writing subqueries, Using window functions , joins
Writing Subqueries:
SELECT DepartmentName
FROM Departments
WHERE DepartmentID IN (
SELECT DepartmentID
FROM Employees
GROUP BY DepartmentID
HAVING COUNT(EmployeeID) > 2
);
Using Window Functions:
SELECT DepartmentID, FirstName, LastName, Salary,
SUM(Salary) OVER (PARTITION BY DepartmentID ORDER BY HireDate) AS CumulativeSalary
FROM Employees;
Joins:
Inner Join:
Retrieve employee details along with their department names:
Left Join:
Show all employees, even those without a department:
Self-Join:
Find employees who share the same department:
2. Schema Optimization Exercise includes analyze and normalize their database schema to at least
the third normal form (3NF) and document the changes made.
Step 1: First Normal Form (1NF)
1NF requires all attributes to have atomic (indivisible) values.
The existing schema satisfies 2NF because there is no partial dependency in the current tables.
Step 3: Third Normal Form (3NF)
3NF removes transitive dependencies, ensuring that non-key attributes are dependent only on
the primary key.
1. Customers Table
FirstName VARCHAR(100),
LastName VARCHAR(100),
Email VARCHAR(100),
Phone VARCHAR(15),
Address VARCHAR(255)
);
2. Products Table
ProductName VARCHAR(100),
StockQuantity INT
);
3. Sales Table
ProductID INT,
Quantity INT,
SaleDate DATETIME,
);
Customers can make purchases via the store’s website or physical location.
By maintaining a Customers table, businesses can store detailed profiles, track purchasing
behavior, and execute targeted marketing strategies.
Product Inventory:
The Products table stores critical product details, including stock quantity.
When a sale is made, the Sales table records the transaction details, and the inventory is
updated by reducing the quantity in the Products table.
UPDATE Products
The Sales table stores the total amount for each sale, which is used to generate business reports
such as:
FROM Sales
Retail businesses use the customer data and sales history stored in the database to personalize
promotions, generate coupons, and send newsletters to customers.
For example, if a customer frequently buys specific products, the company might send them
promotions or discounts related to those products.
Example Query (Find loyal customers who spend more than $100):
FROM Sales
GROUP BY CustomerID
1. Data Redundancy: Managing large-scale data can result in duplication and inconsistencies.
Regular maintenance and normalization help avoid these issues.
2. Data Security: Storing sensitive customer data (such as emails and phone numbers) requires
implementing proper security measures like encryption and access control to prevent
unauthorized access.
3. Scalability: As businesses grow, the volume of transactions increases. Database systems need to
scale efficiently and effectively to handle millions of records.
(For Evaluator’s use only)
Evaluator MUST ask Viva-voice prior to signing and posting marks for each experiment