0% found this document useful (0 votes)
2 views

q.bank Solve of Programming

U

Uploaded by

shamim698669
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

q.bank Solve of Programming

U

Uploaded by

shamim698669
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

29th batch MID-1(SEC-A)

1.What are the Primary Key and Foreign Key in RDBMS? Explain them with a real-world example. (28th batch mid)

Ans: In a Relational Database Management System (RDBMS), the concepts of Primary Key and Foreign Key are
essential for maintaining data integrity and establishing relationships between tables.

1. Primary Key
A Primary Key is a column (or a set of columns) in a table that uniquely identifies each record (row). It ensures that
there are no duplicate or NULL values in the column.
Characteristics of a Primary Key:
• Uniquely identifies each record.
• Cannot contain NULL values.
• There can be only one primary key per table.
Example:
Consider a Students table:
Student_ID (PK) Name Age
101 Alice 20
102 Bob 21
103 Charlie 22
Here, Student_ID is the Primary Key, as it uniquely identifies each student.

2. Foreign Key
A Foreign Key is a column (or set of columns) in one table that establishes a relationship with the Primary Key of
another table. It is used to maintain referential integrity between two tables.
Characteristics of a Foreign Key:
• Establishes a relationship between two tables.
• Can have duplicate values.
• Can contain NULL values (if the relationship allows).
Example:
Consider another table Course_Enrollments, where students enroll in courses:
Enrollment_ID Student_ID (FK) Course_Name
1 101 Math
2 102 Science
3 103 English
4 101 Science
Here, Student_ID in the Course_Enrollments table is a Foreign Key, as it refers to Student_ID in the Students
table. This ensures that only valid student IDs from the Students table can be inserted into the Course_Enrollments
table.

Real-World Example
Imagine a Library Management System:
• Books Table: Has a Primary Key (Book_ID).
• Borrowed_Books Table: Has a Foreign Key (Book_ID) that references the Primary Key in the Books
Table.

1. List the three basic operations of RDBMS. Briefly explain these operations with example.
Ans: Three Basic Operations of RDBMS

A Relational Database Management System (RDBMS) provides several operations to manage and
manipulate data. The three basic operations are:

1. INSERT (Adding Data)


2. UPDATE (Modifying Data)
3. DELETE (Removing Data)

1. INSERT Operation

The INSERT operation is used to add new records (rows) into a table.

Example:

Let's say we have a table called Employees:

Employee_ID Name Department Salary


101 Alice HR 50000
102 Bob IT 60000

To add a new employee:

Sql cord
INSERT INTO Employees (Employee_ID, Name, Department, Salary)
VALUES (103, 'Charlie', 'Finance', 55000);

After executing this query, the table will be updated with the new record.

2. UPDATE Operation

The UPDATE operation is used to modify existing records in a table.

Example:Suppose Bob from the IT department gets a salary increase. We can update his salary as follows:

Sql code
UPDATE Employees
SET Salary = 65000
WHERE Employee_ID = 102;

After this update, Bob's salary changes from 60000 to 65000.

3.DELETE Operation

The DELETE operation is used to remove existing records from a table.

Example:If an employee leaves the company, we can remove their record:

Sql code
DELETE FROM Employees
WHERE Employee_ID = 101;

This will remove Alice’s record from the Employees table.

Conclusion

These three basic operations (INSERT, UPDATE, DELETE) help manage data efficiently in an RDBMS.
They ensure that records can be added, modified, and removed as needed.

3.Why Normalization is important in designing a database? Justify your answer with appropriate example.

Ans: Normalization is a process in database design that organizes data to reduce redundancy and improve
data integrity. It involves dividing large tables into smaller ones and establishing relationships using
Primary Keys and Foreign Keys.

Importance of Normalization

1. Eliminates Data Redundancy


o Reduces duplicate data and saves storage space.
2. Ensures Data Consistency
o Changes made in one place automatically reflect in related tables.
3. Improves Data Integrity
o Prevents anomalies such as insertion, update, and deletion anomalies.
4. Enhances Query Performance
o Smaller, structured tables improve data retrieval speed.
5. Simplifies Maintenance
o Makes updates and modifications easier and more manageable.

Example: Without Normalization (Unnormalized Table - UNF)

Consider a Student Records Table:

Student_ID Name Course Instructor


101 Alice Math, Science John, Mary
102 Bob English David

Problems:

• Redundancy: If Alice takes multiple courses, her name is repeated.


• Update Anomaly: If the instructor for Math changes, we must update all rows where Math appears.
• Insertion Anomaly: If a new course is introduced but no student is enrolled yet, we cannot store
instructor details.
• Deletion Anomaly: If Alice drops out, we lose all course details associated with her.

Applying Normalization
First Normal Form (1NF) – Remove Multivalued Attributes

Break down the table so that each attribute has atomic values.

Student_ID Name Course Instructor


101 Alice Math John
101 Alice Science Mary
102 Bob English David

Now, each cell contains a single value, eliminating multivalued attributes.

Second Normal Form (2NF) – Remove Partial Dependency

A table is in 2NF if it is in 1NF and all non-key attributes are fully dependent on the Primary Key.

We divide the table into Students and Courses tables:

Students Table

Student_ID Name
101 Alice
102 Bob

Courses Table

Course_ID Course Instructor


C1 Math John
C2 Science Mary
C3 English David

Student_Course Table (Many-to-Many Relationship)

Student_ID Course_ID
101 C1
101 C2
102 C3

Now, data is properly organized, reducing redundancy and improving integrity.

Conclusion

Normalization ensures that the database is efficient, scalable, and free from anomalies. It improves data
accuracy, reduces storage costs, and enhances performance in large systems.

4. Define and describe Entity- Relationship Diagram and explain its role in database design.
Ans: An Entity-Relationship Diagram (ERD) is a visual representation of a database that illustrates how
entities (objects) relate to each other. It helps in designing a structured database by showing relationships
between different components such as entities, attributes, and relationships.

Components of ERD

1. Entities (Objects or Concepts)


