0% found this document useful (0 votes)
23 views38 pages

DBMS NJNN

knjhbjhb

Uploaded by

KIRAT PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views38 pages

DBMS NJNN

knjhbjhb

Uploaded by

KIRAT PATEL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

DBMS

Q-1 What is DBMS? List out applications of DBMS.

Ans

• Data – fact/meaningful information that can be recorded or stored


Example :- person name , age ,gender and weight etc .
• Database – collection of logically related data
Example books database in library, student database in university etc.
• Management – Manipulation, searching and security of data
Example viewing result in GTU website, searching exam papers in GTU
website
• System – Program or tools used to manage database
Example:- SQL server studio Express, Oracle
• DBMS – A Database Management system is a software for creating and
managing database
• DBMS is a computerized record-keeping system.
• Database Management System (DBMS) is a software designed
to define, manipulate, retrieve and manage data in a database.
e.g. MS SQL Server, Oracle, My SQL, SQLite, MongoDB etc.

➢ Application of DBMS
1. E-Commerce
2. Online television streaming
3. Social media
4. Banking & insurance
5. Airline& Railway
6. Universities and colleges /schools
7. Human Resource Department
8. Payroll Management
9. Hospitals and Medical Stores
10. Government organizations

Q-2 Draw and explain the three-level architecture of DBMS.


DBMS

ans
The 3-tier architecture is a commonly used architectural approach in
Database Management Systems (DBMSs) for the design and development
of applications that work with databases. The 3-tier architecture divides an
application’s components into three tiers or layers. Each layer has its own
set of responsibilities.

DBMS 3-Tier architecture divides the complete system into three inter-
related but independent modules as shown below
DBMS

Q-3 State how an Entity-Relationship (ER) model represents real-world entities.


Ans

• ER model stands for an Entity-Relationship model. It is a high-level data


model. This model is used to define the data elements and relationship for a
specified system.
• It develops a conceptual design for the database. It also develops a very
simple and easy to design view of data.
• In ER modeling, the database structure is portrayed as a diagram called an
entity-relationship diagram.
DBMS

Q-4 Define Data Abstraction and explain different levels of data abstraction.

• Database systems are made-up of complex data structures.


• To make database system more efficient, developers hide
internal irrelevant details from users.
• Since many database-system users are not computer trained,
so developers hide the complexity from users through several
levels of abstraction to simplify users.
• This process of hiding irrelevant details from user is called
data abstraction.
➢ Internal Level
• It describes how a data is stored on the storage device.
• Deals with physical storage of data.
- Structure of records on disk - files, pages, blocks
- Indexes and ordering of records
• Internal view is described by the internal schema.
• The compiler hides details of this level from programmers.
• Similarly, the database system hides many of the lowest-level
storage details from database programmers.
• Database administrators, on the other hand, may be aware of
certain details of the physical organization of the data
➢ Logical level
• It hides low level complexities of physical storage.
• For Example, STUDENT database may contain STUDENT and
COURSE tables which will be visible to users but users are
unaware about their storage.
• Programmers using a programming language work at this
level of abstraction.
• Similarly, database administrators usually work at this level
of abstraction.
➢ External Level
• It describes only part of the entire database that an end user
concern or How data are viewed by each user.
• End users need to access only part of the database rather than
the entire database.
• Different user needs different views of the database, so there
DBMS

can be many views in a view level abstraction of the database.


• Used by end users and application programmers.

Q-5 Explain Data Independence.

Ans

Types of data independence


1. Physical data independence
2. Logical data independence

➢ Physical data
• Physical data independece is the ability to modify the physical schema
without requiring any change in logical schema and application program.
• Modification at the internal levels are occasionally necessary to improve
performance
DBMS

• Compared to logical independence it is easy to achieve physical data


independence
• Example
• Change in compression techniques, hashing algorithm storage devices,
location of database.
Q-6 Explain the DBMS languages with examples: DDL, DML, and DCL.
Ans Database languages are used to store, retrieve and update data in a database.
There are several such languages that can be used for this purpose; one of them is
SQL (Structured Query Language).
1. DDL (data definition language)
2. DML (Data manipulation language)
3. DCL (Data control Language)

➢ DDL (data definition language)


