29th A
Mid–1
1. Primary Key and Foreign Key in RDBMS
• Primary Key: A column or a set of columns that uniquely identifies each row in a
table. It ensures data integrity by preventing duplicate and NULL values.
• Foreign Key: A column in one table that references the Primary Key of another table,
establishing a relationship between the two tables.
Real-world Example
Consider a university database:
• Students Table (student_id as Primary Key)
• Courses Table (course_id as Primary Key)
• Enrollments Table (Has student_id as a Foreign Key referencing Students and
course_id as a Foreign Key referencing Courses)
CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(100),
dob DATE
);
CREATE TABLE Courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);
FERDOUS HASSAN MIHAD 1
CREATE TABLE Enrollments (
enrollment_id INT PRIMARY KEY,
student_id INT,
course_id INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id),
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);
2. Basic Operations of RDBMS
The three fundamental operations are:
1. Insertion: Adding data into tables.
2. Updation: Modifying existing records.
3. Deletion: Removing records from tables.
Example
-- Insert data
INSERT INTO Students VALUES (1, 'Alice', '2000-01-01');
-- Update data
UPDATE Students SET student_name = 'Alice Smith' WHERE student_id = 1;
-- Delete data
DELETE FROM Students WHERE student_id = 1;
FERDOUS HASSAN MIHAD 2
3. Importance of Normalization in Database Design
Normalization eliminates data redundancy and ensures data integrity by structuring a
database into multiple related tables.
Example
A poorly designed "Employees" table:
emp_id emp_name dept dept_location
1 John HR NY
2 Alice IT LA
3 Bob HR NY
Here, "HR" is repeated for multiple employees. Normalization splits it into two tables:
Employees Table
emp_id emp_name dept_id
1 John 101
2 Alice 102
3 Bob 101
Departments Table
dept_id dept_name dept_location
101 HR NY
102 IT LA
This reduces redundancy and ensures consistency.
FERDOUS HASSAN MIHAD 3
4. Entity-Relationship Diagram (ERD) and Its Role in Database Design
• Definition: ERD is a visual representation of entities and their relationships in a
database.
• Role in Database Design: It helps in structuring the database efficiently by defining
relationships, attributes, and constraints.
Example
For a Library Database, an ERD might show:
• Entities: Books, Members, Loans
• Relationships: A member can borrow multiple books (one-to-many)
5. SQL Commands for Given Scenarios
a) Creating the emp_info Table
CREATE TABLE emp_info (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100),
designation VARCHAR(50),
doj DATE,
salary DECIMAL(10,2),
address VARCHAR(255)
);
b) Retrieve emp_id, designation, salary, address where salary < 100000 or address =
'Khulna'
SELECT emp_id, designation, salary, address FROM emp_info
WHERE salary < 100000 OR address = 'Khulna';
c) Retrieve emp_name, designation, salary, and address in ascending order by
emp_name
SELECT emp_name, designation, salary, address FROM emp_info
ORDER BY emp_name ASC;
FERDOUS HASSAN MIHAD 4
Mid - 2
Here’s how you can create a Relational Database in Microsoft Access named employee
and complete the required tasks.
Step 1: Create the Database
1. Open Microsoft Access.
2. Click on Blank Database.
3. Name it employee.accdb and click Create.
Step 2: Create the Tables
a) Create emp_info Table
1. Go to Table Design View.
2. Create the following fields:
o emp_id (AutoNumber, Primary Key)
o name (Short Text)
o doj (Date/Time)
o designation (Short Text)
3. Save the table as emp_info.
b) Create emp_salary Table
1. Go to Table Design View.
2. Create the following fields:
o emp_id (Number, Foreign Key referencing emp_info)
o name (Short Text)
o salary (Currency)
o address (Short Text)
FERDOUS HASSAN MIHAD 5
3. Save the table as emp_salary.
Step 3: Insert 7 Sample Records
1. Go to Datasheet View of each table.
2. Manually enter at least 7 records in each table.
Example Data for emp_info
emp_id name doj designation
1 John 2020-01-15 Manager
2 Alice 2019-06-20 Engineer
3 Robert 2021-03-10 Analyst
4 Sarah 2018-08-25 HR
5 David 2022-04-30 Developer
6 Emma 2017-11-12 Supervisor
7 James 2016-07-19 Director
Example Data for emp_salary
emp_id name salary address
1 John 60000 Dhaka
2 Alice 48000 Khulna
3 Robert 52000 Dhaka
4 Sarah 45000 Sylhet
5 David 70000 Dhaka
6 Emma 65000 Barisal
7 James 55000 Dhaka
FERDOUS HASSAN MIHAD 6
Step 4: Show the Relationship Among Tables
1. Go to Database Tools → Relationships.
2. Click Show Table → Add emp_info and emp_salary.
3. Drag emp_id from emp_info to emp_id in emp_salary (One-to-Many Relationship).
4. Enforce Referential Integrity and click Create.
Step 5: Create a Query
1. Go to Create → Query Design.
2. Add both tables (emp_info, emp_salary).
3. Drag the following fields to the Query Grid:
o emp_id from emp_info
o designation from emp_info
o salary from emp_salary
o address from emp_salary
4. Add Criteria:
o Salary: >=50000
o Address: "Dhaka"
5. Run the query.
SQL Equivalent
SELECT emp_info.emp_id, emp_info.designation, emp_salary.salary, emp_salary.address
FROM emp_info INNER JOIN emp_salary ON emp_info.emp_id = emp_salary.emp_id
WHERE emp_salary.salary >= 50000 AND emp_salary.address = "Dhaka";
FERDOUS HASSAN MIHAD 7
Final Output (Query Result)
emp_id designation salary address
1 Manager 60000 Dhaka
3 Analyst 52000 Dhaka
5 Developer 70000 Dhaka
7 Director 55000 Dhaka
FERDOUS HASSAN MIHAD 8
28th Batch
Mid – 1(A)
1) Primary Key & Foreign Key in RDBMS
Primary Key:
A Primary Key is a unique identifier for a record in a table. It ensures that no two rows have
the same value for this column. The primary key cannot contain NULL values and must be
unique.
Example:
Consider a “Students” table:
Student_ID (PK) Name Age
101 John 22
102 Alice 21
103 Bob 23
Here, Student_ID is the Primary Key because it uniquely identifies each student.
Foreign Key:
A Foreign Key is a column that establishes a relationship between two tables. It references
the Primary Key of another table.
Example:
Consider a Courses table that links students to the courses they enroll in:
Course_ID Student_ID (FK) Course_Name
C001 101 Math
C002 102 Science
C003 103 History
FERDOUS HASSAN MIHAD 9
Here, Student_ID in the Courses table is a Foreign Key referencing the Student_ID in the
Students table. This ensures that only valid students can be assigned courses.
2) Three Main RDBMS Operations
a) INSERT (Adding Data to a Table)
The INSERT operation is used to add new records to a table.
Example:
INSERT INTO Students (Student_ID, Name, Age) VALUES (104, 'Emma', 22);
b) UPDATE (Modifying Existing Data)
The UPDATE operation is used to modify existing records in a table.
Example:
UPDATE Students SET Age = 24 WHERE Student_ID = 101;
This updates John's age to 24.
c) DELETE (Removing Data from a Table)
The DELETE operation removes records from a table.
Example:
DELETE FROM Students WHERE Student_ID = 103;
This removes Bob's record from the Students table.
3) Definitions of Key Concepts
a) Data Definition Language (DDL):
DDL is a category of SQL commands that define and modify database structures. It
includes:
• CREATE (to create tables/databases)
• ALTER (to modify table structures)
• DROP (to delete tables/databases)
FERDOUS HASSAN MIHAD 10
Example:
CREATE TABLE Employees (
Emp_ID INT PRIMARY KEY,
Name VARCHAR(50),
Salary DECIMAL(10,2)
);
b) Data Dictionary:
A Data Dictionary is a collection of metadata that describes the structure of a database,
including tables, columns, data types, and constraints. It helps in database management and
ensures consistency.
Example:
In an RDBMS, system tables store metadata, such as:
• Table names
• Column names and data types
• Primary and foreign keys
Example Query to View Metadata in MySQL:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Students';
FERDOUS HASSAN MIHAD 11
28th Batch
Semester Final
Question No. 1
(a) Data Types in Python with Examples
Python provides several built-in data types:
1. Numeric Types:
o int (e.g., 10)
o float (e.g., 3.14)
o complex (e.g., 3+4j)
2. Sequence Types:
o str (e.g., "Hello")
o list (e.g., [1, 2, 3])
o tuple (e.g., (4, 5, 6))
3. Set Types:
o set (e.g., {1, 2, 3})
4. Mapping Type:
o dict (e.g., {"name": "Alice", "age": 25})
5. Boolean Type:
o bool (True, False)
6. Binary Types:
o bytes, bytearray, memoryview
FERDOUS HASSAN MIHAD 12
Python Program Demonstrating Data Types
# Numeric Types
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
# Sequence Types
name = "Alice" # str
numbers = [1, 2, 3] # list
coordinates = (4, 5, 6) # tuple
# Set and Dictionary
unique_values = {1, 2, 3} # set
person = {"name": "Alice", "age": 25} # dict
# Boolean
status = True
print(type(x), type(y), type(z))
print(type(name), type(numbers), type(coordinates))
print(type(unique_values), type(person))
print(type(status))
FERDOUS HASSAN MIHAD 13
(b) Python Program to Determine the Break-Even Point
The break-even point (BEP) occurs when:
Question No. 2
(a) Data Manipulation Language (DML) and Basic Commands
Data Manipulation Language (DML) is a subset of SQL used to retrieve and manipulate
data.
Three Basic DML Commands:
1. INSERT: Adds new records.
2. INSERT INTO employees (id, name, salary) VALUES (1, 'Alice', 50000);
3. UPDATE: Modifies existing records.
4. UPDATE employees SET salary = 55000 WHERE id = 1;
5. DELETE: Removes records.
6. DELETE FROM employees WHERE id = 1;
FERDOUS HASSAN MIHAD 14
(b) Mapping Cardinalities in E-R Model
Mapping cardinalities define how many instances of one entity can be associated with
instances of another entity.
1. One-to-One (1:1)
o A person has one passport.
2. One-to-Many (1:M)
o A teacher teaches many students.
3. Many-to-One (M:1)
o Many students are enrolled in one course.
4. Many-to-Many (M:N)
o A student can enroll in many courses, and each course has many students.
Question No. 3
(a) Differences Among Lists, Tuples, Dictionaries, and Sets
Differences Among Lists, Tuples, Dictionaries, and Sets (Theoretical Explanation)
Feature List Tuple Dictionary Set
Definition Ordered An ordered Key-value pairs An unordered
collection of but immutable store data. collection of unique
elements. collection. elements.
Mutability Mutable (can Immutable Mutable (keys Mutable (elements can
be modified). (cannot be are immutable, be added/removed,
modified). values can but not changed).
change).
Order Maintains Maintains Maintains Unordered (does not
insertion insertion insertion order maintain insertion
order. order (Python (Python 3.7+). order).
3.7+).
FERDOUS HASSAN MIHAD 15
Duplicates Allows Allows Keys must be Does not allow
duplicate duplicate unique, values duplicate values.
values. values. can be
duplicated.
Indexing Supports Supports Keys are used Does not support
indexing and indexing and instead of indexing.
slicing. slicing. indexes.
Usage Used for Used when Used for key- Used to store unique
storing a data should value mappings. values efficiently.
sequence of not change.
elements.
Example [1, 2, 3, 4] (10, 20, 30, {"name": "Alice", {1, 2, 3, 4}
40) "age": 25}
(b) Python Program for Personal Income Tax Calculation
FERDOUS HASSAN MIHAD 16
Question No. 4
(a) What is a Database Management System (DBMS)?
A Database Management System (DBMS) is software that allows users to create, manage,
and manipulate databases efficiently. It provides data storage, retrieval, security, integrity,
and backup functionalities.
Why is Relational DBMS (RDBMS) Better than Hierarchical and Network DBMS?
Feature Hierarchical DBMS Network DBMS Relational DBMS
(RDBMS)
Structure Tree-like structure Graph-like structure Tabular structure
(parent-child (many-to-many (tables with rows and
relationships). relationships). columns).
Flexibility Rigid, difficult to More flexible than Highly flexible with
modify relationships. hierarchical, but easy modifications.
complex.
Data High redundancy Less redundancy than Minimal redundancy
Redundancy (data duplication). hierarchical, but still using normalization.
present.
Ease of Use Complex to navigate Complex due to Easy to use with SQL
and update. multiple relationships. for queries.
Query Uses navigational Uses procedural Uses SQL (Structured
Language queries. queries. Query Language).
Scalability Difficult to scale due Better scalability than Highly scalable and
to rigid structure. hierarchical. widely used.
Justification for RDBMS Superiority
1. Flexibility – RDBMS allows changes in schema without major structural changes.
2. Reduced Redundancy – Normalization minimizes data duplication.
3. Ease of Data Retrieval – SQL simplifies querying data.
4. Scalability – Supports large-scale applications efficiently.
5. Data Integrity & Security – Enforces constraints like primary keys and foreign keys.
Thus, RDBMS is better than hierarchical and network DBMS due to its ease of use, reduced
redundancy, scalability, and efficient query execution
FERDOUS HASSAN MIHAD 17
(b) Identifying Super Key(s), Candidate Key(s), Primary Key(s), Alternate Key(s),
and Composite Key(s)
## Description of Different Types of Keys in DBMS
1. Super Key
A super key is a set of one or more attributes that uniquely identify a record in a table. It
may contain extra attributes that are not necessary for uniqueness.
Examples:
• {EID} (Employee ID alone uniquely identifies a record)
• {NID} (National ID is also unique)
• {EID, Name} (Although EID alone is enough, Name is an extra attribute)
• {EID, NID} (Both are unique, but one is redundant)
• {EID, Phone}, {Name, Phone}, {Name, NID, Phone}, etc.
Key Point: Every candidate key is a super key, but not every super key is a candidate
key.
2. Candidate Key
A candidate key is a minimal super key, meaning it has no unnecessary attributes. It
uniquely identifies each record.
Examples:
• {EID} (Employee ID uniquely identifies a record)
• {NID} (National ID is unique for every person)
• {Name, Phone} (If a name alone isn’t unique, but a combination of name and phone
number is, then this is a candidate key)
• {Email} (If emails are unique, this can be a candidate key)
Key Point: A table can have multiple candidate keys, but only one is chosen as the
primary key.
FERDOUS HASSAN MIHAD 18
3. Primary Key
A primary key is the candidate key that is selected to uniquely identify records in a table. It
ensures no duplicate or NULL values.
Example:
• {EID} (Chosen as the primary key because it's always unique and not NULL)
Key Point: A table can have only one primary key.
4. Alternate Key
An alternate key is any candidate key that is not chosen as the primary key.
Examples:
• {NID} (If EID is chosen as the primary key, NID remains an alternate key)
• {Name, Phone} (If unique, but not the primary key, it is an alternate key)
Key Point: Alternate keys are still unique but are not used as the main identifier.
5. Unique Key
A unique key is similar to a primary key but allows NULL values (unlike primary keys, which
must always be filled).
Examples:
• {NID} (If NID is unique but not mandatory, it can be a unique key)
• {Name, Phone} (If this combination must be unique but is not the primary key)
Key Point: A table can have multiple unique keys, but NULL values are allowed.
6. Composite Key
A composite key is a key that consists of two or more attributes together to uniquely identify
a record.
Examples:
• {Name, Phone} (If Name alone is not unique but combined with Phone, it becomes
unique)
FERDOUS HASSAN MIHAD 19
• {Name, NID, Phone} (Multiple attributes together ensure uniqueness)
Key Point: A composite key is used when no single attribute can uniquely identify a
row.
7. Foreign Key
A foreign key is an attribute in one table that establishes a link between two tables by
referencing a primary key in another table. It ensures referential integrity.
Example:
Consider two tables:
Employees Table
EID (PK) Name Phone
1 Alex 0123456789
2 Bob 0987654321
Salaries Table
Salary_ID EID (FK) Salary
101 1 50,000
102 2 40,000
Here, EID in the Salaries Table is a foreign key referring to EID in the Employees Table.
Key Point: A foreign key creates a relationship between tables and maintains data
integrity.
FERDOUS HASSAN MIHAD 20
Final Summary Table
Key Type Definition Example
Super Key A set of attributes that uniquely {EID}, {EID, Name}, {EID, Phone},
identify a record. {Name, Phone}
Candidate A minimal super key with no {EID}, {NID}, {Name, Phone}
Key unnecessary attributes.
Primary Key The chosen candidate key for {EID}
uniquely identifying records.
Alternate Any candidate key that is not the {NID}, {Name, Phone}
Key primary key.
Unique Key A key that ensures uniqueness but {NID}, {Name, Phone}
allows NULL values.
Composite A key made up of two or more {Name, Phone}, {Name, NID,
Key attributes. Phone}
Foreign Key A key that links two tables by EID in Salaries Table referencing
referencing a primary key. EID in Employees Table
Given Table
ID Name Email Skills Salary
1 Michael m@office.com Communication, Leadership 50,000
2 Pam p@office.com Communication 20,000
3 Dwight (No Email) IT, Leadership 35,000
4 Jim j@office.com IT, Teamwork 35,000
5 Pam pm@office.com Teamwork 25,000
FERDOUS HASSAN MIHAD 21
Key Identification and Justification
Key Type Definition Selection in the Justification
Table
Super Key A set of attributes that {ID}, {Email}, Any column or set of columns
uniquely identify a row. {ID, Name}, {ID, that uniquely identifies a row.
Salary}
Candidate A minimal super key {ID}, {Email} ID and Email are unique for
Key (no redundant each row, and no unnecessary
attributes). columns are included.
Primary The chosen candidate {ID} ID is unique and always
Key key for uniquely available, making it the best
identifying records. choice.
Alternate A candidate key that is {Email} Since Email is also unique but
Key not chosen as the not chosen as the primary key,
primary key. it is an alternate key.
Composite A key formed by two or {Name, Email} If ID were not available, Name +
Key more attributes. Email together could uniquely
identify records.
Final Answer
• Super Keys: {ID}, {Email}, {ID, Name}, {ID, Salary}, etc.
• Candidate Keys: {ID}, {Email}
• Primary Key: {ID}
• Alternate Key: {Email}
• Composite Key: {Name, Email}
FERDOUS HASSAN MIHAD 22
Question No. 5
(a) Relationship Constraints in the Entity-Relationship (E-R) Model
There are two main relationship constraints in the E-R model:
1. Cardinality Constraint:
o Defines how many instances of one entity can be associated with instances of
another entity.
o Example: A customer can place multiple orders (1:N), but each order
belongs to one customer.
2. Participation Constraint:
o Specifies whether all entities in a set must participate in a relationship.
o Total Participation: Every instance of an entity must participate (e.g., every
order must belong to a customer).
o Partial Participation: Some instances of an entity may not participate (e.g., a
customer may not have placed an order yet).
FERDOUS HASSAN MIHAD 23
(c) E-R Diagram for an Online Shopping System
• Entities:
o Customer (Customer_ID, First_Name, Last_Name, Email)
o Order (Order_ID, Order_Date, Total_Amount, Customer_ID)
o Product (Product_ID, Product_Name, Price)
o Order_Product (Order_ID, Product_ID, Quantity) (This is a junction table to
handle many-to-many relationships)
• Relationships & Cardinality:
o Customer – Order (1:N) → One customer can place multiple orders.
o Order – Product (M:N) → One order can have multiple products, and a
product can be in multiple orders.
Primary Keys:
• Customer: Customer_ID
• Order: Order_ID
• Product: Product_ID
FERDOUS HASSAN MIHAD 24
• Order_Product (Junction Table): Order_ID + Product_ID (Composite Key)
Question No. 6
(a) What is Normalization? Why is 5th Normal Form Better than 4th Normal Form?
Normalization is the process of organizing a database to reduce redundancy and improve
integrity.
• Fifth Normal Form (5NF) vs. Fourth Normal Form (4NF):
o 4NF eliminates multi-valued dependencies by ensuring a record does not
have multiple independent values for a single attribute.
o 5NF further removes join dependencies, ensuring no redundant
relationships exist.
o Advantage: 5NF ensures that complex many-to-many relationships are
correctly structured, reducing redundancy more efficiently than 4NF.
(b) SQL Commands for Employee Database
(i) Create a Database and Table
CREATE DATABASE Company;
USE Company;
CREATE TABLE Staff (
ID INT AUTO_INCREMENT PRIMARY KEY,
First_Name VARCHAR(50),
Last_Name VARCHAR(50),
Department VARCHAR(50) DEFAULT 'Not Allocated',
Salary DECIMAL(10,2)
);
FERDOUS HASSAN MIHAD 25
(ii) Insert Data into the Table
INSERT INTO Staff (First_Name, Last_Name, Department, Salary) VALUES
('Lionel', 'Messi', 'Acc', 50000),
('Cristiano', 'Ronaldo', 'Mkt', 40000),
('Kylian', 'Mbappe', 'IT', 30000);
(iii) Add a Full Name Column
ALTER TABLE Staff ADD COLUMN Full_Name VARCHAR(100);
UPDATE Staff SET Full_Name = CONCAT(First_Name, ' ', Last_Name);
(iv) Sort Employees Alphabetically by First Name
SELECT * FROM Staff ORDER BY First_Name;
(v) Select Employees Whose Last Name Starts with "M"
SELECT * FROM Staff WHERE Last_Name LIKE 'M%';
(vi) Find the Average Salary
SELECT AVG(Salary) AS Average_Salary FROM Staff;
(vii) Select Employees with Salary >= 40,000
SELECT * FROM Staff WHERE Salary >= 40000;
FERDOUS HASSAN MIHAD 26
27th Batch
Final
Question #03
a) What is an Attribute?
An attribute is a property/column in a database table.
• Example in a Student Database:
o Student_ID (Primary Key)
o Name (Attribute)
o Age (Attribute)
b) What is a Data Model?
A Data Model defines the structure of a database.
• Example: E-R Model (Entity-Relationship Model)
ER Diagram Example:
• Entities: Customer, Product, Order
• Relationships: Places (Customer-Order), Contains (Order-Product)
c) Mapping Cardinalities
1. One-to-One (1:1) – A person has one passport.
2. One-to-Many (1:M) – A teacher teaches many students.
3. Many-to-Many (M: M) – A student enrolls in many courses.
Sdkfjkaksjdfa
FERDOUS HASSAN MIHAD 27
Here’s a detailed breakdown of Question #04 and Question #05 with explanations and SQL
queries.
Question #04
a) What Does the JOIN Clause Do in SQL?
The JOIN clause in SQL is used to combine rows from two or more tables based on a related
column.
Types of JOINs in SQL
1. INNER JOIN: Returns only matching records in both tables.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
2. LEFT JOIN (LEFT OUTER JOIN): Returns all records from the left table and matching
records from the right.
SELECT customers.name, orders.order_id
FROM customers
LEFT JOIN orders
ON customers.customer_id = orders.customer_id;
3. RIGHT JOIN (RIGHT OUTER JOIN): Returns all records from the right table and
matching records from the left.
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
4. FULL JOIN (FULL OUTER JOIN): Returns all records from both tables, with NULL
where there is no match.
SELECT employees.name, departments.department_name
FERDOUS HASSAN MIHAD 28
FROM employees
FULL JOIN departments
ON employees.department_id = departments.department_id;
5. CROSS JOIN: Returns the Cartesian product (combination of all rows).
SELECT customers.name, products.product_name
FROM customers
CROSS JOIN products;
b) Uses of SQL Concepts
1. HAVING Clause
o Used with GROUP BY to filter grouped data.
SELECT department, COUNT(employee_id) FROM employees
GROUP BY department HAVING COUNT(employee_id) > 5;
2. SQL Subqueries
o A query inside another query.
SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM
employees);
3. ORDER BY Clause
o Sorts query results in ascending (ASC) or descending (DESC) order.
SELECT name, salary FROM employees ORDER BY salary DESC;
4. SQL Aliases
o Assigns a temporary name to a table or column.
SELECT e.name AS EmployeeName, d.department_name AS Dept FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
FERDOUS HASSAN MIHAD 29
c) SQL Commands for Given Scenarios
1. Create employee_information Table
CREATE TABLE employee_information (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100),
employee_location VARCHAR(100)
);
2. Find sales, sales_person, trnx_id, region where sales > 10,000
SELECT sales, sales_person, trnx_id, region FROM transactions WHERE sales > 10000;
3. Display customer_name, address, postal_code, country, sorted by
customer_name
SELECT customer_name, address, postal_code, country FROM customer_information
ORDER BY customer_name ASC;
4. Add a New Column customer_review to customer_information Table
ALTER TABLE customer_information ADD customer_review INT CHECK
(customer_review BETWEEN 1 AND 5);
5. Insert Data into employee_information Table
INSERT INTO employee_information (employee_id, employee_name,
employee_location)
VALUES (1, 'John Doe', 'Dhaka');
6. Find customer_name, order_id, region, quantity_sold, amount where amount >
5000 and region = 'DHAKA' (Limit to 10 results)
SELECT customer_name, order_id, region, quantity_sold, amount FROM orders
WHERE amount > 5000 AND region = 'DHAKA' LIMIT 10;
FERDOUS HASSAN MIHAD 30
Question #05
a) What is Data Manipulation Language (DML)?
DML is used to manipulate data within tables in a relational database.
Three Basic DML Commands with Examples
1. INSERT (Adds new records)
INSERT INTO employees (employee_id, name, department) VALUES (1, 'Alice', 'HR');
2. UPDATE (Modifies existing records)
UPDATE employees SET department = 'Finance' WHERE name = 'Alice';
3. DELETE (Removes records)
DELETE FROM employees WHERE employee_id = 1;
b) What is RDBMS? How Does It Organize Data?
A Relational Database Management System (RDBMS) stores data in tables with rows and
columns. It organizes data using relationships between tables using keys.
• Tables store records as rows.
• Primary Key uniquely identifies each row.
• Foreign Key links tables together.
• Normalization ensures minimal data redundancy.
Example: Employee-Department Relationship
Employee_ID Name Department_ID
1 John 101
2 Alice 102
Department_ID Department_Name
101 HR
102 Finance
FERDOUS HASSAN MIHAD 31
SELECT employees.name, departments.department_name FROM employees
JOIN departments ON employees.department_id = departments.department_id;
c) Three Basic Operations in RDBMS
1. Selection (σ): Retrieves specific rows from a table.
SELECT * FROM employees WHERE department = 'HR';
2. Projection (π): Retrieves specific columns from a table.
SELECT name, salary FROM employees;
3. Join (⨝): Combines data from multiple tables.
SELECT employees.name, departments.department_name FROM employees
JOIN departments ON employees.department_id = departments.department_id;
Conclusion
• SQL JOINs allow us to merge data from different tables.
• DML commands modify data in a database.
• RDBMS organizes data efficiently through relationships.
FERDOUS HASSAN MIHAD 32
26th Batch
Final
Question 1: Query Language and RDBMS
a) What is a Query Language? Discuss its Use in Database Management.
A query language is a specialized programming language used to retrieve, manipulate, and
manage data in a database. It allows users to:
• Retrieve specific data using SELECT statements.
• Insert, update, or delete records.
• Define data structures (tables, relationships).
• Control access to data.
Use in Database Management:
• Efficient Data Retrieval: Fetch required data quickly from large datasets.
• Data Manipulation: Perform operations like adding, deleting, or updating data.
• Security and Access Control: Manage user permissions on data.
• Database Optimization: Helps optimize queries for better performance.
b) How SQL Came to Be? What is an SQL Dialect?
History of SQL:
SQL (Structured Query Language) was developed in the 1970s by IBM as part of their
System R project. Later, Oracle became the first company to commercialize SQL-based
RDBMS. SQL was standardized by ANSI in 1986 and ISO in 1987.
What is an SQL Dialect?
An SQL dialect is a variant of SQL adapted by different database vendors. While the core
SQL commands are common, dialects include vendor-specific functions, optimizations, and
syntax.
FERDOUS HASSAN MIHAD 33
Examples of SQL Dialects:
• MySQL – Uses LIMIT instead of TOP for limiting results.
• PostgreSQL – Supports JSON and advanced indexing methods.
• SQL Server (T-SQL) – Includes procedural programming elements.
• Oracle SQL (PL/SQL) – Allows procedural extensions.
c) What is RDBMS? Why is NoSQL Needed?
Relational Database Management System (RDBMS):
An RDBMS is a database management system that organizes data into tables with
relationships between them. Data is stored in structured formats, ensuring data integrity
and consistency.
Features of RDBMS:
• Uses tables with rows and columns.
• Enforces ACID (Atomicity, Consistency, Isolation, Durability) properties.
• Uses SQL for querying and managing data.
• Supports relationships through Primary Keys and Foreign Keys.
Popular RDBMS:
• MySQL
• PostgreSQL
• Oracle Database
• Microsoft SQL Server
• IBM Db2
Why NoSQL is Needed?
NoSQL databases were introduced to handle big data and unstructured data where
RDBMS struggles.
• Scalability: Horizontal scaling for large-scale applications (e.g., social media, e-
commerce).
• Flexible Schema: No predefined schema required, making it easier to handle
dynamic data.
FERDOUS HASSAN MIHAD 34
• High Performance: Faster read/write operations for massive datasets.
Examples of NoSQL Databases:
• MongoDB (Document-based)
• Cassandra (Wide-column store)
• Redis (Key-value store)
• Neo4j (Graph database)
Question 3: SQL Joins and Keys
a) What is JOIN in SQL? Discuss Various Types.
A JOIN in SQL is used to retrieve data from multiple tables based on a related column.
Types of JOINs:
1. INNER JOIN – Returns only matching records.
2. LEFT JOIN – Returns all records from the left table and matching records from the
right table.
3. RIGHT JOIN – Returns all records from the right table and matching records from the
left table.
4. FULL JOIN – Returns all records when there is a match in either table.
5. CROSS JOIN – Returns the Cartesian product of both tables.
b) Differences Between Primary Key and Foreign Key
Primary Key Foreign Key
Uniquely identifies a record in a table. Establishes a link between two tables.
Cannot have NULL values. Can have NULL values.
Each table can have only one primary key. A table can have multiple foreign keys.
FERDOUS HASSAN MIHAD 35
Example:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);
c) SQL Commands for Given Scenarios
i) Create customer_information Table
CREATE TABLE customer_information (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100),
customer_location VARCHAR(100)
);
ii) Query for Sales Greater than 10,000
SELECT sales, sales_person, trnx_id, region FROM transactions WHERE sales > 10000;
iii) Order Customers Alphabetically
SELECT customer_name, address, postal_code, country FROM customer_information
ORDER BY customer_name ASC;
FERDOUS HASSAN MIHAD 36
iv) Add customer_review Column
ALTER TABLE customer_information ADD customer_review
INT CHECK (customer_review BETWEEN 1 AND 5);
v) Insert Hypothetical Data
INSERT INTO customer_information (customer_id, customer_name, customer_location)
VALUES (1, 'John Doe', 'Dhaka');
Question 6: Non-Relational Databases, ER Diagrams, and Database Design Principles
a) Why Non-Relational Databases Are Useful?
Non-relational databases (NoSQL databases) are designed to handle large, unstructured,
and semi-structured data efficiently. Unlike relational databases, they do not use fixed
schemas, making them more scalable and flexible.
Key Advantages:
1. Scalability – Easily scales horizontally by distributing data across multiple servers.
2. Flexibility – Can store different types of data (JSON, key-value pairs, documents,
graphs).
3. High Performance – Faster read/write operations for massive datasets.
4. Schema-Free – Allows dynamic changes to data structure.
5. Handles Big Data – Ideal for real-time analytics, IoT, and recommendation systems.
Examples of NoSQL Databases:
• MongoDB (Document-based) – Used for storing JSON-like data.
• Cassandra (Column-family store) – Used for high availability and distributed
systems.
• Redis (Key-value store) – Used for caching and real-time applications.
• Neo4j (Graph database) – Used for social networks and recommendation engines.
FERDOUS HASSAN MIHAD 37
b) Entity-Relationship Diagram (ERD) and Its Role in Database Design
An Entity-Relationship Diagram (ERD) is a graphical representation of entities (tables)
and their relationships in a database. It helps visualize and structure the data before
creating the actual database.
Components of an ERD:
1. Entities – Objects in the database (e.g., Customer, Order).
2. Attributes – Characteristics of entities (e.g., Customer Name, Order Date).
3. Relationships – Links between entities (e.g., A Customer places an Order).
4. Primary Key – Uniquely identifies an entity (e.g., Customer ID).
5. Foreign Key – Establishes relationships between tables (e.g., Customer ID in Orders
table).
Role in Database Design:
• Clarifies Data Structure – Helps understand data relationships.
• Prevents Redundancy – Identifies duplicate data and normalizes it.
• Improves Query Performance – Organizes data efficiently for retrieval.
• Ensures Data Integrity – Defines constraints to maintain consistency.
Example ERD for an Online Shopping System:
(Customer) -------- (Order) -------- (Product)
| | |
Customer_ID Order_ID Product_ID
Name Order_Date Product_Name
Email Total_Amount Price
c) Normalization and Referential Integrity
Normalization in Database Design
Normalization is the process of structuring a database to reduce redundancy and
improve data integrity. It organizes data into multiple related tables and follows different
normal forms (NF).
FERDOUS HASSAN MIHAD 38
Normalization Forms:
• 1NF (First Normal Form) – Ensures each column contains atomic (indivisible)
values.
• 2NF (Second Normal Form) – Removes partial dependencies; ensures each column
depends on the primary key.
• 3NF (Third Normal Form) – Eliminates transitive dependencies (non-key attributes
must not depend on other non-key attributes).
• BCNF (Boyce-Codd Normal Form) – A stricter version of 3NF, ensuring every
determinant is a candidate key.
Example:
Before Normalization (1NF Violation):
Order_ID | Customer_Name | Product_List
---------------------------------------------
1001 | John Doe | Laptop, Mouse
1002 | Alice Smith | Keyboard
After Normalization:
Orders Table:
Order_ID | Customer_ID | Order_Date
-----------------------------------
1001 |1 | 2025-04-02
1002 |2 | 2025-04-03
Order_Items Table:
Order_ID | Product_ID
----------------------
1001 | 101
1001 | 102
1002 | 103
FERDOUS HASSAN MIHAD 39
Referential Integrity
Referential Integrity ensures relationships between tables remain valid. It enforces
constraints so that foreign keys always reference valid primary keys.
Why Referential Integrity is Important?
1. Prevents Orphan Records – Stops deletion of parent records that have related child
records.
2. Ensures Data Consistency – Foreign key values must match an existing primary key.
3. Maintains Relationship Accuracy – Prevents invalid data from being inserted.
Example of Referential Integrity in SQL:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id) ON DELETE
CASCADE
);
If a customer is deleted, all their associated orders will also be deleted (ON DELETE
CASCADE).
FERDOUS HASSAN MIHAD 40
Conclusion
• Non-relational databases are useful for handling big data, unstructured data, and
real-time applications.
• ER Diagrams play a crucial role in database design by visually representing entities
and their relationships.
• Normalization eliminates redundancy and ensures efficient data organization.
• Referential Integrity maintains consistency and prevents invalid relationships in
databases.
This ensures a well-structured, scalable, and reliable database system. Let me know if you
need further clarifications!
FERDOUS HASSAN MIHAD 41