o Represented as rectangles.
o Example: Students, Courses, Employees.
2. Attributes (Properties of Entities)
o Represented as ellipses (ovals).
o Example: Student_ID, Name, Age (attributes of Student entity).
3. Primary Key
o A unique identifier for an entity.
o Underlined in the diagram.
4. Relationships (Associations between Entities)
o Represented as diamonds.
o Example: "Enrolls" (relationship between Student and Course).
5. Cardinality (Defines the Number of Relationships)
o One-to-One (1:1) – One entity is related to only one other entity.
o One-to-Many (1:M) – One entity is related to multiple entities.
o Many-to-Many (M:N) – Multiple entities are related to multiple entities.

Example: ERD for a Student-Course System

Entities and Relationships:

• Student (Student_ID, Name, Age)


• Course (Course_ID, Course_Name)
• Enrollment (Relationship between Student and Course)

ERD Representation:

STUDENT (Student_ID as PK) ← ENROLLS → COURSE (Course_ID as PK)

Role of ERD in Database Design

1. Clear Structure & Planning


o Helps database designers plan the structure before implementation.
2. Avoids Redundancy
o Defines relationships properly, reducing data duplication.
3. Ensures Data Integrity
o Establishes primary keys and foreign keys, maintaining referential integrity.
4. Improves Communication
o Easy for developers, business analysts, and stakeholders to understand.
5. Efficient Query Processing
o Well-structured databases perform faster queries and operations.
Conclusion

An ERD is a crucial tool in database design that provides a clear, structured blueprint of how entities
interact. It helps in better planning, reducing redundancy, and improving efficiency.

5. Write down the appropriate SQL commands for the following scenarios:

a) Create a table called emp_ info that has the attributes : emp_id, emp_name, designation, doj, salary, address

Ans: (a) Creating the emp_info Table

The following CREATE TABLE statement creates a table named emp_info with the required attributes:

Sql

CREATE TABLE emp_info (

emp_id INT PRIMARY KEY,

emp_name VARCHAR(50),

designation VARCHAR(50),

doj DATE,

salary DECIMAL(10,2),

address VARCHAR(100)

);

emp_id is an integer and serves as the Primary Key.

emp_name, designation, and address are variable character strings (VARCHAR).

Doj is a date field (Date of Joining).

salary is a decimal number (to store salaries properly).

b)Find out the attributes : emp_id, designation, salary, address where salary is less than 100000 or address is Khulna

Ans: The SELECT query retrieves emp_id, designation, salary, and address for employees who have a
salary less than 100000 or live in Khulna.

Sql code
SELECT emp_id, designation, salary, address
FROM emp_info
WHERE salary < 100000 OR address = 'Khulna';
c)Find out the attributes : emp_name, designation, salary, address where emp_name will be in ascending order.

Ans: The SELECT query retrieves emp_name, designation, salary, and address, sorting the results in
ascending order by emp_name:

Sql code
SELECT emp_name, designation, salary, address
FROM emp_info
ORDER BY emp_name ASC;
• ORDER BY emp_name ASC ensures that names are sorted alphabetically (ascending order).

28th batch final


Question:1

1.What are the data types are used in Python programming? Show usage in a program which is coded by Python.

Ans: Python has several built-in data types used for different types of data storage and operations. Below
are the main data types:

1. Numeric Types

• int → Integer numbers (e.g., 10, -5, 1000)


• float → Decimal numbers (e.g., 10.5, -3.14)
• complex → Complex numbers (e.g., 2 + 3j)

2. Sequence Types

• str → String (e.g., "Hello", 'Python')


• list → Ordered, mutable collection (e.g., [1, 2, 3])
• tuple → Ordered, immutable collection (e.g., (10, 20, 30))
• range → Sequence of numbers (e.g., range(5) → 0,1,2,3,4)

3. Set Types

• set → Unordered, unique elements (e.g., {1, 2, 3})


• frozenset → Immutable set (e.g., frozenset({4, 5, 6}))

4. Mapping Type

• dict → Key-value pairs (e.g., {"name": "Alice", "age": 25})

5. Boolean Type

• bool → Represents True or False (True, False)

EAMPLE OF date types

# Integer data type:

age=int(input("what is your age?"))


print(f"my age is {age}")
# Float data type: price=float(input("what is the price of this gooda?")) print(f"the price is {price} ")

2.Write a program in Python to determine the Break-Even Point.

Ans: Break-Even Point (BEP) Calculation in Python

What is the Break-Even Point?

The Break-Even Point (BEP) is the point at which total revenue equals total cost, meaning no profit or
loss.

The formula to calculate BEP (in units):

BEP=Fixed Cost/Selling Price per Unit−Variable Cost per Unit Unit}}

Where:

• Fixed Cost (FC) → Costs that do not change (e.g., rent, salaries).
• Variable Cost per Unit (VC) → Cost that changes per unit (e.g., materials, labor).
• Selling Price per Unit (SP) → Price at which each unit is sold.

Simple Python Program to Calculate Break-Even Point


python
fc=float(input("enter fixed cost"))
sp=float(input("enter sales price"))
vc=float(input("enter variable cost"))
if sp>vc:
bep=fc/sp-vc
print(f'break even point{bep}')
else:
print(f'sales price must be greatern to determine must be ')

Example Run:
Enter Fixed Cost: 50000
Enter Variable Cost per Unit: 10
Enter Selling Price per Unit: 20
Break-Even Point: 5000.00 units

Question No. 2

1. What is Data Manipulation Language? Describe three basic commands of SQL with the help of example.

Ans: Data Manipulation Language (DML) is a subset of SQL (Structured Query Language) used to
retrieve, insert, update, and delete data in a database. These commands do not affect the structure of the
database, only the data inside the tables.

Three Basic DML Commands in SQL


1. INSERT – Adding Data
The INSERT command is used to add new records (rows) into a table.

Example:

sql
INSERT INTO employees (emp_id, emp_name, designation, salary)
VALUES (101, 'Alice', 'Manager', 80000);

This inserts a new employee named "Alice" into the employees table.

2. UPDATE – Modifying Data

The UPDATE command is used to modify existing records in a table.

Example:

sql
UPDATE employees
SET salary = 90000
WHERE emp_id = 101;

This updates Alice's salary to 90,000 where emp_id is 101.