DDL statement are used to alter/modify a database or table structure and
schema its command are auto-committed so, the changes are saved in the
database permanently
• CREATE – is used to create the database or its objects (like table, index,
function, views, store procedure and triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including all
spaces allocated for the records are removed.
• RENAME –is used to rename an object existing in the database.

➢ DML ( Data Manipulation Language)


These are basic operation such as selecting records from a table inserting new
records, deleting unnecessary records, and updating /modifying existing records.
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a table.
• DELETE – is used to delete records from a database table.
• SELECT – is used to retrieve data from the a database.
DBMS

➢ DCL (Data control Language)


DCL includes commands such as GRANT and REVOKE which mainly deals
with the rights, permissions and other controls of the database system.
• GRANT-gives user’s access privileges to database.
• REVOKE-withdraw user’s access privileges given by using the GRANT
Command

Q-7 Draw an E-R diagram for the Library Management System.

Ans
DBMS

Q- 8 What are the constraints in DBMS? explain with a proper example.

ANS In a Database Management System (DBMS), constraints are rules applied to


the data in a table to ensure accuracy, reliability, and consistency. These constraints
restrict the types of data that can be entered into a database, thus maintaining data
integrity. Here are the key types of constraints in DBMS, with examples:
DBMS

Example :
1. NOT NULL Constraint CREATE TABLE Students ( Student
ID INT, Name VARCHAR(100) NOT
Ensures that a column cannot have a NULL );
NULL value.

Example:-
2. UNIQUE Constraint CREATE TABLE Employees (
EmployeeID INT UNIQUE,
Ensures that all the values in a column Name VARCHAR(100)
are unique across the database, );
meaning no two rows can have the
same value in that column.

Example
3. PRIMARY KEY Constraint CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
Combines the NOT NULL and UNIQUE OrderDate DATE,
constraints. It ensures that the column CustomerID INT
(or combination of columns) that is the );
primary key has unique, non-null
values. A table can have only one
primary key.

Example
4. FOREIGN KEY Constraint CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
Ensures that the value in one column OrderDate DATE,
matches the value in another column CustomerID INT,
(usually in a different table). It FOREIGN KEY (CustomerID)
establishes a relationship between two REFERENCES
tables by linking a column in one table Customers(CustomerID)
to the primary key in another table. );
DBMS

CREATE TABLE Products (


5. CHECK Constraint ProductID INT,
ProductName VARCHAR(100),
Ensures that all values in a column Price DECIMAL(10, 2),
satisfy a specific condition. CHECK (Price > 0)
);

Example
DEFAULT Constraint CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Provides a default value for a column Name VARCHAR(100),
when no value is specified. JoinDate DATE DEFAULT
CURRENT_DATE
);

CREATE TABLE Customers (


AUTO_INCREMENT Constraint CustomerID INT
AUTO_INCREMENT,
Automatically generates a unique number Name VARCHAR(100),
for a column when a new record is
PRIMARY KEY (CustomerID)
inserted, typically used for primary keys.
);

Q- 9 Define Primary key, foreign key, NOT NULL constraints and referential integrity
constraint?

• Primary Key: A column (or set of columns) that uniquely identifies each
row in a table. It cannot have NULL values and must be unique for each
record.
• Foreign Key: A column (or set of columns) that establishes a link between
data in two tables by referring to the primary key in another table. It ensures
that a value in one table must correspond to a value in another.
• NOT NULL: Ensures that a column cannot have NULL values, meaning
every row must contain a valid (non-null) value in that column.
• Referential Integrity: A rule that ensures foreign key values in one table
correspond to primary key values in another table, maintaining valid
relationships between tables and preventing orphaned records.

Q-10 Explain the Network model and Relational model in brief.


DBMS

Ans

Network Model:

• Structure: The Network model organizes data using a graph structure, with
records represented as nodes and relationships as edges. Each record can
have multiple parent and child records, forming a many-to-many
relationship.
• Representation: Data is stored in a hierarchical structure, but unlike the
hierarchical model, a child can have multiple parents.
• Example: Consider an employee and project database where an employee
can work on multiple projects, and a project can have multiple employees.
The Network model represents this as a complex, interconnected graph.

Relational Model:

• Structure: The Relational model organizes data into tables (relations),


where each table consists of rows (tuples) and columns (attributes). Each
table has a primary key to uniquely identify rows.
• Representation: Data is stored in a tabular form, and relationships between
tables are established using foreign keys.
• Example: An Employees table and a Departments table can be linked
using a DepartmentID foreign key in the Employees table, referring to
the primary key in the Departments table.