3. DELETE – Removing Data

The DELETE command removes specific records from a table.

Example:

Sql

DELETE FROM employees

WHERE emp_id = 101;

This deletes the employee with emp_id 101 from the employees table.

2. Explain various Mapping Cardinalities that may be used in the E-R Model

Ans: Mapping cardinality (also called cardinality ratio) defines the number of entity instances that can
be associated with another entity in a relationship. It determines the type of relationship between entities in
an Entity-Relationship (E-R) Model.

Types of Mapping Cardinalities

1. One-to-One (1:1)

• Definition: Each entity in Entity A is related to at most one entity in Entity B, and vice versa.
• Example:
o Person ↔ Passport
o Each person has only one passport, and each passport belongs to only one person.

Diagram:

Person (1) ---- (1) Passport

2. One-to-Many (1:M)

• Definition: One entity in Entity A can be related to multiple entities in Entity B, but each entity in
B is related to only one entity in A.
• Example:
o Teacher ↔ Students
o A teacher can teach many students, but each student has only one teacher (in a specific
subject).

Diagram:

Teacher (1) ---- (M) Students

3. Many-to-One (M:1)

• Definition: Many entities in Entity A can be related to one entity in Entity B.


• Example:
o Employees ↔ Company
o Many employees work in one company, but each employee belongs to only one company.

Diagram:

Employees (M) ---- (1) Company

4. Many-to-Many (M:N)

• Definition: Multiple entities in Entity A can be related to multiple entities in Entity B.


• Example:
o Students ↔ Courses
o A student can enroll in many courses, and each course can have many students.

Diagram:

Students (M) ---- (N) Courses

Question no-3
1. What are the differences among lists, tuples, dictionaries, and sets? Explain by giving examples.

Ans: Python provides four main collection types: Lists, Tuples, Dictionaries, and Sets. Each has unique
properties and use cases.

1. List (Ordered, Mutable, Allows Duplicates)


• A list is an ordered collection of elements.
• It is mutable (modifiable).
• Allows duplicate values.
• Elements can be of different data types.

Example:
python
fruits = ["Apple", "Banana", "Cherry", "Apple"]
fruits.append("Mango") # Adding an element
fruits[1] = "Orange" # Modifying an element
print(fruits) # Output: ['Apple', 'Orange', 'Cherry', 'Apple', 'Mango']

✔ Best for: Storing multiple items in a sequence when modification is needed.

2. Tuple (Ordered, Immutable, Allows Duplicates)


• A tuple is an ordered collection.
• It is immutable (cannot be modified after creation).
• Allows duplicate values.
• Faster than lists.

Example:
python
coordinates = (10, 20, 30, 10)
# coordinates[1] = 40 # This will give an error (Tuples cannot be modified)
print(coordinates) # Output: (10, 20, 30, 10)

✔ Best for: Storing fixed data that should not change, like geographical coordinates.

3. Dictionary (Unordered, Mutable, Key-Value Pairs, No


Duplicate Keys)
• A dictionary stores key-value pairs.
• Keys are unique (no duplicates).
• Values can be modified, but keys cannot.
• Unordered before Python 3.7, but ordered in Python 3.7+.

Example:
python
student = {"name": "Alice", "age": 25, "city": "New York"}
student["age"] = 26 # Modifying a value
student["gender"] = "Female" # Adding a new key-value pair
print(student)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'gender': 'Female'}

✔ Best for: Storing related data where each item has a unique identifier (like a phonebook or database
record).
4. Set (Unordered, Mutable, No Duplicates)
• A set is an unordered collection.
• Does not allow duplicate values.
• Mutable (you can add or remove items).
• Optimized for fast lookup operations.

Example:
python
numbers = {1, 2, 3, 4, 1, 2} # Duplicates will be removed automatically
numbers.add(5) # Adding an element
numbers.remove(3) # Removing an element
print(numbers) # Output: {1, 2, 4, 5}

✔ Best for: Storing unique items, like a list of unique student IDs.

Comparison Table
Tuple
Feature List Dictionary Set

Ordered? Yes Yes (Python 3.7+) No


Mutable? Yes No Yes Yes
Duplicates
Yes Yes No (Keys) No
Allowed?
Indexed? Yes Yes No (Uses keys) No
Uses Key-Value? No No Yes No
When order & mutability are Fixed Key-value pairs Unique
Best Use Case?
needed data (database) items

2. Create a program using Python to calculate the amount of personal income tax of a person by taking his taxable
income as an input. The tax slabs are as follows:
Taxable income Tax rate
First tk. 350000 0%
Next tk.100000 5%
Next tk.300000 10%
Next tk.400000 15%
Next tk.500000 20%
On Balance 25%

Ans: income=int(input("what is your income?"))


if(income<=350000):
tax=0
elif(income<=450000):
tax=(income-350000)*0.05
elif(income<=750000):
tax = 100000 * .05#5000
tax=tax+(income-450000)*0.1
elif(income<=1150000):
tax=100000 * .05
tax=tax+(300000*0.1)
tax=tax+(income-1150000)*0.15
elif(income<=1650000):
tax=100000 * .05
tax=tax+(300000*0.1)
tax=tax+(400000*.15)
tax=tax+(income-1650000)*0.2
elif(income>1650000):
tax = 100000 * .05
tax = tax + (300000 * 0.1)
tax = tax + (400000 * .15)
tax = tax + (500000 * .2)
tax=tax+(income-1650000)
print(f'tax is {tax}')

Question no 4
1. What is database management system (DBMS)? Why is the Relational DBMS better than Hierarchical DBMS
and Network DBMS? Justify your answer.
2. Consider the following table and identify the super key(S), candidate key(S), primary key(S), alternate key(S),
composite key(S).justify the reason behind your selection.
ID Name Email Skills salary
1 A [email protected] Communication, leadership 50000
2 B [email protected] Communication, 20000
3 C [email protected] IT, Leadership 35000
4 D [email protected] IT, Teamwork 35000
5 E [email protected] Teamwork 25000

ans: 1. Super Key (S)


• A super key is a set of one or more attributes that can uniquely identify a row in a table.
• It may contain extra attributes that are not necessary for uniqueness.
Super Keys in this Table:
1. {ID} → ID is unique for each row.
2. {Email} → Each employee has a unique email.
3. {ID, Name} → Since ID is unique, adding Name is unnecessary but still qualifies as a super key.
4. {ID, Email} → Both are unique individually, so together they still form a super key.
5. {Email, Name} → Email is already unique; adding Name does not change the uniqueness.
✔ Any key that includes a unique column (ID or Email) is a super key.

2. Candidate Key (CK)


• A candidate key is a minimal super key (i.e., it cannot have extra attributes).
• Among the super keys, only {ID} and {Email} are minimal.
Candidate Keys:
1. {ID} → Unique for each row.
2. {Email} → Unique for each row.
✔ These are minimal keys and can be chosen as a primary key.

3. Primary Key (PK)


• The primary key is a candidate key that is chosen to uniquely identify records in the table.
• In most cases, ID is chosen as the primary key because:
o It is a simple numeric identifier.
o It does not change over time, unlike an email.
Primary Key:
{ID}

4. Alternate Key (AK)


• The alternate key is a candidate key that is not selected as the primary key.
Alternate Key:
{Email} (since {ID} is chosen as the primary key)

5. Composite Key (CK)


• A composite key consists of two or more columns that together uniquely identify a row.
• In this table, ID and Email are already uniquely identifying records individually, so a composite key is not
needed.
No composite key is required in this case because we already have simple candidate keys.

Summary of Key Identifications


Key Type Selected Key(s) Reason
{ID}, {Email}, {ID, Name}, {ID, Email}, Can uniquely identify a row (may contain extra
Super Key (S)
{Email, Name} attributes).
Candidate Key
{ID}, {Email} Minimal super keys (no extra attributes).
(CK)
Primary Key (PK) {ID} Chosen for uniqueness and simplicity.
Alternate Key
{Email} Not chosen as the primary key.
(AK)
Composite Key
None No need for a combination of attributes.
(CK)

Question no 5

a. What are the two relationship constraints in entity relationship model? Explain.

Ans: In an Entity-Relationship (E-R) model, relationship constraints define rules that regulate how
entities associate with one another. The two main constraints are:

1. Cardinality Constraint

• Defines the number of entities that can be associated with another entity in a relationship.
• Also known as mapping cardinality.
• Specifies how many instances of an entity A relate to how many instances of entity B.

Types of Cardinality Constraints:

1. One-to-One (1:1) → Each entity in A is related to at most one entity in B.


o Example: Person ↔ Passport (Each person has only one passport).
2. One-to-Many (1:M) → One entity in A is related to multiple entities in B.
o Example: Teacher ↔ Students (One teacher can teach many students, but each student has
only one teacher in a subject).
3. Many-to-One (M:1) → Many entities in A are related to one entity in B.
o Example: Employees ↔ Company (Many employees work for one company).
4. Many-to-Many (M:N) → Many entities in A can be related to many entities in B.
o Example: Students ↔ Courses (A student can enroll in many courses, and a course can have
many students).

2. Participation Constraint

• Defines whether all instances of an entity must participate in a relationship.


• Specifies if an entity's participation is mandatory or optional.
Types of Participation Constraints:

1. Total Participation → Every instance of the entity must participate in the relationship.
o Example: Every student must be enrolled in at least one course.
2. Partial Participation → Some instances of the entity may participate, but not all.
o Example: Not every faculty member is assigned to research work.

Example Diagram of Relationship Constraints


University Database Example

• Entities: Student, Course


• Relationship: Enrolls
• Constraints:
o Cardinality: Many-to-Many (A student can enroll in multiple courses, and a course can have
multiple students).
o Participation: Total for students (Every student must enroll in at least one course), Partial
for courses (Some courses might not have any students).

mathematica
(Student) (M) ---- Enrolls ---- (N) (Course)
| |
Total Partial

b. Consider a database for a simple online shopping system. In this system, each customer has attributes: Customer
ID, First Name, Last Name, and Email. Each product has attributes: Product ID, Product Name, and Price. Each
order has attributes: Order ID, Order Date, and Total Amount. A customer can place multiple orders, and each
order is placed by a single customer. Each order can contain multiple products, and each product can be part of
multiple orders.

Required:

i. Create an E-R diagram that represents the relationships among these entities.
ii. Identify the primary key for each entity. iii.
iii. Specify the cardinality of the relationships between the entities.

Ans: E-R Diagram (Textual Representation)

Do yourself

ii. Primary Keys for Each Entity

1. Customer: Customer ID
2. Product: Product ID
3. Order: Order ID
4. Order_Product (junction table for many-to-many relationship): Composite primary key (Order ID, Product
ID)

iii. Cardinality of Relationships

1. Customer to Order:
o One-to-Many (1:M)
o One customer can place many orders
o Each order is placed by exactly one customer
2. Order to Product:
o Many-to-Many (M:N) - implemented via the junction table Order_Product
o Each order can contain multiple products
o Each product can appear in multiple orders

The junction table Order_Product would typically include additional attributes like quantity ordered for each product
in an order.

Question no-6

a. What is normalization in DBMS? Why is the fifth normal form better than the fourth one?

Ans: Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity. It
involves dividing large tables into smaller ones and defining relationships between them to minimize data anomalies
such as insertion, update, and deletion anomalies.

Normalization is performed through a series of normal forms (1NF, 2NF, 3NF, BCNF, 4NF, 5NF, etc.), each
addressing specific redundancy and dependency issues.

Why is the Fifth Normal Form (5NF) Better Than the Fourth (4NF)?

• Fourth Normal Form (4NF): Eliminates multi-valued dependencies to ensure that a table contains only
independent multi-valued facts. However, it does not resolve all types of redundancy, particularly those
caused by join dependencies.
• Fifth Normal Form (5NF) (Project-Join Normal Form - PJNF): Ensures that no non-trivial join
dependency exists in the table, meaning the data should not require recombination of multiple tables to
preserve meaning. It is particularly useful in cases where a table can be decomposed into multiple smaller
tables without losing data integrity.

Thus, 5NF is better than 4NF because it eliminates join dependencies that can still cause redundancy even after
4NF is applied. This results in a more optimized database design.