Q- 11 Describe the difference between Tuple Relational Calculus and Domain


Relational Calculus.

Ans

Tuple Relational Calculus Domain Relational Calculus

Works with tuples (rows) of a relation Works with individual fields (domains)
(table). of a relation.
DBMS

Specifies conditions for retrieving Specifies conditions for retrieving


entire tuples that satisfy a given specific attributes (domains) that satisfy
predicate a predicate.
Syntax:- {T | P(T)}, where T is a Syntax:- {<d1, d2, ..., dn> |
tuple variable and P(T) is a predicate P(d1, d2, ..., dn)}, where d1,
that the tuple T must satisfy. d2, ..., dn are domain variables.
Example: Retrieve tuples where age > Example: Retrieve employee names
30: where age > 30:
{T | T ∈ Employees ∧ T.age > {<Name> | ∃Age
30} (Employees(Name, Age) ∧ Age >
30)}

Q-12 Explain the working of the Cartesian Product operation with an appropriate
Table.

Ans The Cartesian Product is a fundamental operation in set theory, database


systems (SQL), and mathematics. It combines two sets (or relations) to produce all
possible ordered pairs from those sets.

Definition:

If you have two sets AAA and BBB, the Cartesian Product of AAA and BBB,
denoted as A×BA \times BA×B, is the set of all possible pairs (a,b)(a, b)(a,b),
where a∈Aa \in Aa∈A and b∈Bb \in Bb∈B.

Formally:

A×B={(a,b)∣a∈A and b∈B}A \times B = \{ (a, b) | a \in A \text{ and } b \in B


\}A×B={(a,b)∣a∈A and b∈B}

Example:

Let’s consider two sets (or tables):

• Set A (Students):
Student ID Name
1 Alice
DBMS

2 Bob
• Set B (Courses):
Course
Course ID
Name
101 Math
102 Science

Cartesian Product: A×BA \times BA×B

Course
Student ID Name Course ID
Name
1 Alice 101 Math
1 Alice 102 Science
2 Bob 101 Math
2 Bob 102 Science

Explanation:

• The Cartesian Product takes each row from Set A and pairs it with every row
from Set B.
• For example, Alice (Student ID 1) is paired with both Math (Course ID 101)
and Science (Course ID 102).
• Similarly, Bob (Student ID 2) is paired with both Math and Science.

Key Points:

1. If Set A has mmm elements and Set B has nnn elements, the resulting
Cartesian Product will have m×nm \times nm×n elements.
2. In database terms, the Cartesian Product can create large results if the sets
are large, so it should be used with caution when the tables have many rows.

The Cartesian Product is typically followed by a selection or condition to filter the


relevant rows (e.g., via JOIN operations in SQL).
DBMS

Q-13 List the relational algebra operators. Discuss any one such algebra operator
with suitable examples.
Ans

Relational algebra is a procedural query language used to retrieve data from


relational databases. It consists of a set of operations that take one or two relations
as input and produce a new relation as output.

Relational Algebra Operators:

1. Selection (σ) – Selects rows that satisfy a given predicate.


2. Projection (π) – Selects specific columns from a relation.
3. Union ( ∪ ) – Combines the result of two relations, eliminating duplicates.
4. Set Difference ( − ) – Returns tuples that are in one relation but not in
another.
5. Cartesian Product ( × ) – Combines every tuple of one relation with every
tuple of another.
6. Rename (ρ) – Renames the attributes of a relation.
7. Intersection ( ∩ ) – Returns tuples that are common to both relations.
8. Join (⨝) – Combines related tuples from two relations based on a condition.
a. Types of joins: Inner Join, Outer Join, Natural Join, etc.
9. Division (÷) – Used to find tuples in one relation that are associated with all
tuples in another relation.
Example

EMP id Name Department salary


101 Alice HR 50000
102 Bob IT 60000
103 carol IT 55000
104 Dave Finance 62000
DBMS

Result

Emp id Name department salary


102 BOB IT 60000
103 carol IT 55000

Q-14 Explain Armstrong's axioms.

Ans Armstrong's axioms are a set of inference rules used in relational database
theory to derive all functional dependencies (FDs) on a relational database schema.
These rules are sound (only generate correct functional dependencies) and complete
(can derive all functional dependencies that hold in the schema). They were
introduced by William W. Armstrong in 1974.