b. Suppose you are creating a database of the employees in your organization. Now, write the SQL commands for
completing the following tasks:
I. Create a database named 'Company'. Under this database, create a table named 'Staff and insert these columns:
ID, First _Name, Last_Name, Department, Salary. ID will be the primary key and will be automatically
incremented. Set the default value of Department to 'Not Allocated'.

Ans: I. Create the 'Company' database and 'Staff' table


sql
CREATE DATABASE Company;
USE Company;

CREATE TABLE Staff (


ID INT AUTO_INCREMENT PRIMARY KEY,
First_Name VARCHAR(50) NOT NULL,
Last_Name VARCHAR(50) NOT NULL,
Department VARCHAR(50) DEFAULT 'Not Allocated',
Salary INT NOT NULL
);

II. Insert the following data to the table 'Staff:


ID FIRST NAME LAST NAME DEPARTMENT SALARY
1 LIONEL MESSI ACC 50000
2 CRISTIANO RONALDO MKT 40000
3 KYLIAN MBAPPE IT 30000
1. Create a new column named Full_Name and combine the values of First_ Name and Last_Name columns there.
2. Sort the rows based on the First_Name column alphabetically.
3. Select the employees whose last names starts with the alphabet 'M'.
4. Find out the average salary of the employees.
5. Select the employees having salaries of more than or equal to Tk. 40,000.

Ans: II. Insert the given data into the 'Staff' table
sql
INSERT INTO Staff (First_Name, Last_Name, Department, Salary)
VALUES
('LIONEL', 'MESSI', 'ACC', 50000),
('CRISTIANO', 'RONALDO', 'MKT', 40000),
('KYLIAN', 'MBAPPE', 'IT', 30000);

1. Add a new column named 'Full_Name' and update it


sql
ALTER TABLE Staff ADD Full_Name VARCHAR(100);

UPDATE Staff
SET Full_Name = CONCAT(First_Name, ' ', Last_Name);

2. Sort rows based on the 'First_Name' column alphabetically


sql
SELECT * FROM Staff ORDER BY First_Name ASC;

3. Select employees whose last names start with 'M'


sql
SELECT * FROM Staff WHERE Last_Name LIKE 'M%';

4. Find the average salary of employees


sql
SELECT AVG(Salary) AS Average_Salary FROM Staff;

5. Select employees with salaries of Tk. 40,000 or more


sql
SELECT * FROM Staff WHERE Salary >= 40000;

27th final (SQL-related question)

Question no 3

a) What is an attribute? Extend appropriate examples of attributes in the context of different types of databases.

Ans: an attribute refers to a characteristic or property of an entity. It defines the type of data that can be
stored for an entity in a database.

Types of Attributes in Databases


1. Simple (Atomic) Attribute
o These attributes cannot be further divided.
o Example: In a student database, Student_ID or Name are simple attributes.
2. Composite Attribute
o These attributes can be divided into smaller sub-parts.
o Example: The Full_Name attribute can be divided into First_Name and Last_Name. The
Address attribute can be divided into Street, City, State, and ZIP_Code.
3. Single-Valued Attribute
o These attributes have only one value for a particular entity.
o Example: A Date_of_Birth attribute in an employee database will have a single value for
each employee.
4. Multi-Valued Attribute
o These attributes can have multiple values for a single entity.
o Example: A Phone_Number attribute for a person might have multiple values (Home, Work,
and Mobile).
5. Derived Attribute
o These attributes are not stored directly in the database but are derived from other attributes.
o Example: Age can be derived from the Date_of_Birth.
6. Stored (Source) Attribute
o These attributes are stored physically in the database and used to derive other attributes.
o Example: Date_of_Birth is a stored attribute that is used to derive Age.
7. Complex Attribute
o These attributes are a combination of multivalued and composite attributes.
o Example: The Educational_Qualification attribute, which can store multiple degrees
(Bachelor's, Master's), and each degree can have sub-attributes (Degree_Name,
University, Year_of_Completion).

Examples in Databases

1. Relational Database (RDBMS - MySQL, PostgreSQL)


o Employee (Emp_ID, Name, Address, Phone_Number, Date_of_Birth, Age)
o Name (Simple), Address (Composite), Phone_Number (Multi-valued), Age (Derived from
Date_of_Birth).

b) What is a data model? Explain the concept of the E-R Model. Use an ER diagram to depict the elements of the E-R
Model.

Ans: What is a Data Model?

A data model is a conceptual framework that defines how data is structured, stored, and manipulated within
a database. It provides a systematic way to represent real-world entities and their relationships in a database.

Types of Data Models

1. Hierarchical Model – Data is organized in a tree-like structure.


2. Network Model – Uses graph-like structures with multiple parent-child relationships.
3. Relational Model – Represents data in tables with rows and columns.
4. Entity-Relationship (E-R) Model – Represents data using entities, attributes, and relationships in a
graphical form.

Concept of the E-R Model


The Entity-Relationship (E-R) Model is a high-level conceptual model used to design databases by
visually representing real-world objects (entities) and their relationships.

Key Elements of the E-R Model

1. Entities – Objects in the real world that have attributes.


o Example: Student, Teacher, Course.
2. Attributes – Characteristics of an entity.
o Example: Student has attributes like Student_ID, Name, and Age.
3. Primary Key – A unique attribute that identifies an entity.
o Example: Student_ID uniquely identifies each student.
4. Relationships – Associations between two or more entities.
o Example: A Student "enrolls in" a Course.
5. Cardinality – Defines the number of instances of one entity related to another.
o Example: One Student can enroll in many Courses (One-to-Many relationship).

ER Diagram Representation
Here is an ER Diagram illustrating the relationship between Student, Course, and Instructor:

• Entities: Student, Course, Instructor


• Relationships:
o A Student enrolls in a Course (Many-to-Many)
o An Instructor teaches a Course (One-to-Many)

ER Diagram for Student-Course System

c) Explain various Mapping Cardinalities that may be used in the case of entity relationships. Use appropriate examples
to represent each cardinality in a hypothetical scenario.

Ans: see for more info 28th batch final Q-3 0f 2

ardinality Type Description Example