Here are the three basic axioms, along with their meanings:

1. Reflexivity (Trivial Dependency)

If Y⊆XY \subseteq XY⊆X, then X→YX \to YX→Y.

• Meaning: If an attribute set YYY is a subset of another set XXX, then XXX
functionally determines YYY. This is called a trivial dependency because the
set of attributes trivially determines its own subset.

2. Augmentation (Extension)

If X→YX \to YX→Y, then XZ→YZXZ \to YZXZ→YZ for any ZZZ.

• Meaning: If XXX determines YYY, then adding another attribute set ZZZ to
both XXX and YYY still results in a valid functional dependency. This
essentially says that adding more attributes to both sides of a dependency
doesn't invalidate it.
DBMS

3. Transitivity (Chain Rule)

If X→YX \to YX→Y and Y→ZY \to ZY→Z, then X→ZX \to ZX→Z.

• Meaning: If XXX functionally determines YYY, and YYY functionally


determines ZZZ, then XXX must functionally determine ZZZ. This allows you
to chain dependencies together.

Additional Rules Derived from Armstrong's Axioms

Using the three basic axioms, you can derive some additional rules:

• Union: If X→YX \to YX→Y and X→ZX \to ZX→Z, then X→YZX \to
YZX→YZ.
• Decomposition: If X→YZX \to YZX→YZ, then X→YX \to YX→Y and X→ZX
\to ZX→Z.
• Pseudotransitivity: If X→YX \to YX→Y and WY→ZW Y \to ZWY→Z, then
XW→ZXW \to ZXW→Z.

These axioms are fundamental to reasoning about functional dependencies and are
crucial for database normalization, which is the process of organizing a database to
minimize redundancy and improve data integrity.

Q-15 Define functional dependency with a simple example.

Ans Let R be a relation schema having n attributes A1, A2, A3,…, An.

Student Roll no. Name SPI BL


101 Raju 8 0
102 Mitesh 7 1
103 Jay 7 0

• Let attributes X and Y are two subsets of attributes of relation R.


DBMS

• If the values of the X component of a tuple uniquely (or functionally)


determine the
• values of the Y component, then there is a functional dependency from X to
Y.
• This is denoted by X → Y (i.e RollNo → Name, SPI, BL).
• It is referred as: Y is functionally dependent on the X or X functionally
determines Y.

Q-16 What is meant by normalization? Write its need. List and discuss various
normalization forms.
Ans
• Normalization is the process of removing redundant data from tables to
improve data. Integrity, scalability and storage efficiency.
• data integrity (completeness, accuracy and consistency of data)
• scalability (ability of a system to continue to function well in a growing
amount of work)
• storage efficiency (ability to store and manage data that consumes the least
amount of space)
What we do in normalization?
• Normalization generally involves splitting an existing table into multiple
(more than one) tables, which can be re-joined or linked each time a query is
issued (executed).
• Normal forms:
➢ 1NF (First normal form)
➢ 2NF (Second normal form)
➢ 3NF (Third normal form)
➢ BCNF (Boyce–Codd normal form)
➢ 4NF (Forth normal form)
➢ 5NF (Fifth normal form)

Q-17 state true or false : any relation schema that satisfies BCNF also satisfies 3NF
DBMS

Ans True.

Any relation schema that satisfies Boyce-Codd Normal Form (BCNF) also satisfies Third
Normal Form (3NF).

This is because BCNF is a stricter form of 3NF. BCNF has more stringent requirements
than 3NF, so if a relation schema satisfies BCNF, it automatically satisfies the conditions
for 3NF as well. However, the reverse is not necessarily true; a schema that satisfies 3NF
may not satisfy BCNF.

Q-18 Construct a relational schema for a database and implement normalization up

to the 3rd Normal Form (3NF).

Ans

Scenario: University Database (tracking Students, Courses, Instructors,


and Enrollments)

1. Unnormalized Form (UNF):

• Contains all information in one table (with redundancy):


student_nam course_cod course_titl instructor_nam
student_id grade
e e e e
1 Alice CS101 Intro to CS Dr. Smith A
2 Bob MATH101 Calculus I Dr. Johnson B

2. First Normal Form (1NF):

• Atomic Values: All fields contain atomic (indivisible) values.


• Remove Repeating Groups.

3. Second Normal Form (2NF):

• Remove Partial Dependencies:


o Separate non-key attributes that don't depend on the entire composite key.
• Break into smaller tables:
DBMS

1. Student: student_id (PK), student_name


2. Course: course_code (PK), course_title
3. Instructor: instructor_id (PK), instructor_name
4. Enrollment: student_id (FK), course_code (FK), grade

4. Third Normal Form (3NF):

• Remove Transitive Dependencies:


o Instructor is related to course, so separate instructor-course relation.
1. Student (student_id, student_name)
2. Course (course_code, course_title)
3. Instructor (instructor_id, instructor_name)
4. Enrollment (student_id, course_code, grade)
5. Teaches (course_code, instructor_id)

Marks Gain Method (for exams):


• Normalization to 3NF earns marks for:
o Identifying entities and dependencies.
o Correct splitting of tables to remove partial and transitive dependencies.
o Final 3NF schema structure without redundancy or update anomalies.

Q- 19 Explain the structure of a B-tree.

Ans
DBMS

The B Tree is a particular m-way tree which can be used to access discs in a

variety of ways. At most m children and m-1 keys can be found in a B-Tree of

order m. One of the main advantages of the B tree is its capacity to store a

large number of keys inside a single node and huge key values while keeping

the tree’s height low.

Need of a B Tree in a Data Structure

The need for B-tree emerged as the demand for faster access to physical

storage media such as a hard disk grew. With a bigger capacity, backup

storage devices were slower. There was a demand for data structures that

reduced the number of disc accesses.

A binary search tree, an AVL tree, a red-black tree, and other data structures

can only store one key in each node. When you need to store a significant

number of keys, the height of such trees grows quite vast, and the time it

takes to access them grows.

B-tree, on the other hand, can store multiple keys inside a single node and

has several child nodes. It considerably reduces the height, allowing for

speedier disk access. B Tree Example


DBMS

Q-20 Explain B-tree and Hashing

Ans

B-tree
A B-tree is a self-balancing tree data structure that maintains sorted data and

allows searches, sequential access, insertions, and deletions in logarithmic time,

making it ideal for databases and file systems. Unlike binary search trees, B-trees

are designed to work efficiently on disk storage, where reading from and writing to

disks is slow compared to accessing data in memory.

Characteristics:

• Multi-level Indexing: Multi-level Indexing: B-trees use a hierarchy of nodes with


multiple keys in each node to organize data.
• Balanced Structure: All leaf nodes are at the same level, ensuring consistent
search times.
• Order mmm: Each node can hold up to m−1m-1m−1 keys and mmm pointers to
child nodes.
• Efficient Search: Searching, inserting, and deleting operations take
O(log⁡n)O(\log n)O(logn) time.

Hashing is a technique used to map data items (keys) to a specific location

or "bucket" in memory using a hash function. Hashing enables efficient data

retrieval by directly accessing the desired record based on the value of the

key, instead of performing a linear or binary search.


DBMS

The efficiency of hashing lies in the fact that the hash function computes the

address or bucket where the data is stored, allowing for constant time

complexity O(1)O(1)O(1) on average for insertions, deletions, and searches

Hash Function

A hash function takes a key as input and produces an integer (hash code)

that maps to a location in the memory or a bucket: h(key)=addressh(key) =

address(key)=address The key is mapped to the bucket using the hash

code, and data can be retrieved directly from that bucket.

Hashing

Static Hashing

Dynamic Hashing

Static Hashing:

In static hashing, the number of buckets in memory is fixed, and this number does

not change during the insertion or deletion of records. A fixed hash function maps

the data to these buckets.

Dynamic Hashing:

Dynamic hashing adjusts the number of buckets dynamically based on data size. It

uses techniques like extendible hashing or linear hashing to grow and shrink the

hash table as needed, efficiently handling data overflow and underflow.

Q-21 Define Static and Dynamic Hashing.

Ans

Static hashing:- in static hashing, the number of buckets in memory is fixed, and this
number does not change during the insertion or deletion of records. A fixed hash function
maps the data to these buckets

Buckets: A predefined number of buckets store records when records exceed bucket
capacity, overflow buckets are used.
DBMS

Hash function : A hash function, say h (key ), maps a search key to a bucket

Dynamic Hashing:- It is a hashing technique that enables users to lookup a dynamic