One-to-One (1:1) One entity to one entity Person ↔ Passport

One-to-Many (1:N) One entity to many Teacher → Courses

Many-to-One (N:1) Many entities to one Employees → Department

Many-to-Many (M:N) Many to many Students ↔ Courses

Question no 4

a) What does the JOIN clause do in SQL? Discuss the various types of JOINs.
Ans: 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
between them, usually a foreign key. It allows you to retrieve data from multiple tables in a single query,
especially when the data is split across normalized tables.

Why use JOIN?

To answer queries that involve data from multiple related tables, for example:

“List all employees along with their department names.”

Types of JOINs in SQL


Here are the major types of JOINs with explanations and examples:

1. INNER JOIN

Returns only the rows where there is a match in both tables.

Syntax:

sql
SELECT *
FROM Employees e
INNER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;

Use case:

List all employees along with their department info—but only for those assigned to a department.

2. LEFT JOIN (or LEFT OUTER JOIN)

Returns all rows from the left table, and matched rows from the right table. If no match, NULL is
returned for right-side columns.

Syntax:

sql
SELECT *
FROM Employees e
LEFT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;

Use case:
List all employees, even those who don’t belong to any department.

3. RIGHT JOIN (or RIGHT OUTER JOIN)

Returns all rows from the right table, and matched rows from the left table. If no match, NULL is
returned for left-side columns.

Syntax:

Sql
SELECT *
FROM Employees e
RIGHT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;

Use case:

List all departments, including those that currently have no employees.

5. FULL JOIN (or FULL OUTER JOIN)

Returns all rows when there is a match in either left or right table. Missing matches on either side
return NULLs.

Syntax:

sql
SELECT *
FROM Employees e
FULL OUTER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;

Use case:

List all employees and departments, whether or not they match with each other.

5. CROSS JOIN

Returns the Cartesian product of both tables—every row of Table A joined with every row of Table
B.

Syntax:sql

SELECT *
FROM Products p
CROSS JOIN Categories c;

Use case:

Generate all combinations between two datasets (e.g., all possible product-category pairs).
6. SELF JOIN

A table is joined with itself. Often used to show relationships within the same entity (like manager-
employee).

Syntax:

sql
SELECT e1.Name AS Employee, e2.Name AS Manager
FROM Employees e1
JOIN Employees e2
ON e1.Manager_ID = e2.Employee_ID;

Use case:

Display employees along with their managers.

b) In SQL, what are the uses of the following concepts:

i. HAVING clause
ii. SQL sub-queries
iii. ORDER BY
iv. SQL Aliases

Ans: i. HAVING Clause

The HAVING clause is used to filter the results of groups created by the GROUP BY clause. It acts like a
WHERE clause, but for aggregated data.

Use Case:

To find departments with more than 5 employees.

sql
SELECT Dept_ID, COUNT(*) AS Employee_Count
FROM Employees
GROUP BY Dept_ID
HAVING COUNT(*) > 5;

You use HAVING when you need to filter groups after aggregation (like SUM, COUNT, AVG, etc.).

ii. SQL Sub-queries

A sub-query (or nested query) is a query inside another SQL query. It’s used to compute values or filter
results based on another query.

Use Case:

Find employees who earn more than the average salary.


sql
SELECT Name, Salary
FROM Employees
WHERE Salary > (
SELECT AVG(Salary) FROM Employees
);

Sub-queries can appear in SELECT, FROM, or WHERE clauses, and can return single or multiple values.

iii. ORDER BY

The ORDER BY clause is used to sort the result set by one or more columns, in ascending (ASC) or
descending (DESC) order.

Use Case:

List all employees in descending order of salary.

sql
SELECT Name, Salary
FROM Employees
ORDER BY Salary DESC;

Default sorting is ASC if no direction is specified.

iv. SQL Aliases

Aliases are temporary names assigned to columns or tables to make query results more readable or to
simplify complex expressions.

Use Case:

Rename a column and table in the result for clarity.

sql
SELECT e.Name AS Employee_Name, d.Dept_Name AS Department
FROM Employees e
JOIN Departments d ON e.Dept_ID = d.Dept_ID;

c) Write down the SQL commands to be used for each of the given scenarios:

i. Create a table called 'employee information' that has as attributes- employee id, employee name and employee
location.
ii. Find out the 'sales, 'sales person', 'trnx _id' and 'region' from the 'transactions" table where the sales amount is greater
than BDT. 10,000.
iii. Make a query and display the 'customer name', 'address', 'postal code', 'country' from the customer information' table
and also order the outpul according to the customer name in ascending alphabetical order.
iv. Add a new. column called 'customer review' to the 'customer information' table. Consider that the reviews are given
on a scale from 1 to 5 stars
v. Make an entry of record into the employee information table created in (i). Use hypothetical values for data insertion.
vi. Make a query to find out and show 'customer name', 'order id', 'region', 'quantity sold' and 'amount' where the amount
sold is more than BDT. 5,000 and the region is DHAKA. Limit the results to the first 10 entries.
Ans: . Create a table called 'employee_information'
sql
CREATE TABLE employee_information (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100),
employee_location VARCHAR(100)
);

Use underscores (_) instead of spaces in table or column names for better readability and compatibility.

ii. Find 'sales', 'sales_person', 'trnx_id', and 'region' where sales > BDT 10,000
sql
SELECT sales, sales_person, trnx_id, region
FROM transactions
WHERE sales > 10000;

This assumes the sales column contains numeric values (like BDT amounts).

iii. Display customer details ordered by customer name


sql
SELECT customer_name, address, postal_code, country
FROM customer_information
ORDER BY customer_name ASC;

ASC is optional since ascending is the default order.

iv. Add a new column 'customer_review' to the 'customer_information' table


sql
ALTER TABLE customer_information
ADD customer_review INT CHECK (customer_review BETWEEN 1 AND 5);

Adds validation to ensure reviews are only between 1 and 5 stars.

v. Insert a record into the 'employee_information' table


sql
INSERT INTO employee_information (employee_id, employee_name, employee_location)
VALUES (101, 'Ayesha Rahman', 'Chattogram');

You can change the values as per your scenario.