data set. Means, the data set is modified by adding data to or removing the data from,
on demand hence the name ‘Dynamic’ hashing. Thus, the resulting data bucket keeps
increasing or decreasing depending on the number of records.

In this hashing technique, the resulting number of data buckets in memory is ever-
changing.

Q-22 Explain the steps of query processing with the help of a neat diagram.

Ans
DBMS

Q-23 Describe different join strategies for a query and explain how they affect

Performance.

Ans Here’s a concise breakdown of join strategies and their performance impact:

1. Nested Loop Join (NLJ):


a. How it works: For each row in the outer table, it checks all rows in the inner
table.
b. Performance: Slow for large tables (O(N × M)), better with indexing.
c. Best for: Small tables or indexed inner tables.
2. Hash Join:
a. How it works: Builds a hash table on the smaller table, then probes it with
the larger table.
b. Performance: Efficient for large tables (O(N + M)), but needs memory.
c. Best for: Large, non-indexed tables with equality joins.
3. Merge Join (Sort-Merge):
a. How it works: Sorts both tables and merges them.
b. Performance: O(N + M), slower if sorting is needed.
c. Best for: Pre-sorted or indexed tables.
4. Block Nested Loop Join:
a. How it works: Processes blocks of rows, reducing scans.
b. Performance: Better than simple NLJ, but slower than hash/merge.
c. Best for: Large tables without indexes.
5. Index Join:
a. How it works: Uses indexes on both tables for matching rows.
b. Performance: Fast with proper indexes (O(log N)).
c. Best for: Indexed tables.
DBMS

Key Factors: Table size, indexing, memory, and data sorting dictate which strategy is
optimal.

Q-24 Explain linear search and binary search algorithms for selection operation.

Ans Linear Search and Binary Search are two fundamental algorithms used for searching
elements in a collection, such as an array or list. They differ in their approach and
efficiency.

1. Linear Search:

Description:

• In a linear search, you start from the first element and sequentially check each
element of the list until you find the target element or reach the end of the list.
• It doesn't require the list to be sorted.

Algorithm:

1. Start from the first element.


2. Compare each element with the target value.
3. If the current element matches the target, return its index.
4. If no match is found by the end of the list, return "not found."

Example:

python
Copy code
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
DBMS

return i
return -1 # Target not found

2. Binary Search:

Description:

• In a binary search, the list must be sorted beforehand. The search algorithm works
by repeatedly dividing the search interval in half. It compares the target value with
the middle element of the array.
• If the target is less than the middle element, it searches the left half; if greater, it
searches the right half.

Algorithm:

1. Find the middle element of the sorted array.


2. Compare the middle element with the target.
a. If the target is equal to the middle element, return its index.
b. If the target is smaller, repeat the search on the left half.
c. If the target is larger, repeat the search on the right half.
3. Continue this process until the target is found or the interval becomes empty.

Example:

python
Copy code
def binary_search(arr, target):
low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2 # Find the middle element
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1 # Search the right half
else:
high = mid - 1 # Search the left half
DBMS

return -1 # Target not found

Q-25 Explain linear search and binary search algorithms for selection operation.
Ans
Linear search(A1)
• It scans each blocks and tests all records to see whether they satisfy the selection
Condition .
• Cost of linear search (worst case )=br
• Br denotes number of blocks containing records from relation r
• If the selection condition is there on a (primary) key attribute, then system can
stop searching if the required record is found.
• Cost of linear search (best case)=(br/2)
• If the selection is on non (primary) key attribute then multiple block may
contains required records, then the cost of scanning such blocks need to be
added to the cost estimate.
• Linear search can be applied regardless of
• Selection condition
• Ordering of records inthe file (relation)
• This algorithm is slower than binary search algorithm.
Binary search :-
• Generally this algorithm is sed if selection is an equality comparison on the
(primary) key attribute and file (relation) is ordered (sorted) on (primary) key
attribute
• Cost of binary search =[log2(br)] br denotes number if blocks containing records
from relation r
• This algorithm is father than linear search algorithm.

Q-26 Explain the External Sort Merge Algorithm with an example.


Ans Till now, we saw that sorting is an important term in any database
system. It means arranging the data either in ascending or descending order.
We use sorting not only for generating a sequenced output but also for
satisfying conditions of various database algorithms. In query processing,
the sorting method is used for performing various relational operations such
as joins, etc. efficiently. But the need is to provide a sorted input value to the
system. For sorting any relation, we have to build an index on the sort key
DBMS

and use that index for reading the relation in sorted order. However, using an
index, we sort the relation logically, not physically. Thus, sorting is
performed for cases that include:

Q-27 Describe how the UNIQUE constraint differs from the


PRIMARY KEY constraint.
Ans

The UNIQUE and PRIMARY KEY constraints in a database both ensure that the
values in certain columns are unique, but they have important differences:

1. Uniqueness of Values:
a. UNIQUE Constraint: Ensures that all values in a column (or a
combination of columns) are unique across the rows in a table.
However, it allows multiple NULL values in the column, as NULL is
treated as an unknown value and not compared for uniqueness.
b. PRIMARY KEY Constraint: Also ensures uniqueness, but it doesn't
allow NULL values at all. Every row must have a unique value for the
column or set of columns designated as the primary key.
2. Purpose:
a. UNIQUE: Typically used when a column must have unique values,
but it's not necessarily the primary identifier for a record in the table
(e.g., email addresses).
b. PRIMARY KEY: A column (or combination of columns) that
uniquely identifies each record in the table. It is the main identifier for
records, ensuring no two records can share the same primary key.
3. Number of Constraints Allowed:
a. UNIQUE: You can have multiple UNIQUE constraints in a single
table.
b. PRIMARY KEY: There can only be one PRIMARY KEY constraint
per table.
DBMS

4. Index Creation:
a. UNIQUE: Automatically creates a unique index to enforce the
constraint, ensuring efficient lookups for unique values.
b. PRIMARY KEY: Also creates a unique index but often used as the
default clustered index (though this can vary depending on the
database system).
Q-26 Apply different SQL aggregate functions with an
Example.
Ans

SQL aggregate functions perform calculations on a set of values and return a single value.
Here are common SQL aggregate functions, along with examples:

1. COUNT() - Counts the number of rows in a set.

sql
Copy code
SELECT COUNT(*) AS total_employees
FROM employees;

• Explanation: This query counts the total number of rows in the employees table,
giving the total number of employees.

2. SUM() - Adds up the values in a numeric column.

sql
Copy code
SELECT SUM(salary) AS total_salary
FROM employees;

• Explanation: This query calculates the total salary of all employees by summing the
salary column.

3. AVG() - Calculates the average value of a numeric column.

sql
Copy code
DBMS

SELECT AVG(salary) AS average_salary


FROM employees;

• Explanation: This query returns the average salary of all employees.

4. MIN() - Returns the smallest value in a column.

sql
Copy code
SELECT MIN(salary) AS minimum_salary
FROM employees;

• Explanation: This query returns the minimum salary from the employees table.

5. MAX() - Returns the largest value in a column.

sql
Copy code
SELECT MAX(salary) AS maximum_salary
FROM employees;

• Explanation: This query returns the highest salary in the employees table.

6. GROUP BY with Aggregates:

Aggregate functions can be used with the GROUP BY clause to calculate values for different
groups of data.

sql
Copy code
SELECT department, COUNT(*) AS total_employees, AVG(salary) AS
average_salary
FROM employees
GROUP BY department;

• Explanation: This query groups the data by department and returns the total
number of employees and average salary for each department.
DBMS

7. HAVING with Aggregates:

You can use the HAVING clause to filter the results of an aggregate function.

sql
Copy code
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;

• Explanation: This query returns only departments that have more than 10
employees.

8. DISTINCT with COUNT():

sql
Copy code
SELECT COUNT(DISTINCT department) AS distinct_departments
FROM employees;

• Explanation: This query counts the number of unique departments in the


employees table.
DBMS

Q-27 List and explain aggregation functions with suitable examples.


Ans

Here’s a concise overview of SQL aggregate functions with examples:

1. COUNT(): Counts the number of rows or non-null values.

sql
Copy code
SELECT COUNT(*) AS total_employees FROM employees;

2. SUM(): Sums numeric values.

sql
Copy code
SELECT SUM(salary) AS total_salary FROM employees;

3. AVG(): Calculates the average value.

sql
Copy code
SELECT AVG(salary) AS average_salary FROM employees;

4. MIN(): Returns the smallest value.

sql
Copy code
SELECT MIN(salary) AS minimum_salary FROM employees;
DBMS

5. MAX(): Returns the largest value.