vi. Query with filter and LIMIT on sales over BDT 5,000 in DHAKA
sql
SELECT customer_name, order_id, region, quantity_sold, amount
FROM orders
WHERE amount > 5000 AND region = 'DHAKA'
LIMIT 10;

Make sure your table name is orders (or update it if named differently). LIMIT restricts output to first
10 rows.

Question no 5

a) What is Data Manipulation Language? Describe three basic commands of SQL with the help of example.

Ans: 28th batch final question 2 (a)

b) Define a Relational Database Management System and explain how it organizes data.

Ans: A Relational Database Management System (RDBMS) is a type of database management system
that stores data in the form of tables (also called relations). It allows users to create, update, manage, and
query data using Structured Query Language (SQL).

Key Features of RDBMS:

• Data is organized into tables (relations).


• Tables consist of rows (records) and columns (attributes).
• Each table has a primary key to uniquely identify rows.
• Tables can be related through foreign keys.
• Supports ACID properties (Atomicity, Consistency, Isolation, Durability).
• Data can be easily queried and joined across multiple tables.

How RDBMS Organizes Data

Let’s break it down step-by-step:

1. Tables (Relations)

Data is stored in structured tables. Each table represents one entity (e.g., Students, Orders, Products).

Student_ID Name Age


101 Ayesha 20
102 Rahul 22

2. Columns (Attributes)

Each column in a table represents a specific attribute of the entity.

• Student_ID → unique identifier (primary key)


• Name, Age → attributes of the student
3. Rows (Records/Tuples)

Each row represents a single record or instance of that entity.

Example: A row in the Students table represents one student’s complete info.

4. Keys

• Primary Key: Uniquely identifies a row in a table.


• Foreign Key: Refers to the primary key of another table to establish a relationship

c) List the three basic operations in Relational Database Management System and explain them with example. (28th
batch mid)

Ans: 1. SELECT Operation (σ)


The SELECT operation is used to retrieve rows from a table that satisfy a specific condition.
It is used for filtering records.

Example:
sql
SELECT * FROM Employees
WHERE department = 'Sales';

This retrieves all employees who work in the Sales department.

2. PROJECT Operation (π)


The PROJECT operation retrieves specific columns (attributes) from a table.
It is used to eliminate unnecessary data from the output.

Example:
sql
SELECT employee_name, salary FROM Employees;

This returns only the employee names and their salaries, not the full table.

3. JOIN Operation (⨝)


The JOIN operation combines rows from two or more related tables based on a common attribute, typically
a foreign key.

Example:
sql
SELECT e.employee_name, d.department_name
FROM Employees e
JOIN Departments d
ON e.department_id = d.department_id;

This returns a list of employees along with their respective department names, by joining the Employees
and Departments tables.

26th final (SQL-related question)

Question no 1

a) What is a query language? Discuss its use in database management.

Ans: A query language is a specialized language used to communicate with a database, primarily to
retrieve, manipulate, and manage data stored in it. The most widely used query language for relational
databases is SQL (Structured Query Language).

Purpose of a Query Language in Database Management

A query language helps users:

1. Retrieve Data
o Allows fetching specific data using commands like SELECT.
o Example:

sql
CopyEdit
SELECT name, salary FROM Employees WHERE department = 'HR';

2. Insert, Update, and Delete Data


o Modify or add new data in tables using INSERT, UPDATE, DELETE.
3. Create and Manage Database Objects
o Create tables, views, indexes using CREATE, ALTER, DROP.
4. Control Access and Security
o Manage permissions using GRANT and REVOKE.
5. Perform Aggregations and Calculations
o Use functions like COUNT(), SUM(), AVG() to analyze data.

Importance in Database Management

Function Description
Data Retrieval Extract only the data you need, even from multiple tables
Data Manipulation Change, insert, or remove data safely and efficiently
Data Definition Define the structure (schema) of the database
Access Control Limit who can view or edit specific data
Data Analysis & Reporting Summarize and filter data for business insights
Common Query Language: SQL

SQL is the industry standard for relational databases and supports:

• DML (Data Manipulation Language) – SELECT, INSERT, UPDATE, DELETE


• DDL (Data Definition Language) – CREATE, ALTER, DROP
• DCL (Data Control Language) – GRANT, REVOKE
• TCL (Transaction Control Language) – COMMIT, ROLLBACK

Example SQL Query:


sql
SELECT customer_name, order_id, total_amount
FROM orders
WHERE total_amount > 5000
ORDER BY customer_name;

Retrieves customer orders where the amount is more than 5000 and sorts them by customer name.

b) Discuss how SQL came to be. What is meant by an SQL dialect?

Ans: The Origins of SQL

• SQL (Structured Query Language) was developed in the 1970s at IBM.


• It was originally called SEQUEL (Structured English Query Language), designed for querying and
manipulating data stored in IBM’s System R—a prototype of a relational database.

Key Milestones:

Year Event
1970 Edgar F. Codd published the relational model concept in a research paper.
1974 Donald D. Chamberlin and Raymond F. Boyce at IBM created SEQUEL.
Late 1970s SEQUEL was renamed to SQL due to a trademark conflict.
1980s Oracle (then Relational Software Inc.) launched the first commercial SQL-based RDBMS.
1986 SQL became a standard by ANSI (American National Standards Institute).
1987 ISO adopted SQL as a standard.

Why SQL Became Popular

• Easy to learn (uses English-like syntax).


• Powerful enough for complex queries.
• Became the industry standard for relational database access.

What is an SQL Dialect?


An SQL dialect refers to the flavor or variation of SQL used by different RDBMS vendors, with slight
changes in syntax, functions, or features—though the core SQL commands (like SELECT, INSERT, UPDATE)
are the same.

Why Dialects Exist?

Each database system adds its own extensions to improve performance, add features, or optimize
functionality beyond standard SQL.

Examples of SQL Dialects

RDBMS SQL Dialect Name Unique Features


MySQL MySQL SQL LIMIT, AUTO_INCREMENT
PostgreSQL PostgreSQL SQL Advanced JSON and array support
Oracle PL/SQL (Procedural SQL) Procedural features like loops and triggers
SQL Server T-SQL (Transact-SQL) TOP, error handling, procedural code
SQLite SQLite SQL Lightweight, file-based, flexible typing