sql
Copy code
SELECT MAX(salary) AS maximum_salary FROM employees;

6. COUNT(DISTINCT): Counts unique values.

sql
Copy code
SELECT COUNT(DISTINCT department) AS unique_departments FROM
employees;

7. GROUP BY: Aggregates by groups.

sql
Copy code
SELECT department, AVG(salary) FROM employees GROUP BY
department;

8. HAVING: Filters results after aggregation.

sql
Copy code
SELECT department, COUNT(*) FROM employees GROUP BY
department HAVING COUNT(*) > 10;

These functions help summarize and analyze data in SQL.


DBMS

Q-26 How does the CHECK constraint help maintain data integrity? Explain with

an example.

Ans

The CHECK constraint in SQL helps maintain data integrity by ensuring that the
values entered into a column satisfy a specific condition or meet a defined rule.
This ensures that only valid data is stored in the table according to the business or
data rules.

How CHECK Maintains Data Integrity:

• It prevents invalid data from being inserted into the table.


• Ensures that the data adheres to predefined rules, such as limits, formats, or
relationships between columns.

Example:

Suppose you have an employees table, and you want to ensure that an employee's
salary is always greater than 0 and less than or equal to 100,000. You can apply the
CHECK constraint as follows:

sql
Copy code
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10, 2),
CHECK (salary > 0 AND salary <= 100000)
);

• Explanation: This CHECK constraint ensures that every value entered into
the salary column is greater than 0 and less than or equal to 100,000. If
someone tries to insert a salary outside this range, the database will reject the
data and enforce integrity.
DBMS

Benefits of CHECK:

• Ensures logical consistency (e.g., age can't be negative, quantity can't exceed
stock levels).
• Reduces the risk of errors or invalid data being stored in the database.

This makes the data more reliable and trustworthy.

Q-27 What are primary and foreign keys in a database table?

Ans

Primary Key and Foreign Key are fundamental concepts in relational databases
that help maintain the integrity and relationships between tables.

1. Primary Key:

• Definition: A primary key is a column or a set of columns in a database


table that uniquely identifies each record in that table. It ensures that no
duplicate or null values are allowed.
DBMS

• Characteristics:
o Uniqueness: Each value in the primary key column must be unique
across the table.
o Non-nullable: A primary key cannot have NULL values.
o Single table: Each table can have only one primary key, although it
can be composed of multiple columns (composite key).
• Example:

sql
Copy code
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10, 2)
);

o Here, employee_id is the primary key, ensuring each employee has


a unique ID.

2. Foreign Key:

• Definition: A foreign key is a column (or a set of columns) in one table that
references the primary key of another table. It establishes a relationship
between the two tables and enforces referential integrity by ensuring that the
value in the foreign key column matches a valid value in the referenced
primary key.
• Characteristics:
o Referential Integrity: Ensures that a record in one table corresponds
to a valid record in another table.
o Nullable: Foreign keys can accept NULL values, which means the
relationship is optional.
o Multiple per table: A table can have multiple foreign keys.
• Example:

sql
DBMS

Copy code
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(100)
);

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10, 2),
department_id INT,
FOREIGN KEY (department_id) REFERENCES
departments(department_id)
);

o Here, department_id in the employees table is a foreign key that


references department_id in the departments table, establishing
a link between the two

Q-28 Write SQL statements (Query) for the following : 1. Create table Employee
(emp_no, emp_name, emp_sal, emp_comm, dept_no). 2. Insert a minimum of 8
values in the table Employee 3. display table Employee.

Ans

CREATE TABLE Employee (

emp_no INT PRIMARY KEY,

emp_name VARCHAR(100),

emp_sal DECIMAL(10, 2),

emp_comm DECIMAL(10, 2),

dept_no INT
DBMS

);

INSERT INTO Employee (emp_no, emp_name, emp_sal, emp_comm, dept_no)

VALUES

(1, 'John Doe', 50000, 5000, 10),

(2, 'Jane Smith', 55000, 4500, 20),

(3, 'Robert Brown', 60000, 6000, 10),

(4, 'Lisa Adams', 52000, 4800, 30),

(5, 'Michael Lee', 59000, 5500, 20),

(6, 'David Clark', 61000, 6100, 30),

(7, 'Emily Davis', 53000, 4700, 10),

(8, 'James Wilson', 62000, 6200, 20);

SELECT * FROM Employee;

Q-

You might also like