c) Explain in detail about Relational Database Management Systems (RDBMS). Mention some of the widely used
RDBMS around the world. Why is there a need for NoSQL platforms?

Ans: A Relational Database Management System (RDBMS) is a type of database management software
that stores data in structured tables (relations). These tables are made up of rows (records) and columns
(attributes).

RDBMS allows users to:

• Create, manage, and access data efficiently.


• Use SQL (Structured Query Language) to interact with the database.
• Define relationships between tables using keys (primary and foreign).
• Enforce data integrity and constraints.

Popular RDBMS Around the World

RDBMS Description
MySQL Open-source, widely used in web applications (PHP, WordPress).
PostgreSQL Advanced features, open-source, supports JSON, GIS.
Oracle DB Commercial RDBMS used in enterprise-level applications.
Microsoft SQL Server Popular for Windows-based systems and enterprise software.
SQLite Lightweight, file-based RDBMS used in mobile and embedded applications.

Why is There a Need for NoSQL Platforms?

While RDBMS works great for structured data, it has limitations when dealing with:

Limitations of RDBMS:
• Difficult to scale horizontally (e.g., across multiple servers).
• Poor performance with very large volumes of unstructured/semi-structured data (e.g., logs, images,
JSON).
• Not flexible with changing schema or dynamic data.

Enter NoSQL (Not Only SQL)

NoSQL databases are designed to handle:

• Big Data
• Unstructured or semi-structured data
• Scalability and high availability

Types of NoSQL Databases:

Type Example Usage Example


Document MongoDB, CouchDB JSON-like documents (e.g., blog posts, user profiles)
Key-Value Redis, DynamoDB Caching, session storage
Column Store Cassandra, HBase High-speed analytics and big data
Graph Neo4j, ArangoDB Social networks, recommendation engines

Question no 3

a) What does the JOIN clause do in SQL? Discuss the various types of JOINs.
b) Write down the SQL commands to be used for each of the given scenarios:
vii. Create a table called 'employee information' that has as attributes- employee id, employee name and employee
location.
viii. Find out the 'sales, 'sales person', 'trnx _id' and 'region' from the 'transactions" table where the sales amount is greater
than BDT. 10,000.
ix. Make a query and display the 'customer name', 'address', 'postal code', 'country' from the customer information' table
and also order the outpul according to the customer name in ascending alphabetical order.
x. Add a new. column called 'customer review' to the 'customer information' table. Consider that the reviews are given
on a scale from 1 to 5 stars
xi. Make an entry of record into the employee information table created in (i). Use hypothetical values for data insertion.
xii. Make a query to find out and show 'customer name', 'order id', 'region', 'quantity sold' and 'amount' where the amount
sold is more than BDT. 5,000 and the region is DHAKA. Limit the results to the first 10 entries.

Ans: same as 27th batch final Q-4

Question no 6

a) Why Non- Relational Databases are useful? Briefly explain.

Ans: Non-Relational Databases, also known as NoSQL databases, are useful because they are designed to
handle large volumes of diverse, unstructured, or semi-structured data in ways that traditional relational
databases (RDBMS) struggle with.

Key Reasons Why Non-Relational Databases Are Useful:


1. Flexibility with Data Structure

• No fixed schema – you can store different fields in different records.


• Great for handling dynamic or evolving data models (e.g., user profiles with optional fields).

Example: A product catalog where some products have sizes and others have colors – NoSQL can handle
this easily.

2. High Scalability

• NoSQL databases are built for horizontal scaling – can easily be distributed across multiple servers.
• Useful for big data applications and real-time processing.

Example: Facebook, Amazon, Netflix use NoSQL to manage millions of users/data points across distributed
systems.

3. Optimized for Specific Use Cases

Different types of NoSQL databases serve specialized purposes:

Type Ideal For Example


Document DB JSON-like data (flexible records) MongoDB
Key-Value Fast lookups, caching Redis, DynamoDB
Columnar DB Big data analytics Cassandra, HBase
Graph DB Network relationships Neo4j, ArangoDB

4. Better Performance with Big or Unstructured Data

• Designed to store massive volumes of unstructured data like logs, images, videos, JSON.
• Supports fast read/write operations at scale.

5. Ideal for Real-Time Applications

• NoSQL databases are used in applications that require real-time analytics, personalization,
messaging, etc.

b) Define and describe Entity- Relationship Diagram and explain its role in database design.

Ans: see 29th batch mid Q-4

c) Describe Normalization and Referential Integrity and explain how they contribute to a well-designed
relational database.
Ans: Normalization is the process of organizing data in a relational database to reduce data redundancy and
improve data integrity. It involves dividing large tables into smaller, related tables and defining relationships between
them.

Goals of Normalization:

• Eliminate duplicate data


• Ensure data consistency
• Make updates, inserts, and deletes more efficient
• Improve database performance and design

Benefits of Normalization

• Avoids update anomalies


• Saves storage space
• Makes database more maintainable
• Ensures data accuracy

Referential Integrity ensures that relationships between tables remain consistent. It means that a foreign
key in one table must either be null or match a primary key in another table.

Example:

Suppose you have two tables:

• Customers (Customer_ID, Customer_Name)


• Orders (Order_ID, Customer_ID, Amount)

Here, Customer_ID in Orders is a foreign key referring to Customer_ID in Customers.

Referential integrity ensures that:

• You can’t insert an order with a Customer_ID that doesn't exist in Customers.
• You can’t delete a customer if there are orders referencing them (unless handled).

How Referential Integrity Helps:

• Prevents orphan records (e.g., orders with no existing customer).


• Maintains logical connections between tables.
• Improves reliability and trust in data.

How They Contribute to a Well-Designed Database:

Feature Contribution to Design


Normalization Clean structure, no redundant data, efficient updates
Referential
Reliable relationships, consistent data, accurate joins
Integrity
Feature Contribution to Design
Ensures data integrity, efficiency, and logical structure of a relational database
Combined Benefit
system

Solution prepared by Iftekhar (29th ) with help of AI and materials provided by teachers

You might also like