Relational Model
Codd proposed the relational data model in 1970. The dominant data model and is the
foundation for the leading DBMS products. In relational model, a database is a collection of
one or more relations, where each relation is a table with rows and columns. The major
advantages of the relational model over the older data models are its simple data
representation and the ease with which even complex queries can be expressed.
Integrity Constraints over Relations
Integrity constraints are a set of rules. It is used to maintain the quality of information.
Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.
Thus, integrity constraint is used to guard against accidental damage to the database.
Rules that help to maintain the accuracy and consistency of data in a database.
Purpose of Integrity Constraints
Integrity constraints are an important part of maintaining database correctness. They ensure that
the data in the database adheres to a set of rules, which can help prevent errors and
inconsistencies. In some cases, integrity constraints can be used to enforce business rules, such
as ensuring that a customer's balance remains within a certain limit. They can be used to enforce
data integrity, such as ensuring that all values in a column are unique. Integrity constraints in
SQL can be either enforced by the database system or by application code. Enforcing them at the
database level can help ensure that the rules are always followed, even if the application code is
changed. However, enforcing them at the application level can give the developer more
flexibility in how the rules are enforced.
Types of IC:
1. Domain Constraint
1. A domain constraint is a restriction on the values that can be stored in a column. For example, if I
have a column for "age," domain integrity constraints in DBMS would ensure that only values
between 1 and 120 can be entered into that column. This ensures that only valid data is entered
into the database.
2. Domain constraints can be defined as the definition of a valid set of values for an
attribute. (Javatpoint)
3. The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain. (Javatpoint)
4. Domain integrity ensures that the values entered into a column or attribute adhere to
specific data type, format, or range constraints.
5. It prevents the insertion of invalid or inappropriate data into a column.
6. Example: A domain integrity constraint on a "DateOfBirth" column ensures that only
valid dates in a specified format (e.g., YYYY-MM-DD) are allowed.
Example:
2. Entity Integrity Constraint
An entity integrity constraint is a restriction on null values. Null values are values that are
unknown or not applicable, and they can be problematic because they can lead to inaccurate
results. Entity integrity constraints would ensure that null values are not entered into any
required columns. For example, if you have a column for "first name," an entity integrity
constraint in DBMS would ensure that this column cannot contain any null values.
The entity integrity constraint states that primary key value can't be null.
This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
A table can contain a null value other than the primary key field.
The bullets source: Javatpoint
Example:
3. Referential Integrity Constraints
This constraint is a restriction on how foreign keys can be used. A foreign key is a column in one
table that references a primary key in another table. For example, let's say I have a table of
employees and a table of department managers. The "employee ID" column in the employee's
table would be a foreign key that references the "manager ID" column in the manager's table.
Referential integrity constraints in DBMS would ensure that every manager ID in the manager's
table has at least one corresponding employee ID in the employee's table. In other words, it
would prevent us from assigning an employee to a manager who doesn't exist.
A referential integrity constraint is specified between two tables.
In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.
The bullets source: Javatpoint
Example:
4. Key constraint
A key constraint enforces uniqueness within a column or set of columns, ensuring that each
value is unique. It can be applied to primary keys, unique keys, or alternate keys. Example: A
key constraint on a "Username" column in a user table ensures that each user has a unique
username. (ChatGPT)
Key constraints in DBMS are a restriction on duplicate values. A key is composed of one or more columns
whose values uniquely identify each row in the table. For example, let's say you have a table of products
with columns for "product ID" and "product name." The combination of these two values would be the
key for each product, and a key constraint would ensure that no two products have the same
combination of product ID and product name. (Website)
Types of key constraint
1. Primary Key Constraints
A primary key constraint (also known as a "primary key") is a type of key constraint that requires
every value in a given column to be unique. In other words, no two rows in a table can have the
same value for their primary key column(s). A primary key can either be a single column or
multiple columns (known as a "composite" primary key). The null value is not allowed in the
primary key column(s).
2. Unique Key Constraints
A unique key constraint is a column or set of columns that ensures that the values stored in the
column are unique. A table can have more than one unique key constraint, unlike the primary
key. A unique key column can contain NULL values. Like primary keys, unique keys can be
made up of a single column or multiple columns.
3. Foreign Key Constraints
A foreign key constraint defines a relationship between two tables. A foreign key in one table
references a primary key in another table. Foreign keys prevent invalid data from being inserted
into the foreign key column. Foreign keys can reference a single column or multiple columns.
For example, if we have tables student and enrolled, foreign key constraint states that every
Student value in Enrolled must also appear in Students, that is, student_ID in Enrolled is a
foreign key referencing Students. Incidentally, the primary key constraint states that a student
has exactly one grade for each course that he or she is enrolled in.
4. NOT NULL Constraints
A NOT NULL constraint is used to ensure that no row can be inserted into the table without a
value being specified for the column(s) with this type of constraint. Thus, every row must have a
non-NULL value for these columns.
5. Check Constraints
A check constraint enforces data integrity by allowing you to specify conditions that must be met
for data to be inserted into a column. For example, you could use a check constraint to ensure
that only positive integer values are inserted into a particular column. Check constraints are
usually used in combination with other constraints (such as NOT NULL constraints) to enforce
more complex rules.
Views:
A view is a virtual table that is dynamically generated based on a predefined query. Unlike physical
tables, views do not store data themselves; instead, they are derived from one or more underlying tables
or other views. Views can be used to present data in a customized or aggregated form, simplify complex
queries, or restrict access to certain columns or rows of a table. The main difference between them is
that a table is an object that consists of rows and columns to store and retrieve data whenever the
user needs it. In contrast, the view is a virtual table based on an SQL statement's result set and will
disappear when the current session is closed.
We can create the columns of the view from one or more tables. Its content is based on base
tables. The view is a database object with no values and contains rows and columns the same as
real tables. It does not occupy space on our systems.
SQL – Structured Query Language
a standardized programming language used to interact with relational databases. It allows users to
manage, manipulate, and query data stored in a relational database management system (RDBMS). SQL
is widely used in database management, data analysis, and data manipulation tasks.
SQL Aggregate Functions
Aggregate functions in SQL are used to perform calculations on sets of rows and return a single
value as a result. Here are some commonly used aggregate functions in SQL:
1. COUNT: Returns the number of rows in a set.
2. SUM: Returns the sum of values in a set.
3. AVG: Returns the average of values in a set.
4. MIN: Returns the minimum value in a set.
5. MAX: Returns the maximum value in a set.
Now, let's demonstrate these aggregate functions with an example using a sample table called
"Sales":
| OrderID | ProductCategory | Quantity | Price |
|---------|-----------------|----------|-------|
| 1 | Electronics | 10 | 500 |
| 2 | Electronics | 20 | 450 |
| 3 | Clothing | 30 | 40 |
| 4 | Clothing | 20 | 30 |
| 5 | Books | 50 | 15 |
| 6 | Books | 50 | 25 |
COUNT:
SELECT COUNT(*) AS TotalSales FROM Sales;
Output:
| TotalSales |
|------------|
| 6 |
SUM:
SELECT SUM(Quantity) AS TotalQuantity, SUM(Price) AS TotalRevenue FROM Sales;
Output:
| TotalQuantity | TotalRevenue |
|---------------|--------------|
| 180 | 2065 |
3. AVG:
SELECT AVG(Quantity) AS AvgQuantity, AVG(Price) AS AvgPrice FROM Sales;
Output:
| AvgQuantity | AvgPrice |
|-------------|----------|
| 30 | 344.167 |
4. MIN:
SELECT MIN(Quantity) AS MinQuantity, MIN(Price) AS MinPrice FROM Sales;
Output:
| MinQuantity | MinPrice |
|-------------|----------|
| 10 | 15 |
5. MAX:
SELECT MAX(Quantity) AS MaxQuantity, MAX(Price) AS MaxPrice FROM Sales;
Output:
| MaxQuantity | MaxPrice |
|-------------|----------|
| 50 | 500 |
These aggregate functions provide valuable insights into the data by summarizing information
across multiple rows in a table.
GROUP BY:
GROUP BY is a clause in SQL used to group rows that have the same values into summary rows, typically
to perform aggregate functions on these groups. It divides the result set into groups based on one or
more columns and applies aggregate functions to each group.
Consider the "Sales" table:
| OrderID | ProductCategory | Quantity | Price |
|---------|-----------------|----------|-------|
| 1 | Electronics | 10 | 500 |
| 2 | Electronics | 20 | 450 |
| 3 | Clothing | 30 | 40 |
| 4 | Clothing | 20 | 30 |
| 5 | Books | 50 | 15 |
| 6 | Books | 50 | 25 |
Now, let's apply the GROUP BY clause to calculate the total quantity and average price for each
product category:
SELECT ProductCategory, SUM(Quantity) AS TotalQuantity, AVG(Price) AS AvgPrice
FROM Sales
GROUP BY ProductCategory;
This query will group the rows by the "ProductCategory" column and calculate the total quantity
and average price for each product category.
The result might look like this:
| ProductCategory | TotalQuantity | AvgPrice |
|-----------------|---------------|----------|
| Electronics | 30 | 475 |
| Clothing | 50 | 35 |
| Books | 100 | 20 |
In this result, each row represents a product category, and the "TotalQuantity" column shows the
total quantity of products sold in that category, while the "AvgPrice" column shows the average
price of products sold in that category.
Having Clause
The HAVING clause in SQL is used to filter groups of rows returned by a GROUP BY clause. It
allows you to apply a condition to the grouped rows after the grouping has been performed. This
is particularly useful when you want to filter aggregated results based on specific criteria.
Here's the syntax of the HAVING clause:
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1
HAVING condition;
And here's an example using the "Sales" table:
Consider the "Sales" table:
| OrderID | ProductCategory | Quantity | Price |
|---------|-----------------|----------|-------|
| 1 | Electronics | 10 | 500 |
| 2 | Electronics | 20 | 450 |
| 3 | Clothing | 30 | 40 |
| 4 | Clothing | 20 | 30 |
| 5 | Books | 50 | 15 |
| 6 | Books | 50 | 25 |
Suppose we want to find the total quantity and average price for each product category but only
include categories where the total quantity sold is greater than 30. We can use the HAVING
clause to achieve this:
SELECT ProductCategory, SUM(Quantity) AS TotalQuantity, AVG(Price) AS AvgPrice
FROM Sales
GROUP BY ProductCategory
HAVING SUM(Quantity) > 30;
Output:
| ProductCategory | TotalQuantity | AvgPrice |
|-----------------|---------------|----------|
| Clothing | 50 | 35 |
| Books | 100 | 20 |
In this example, the HAVING clause filters out the groups where the total quantity sold is not
greater than 30, leaving only the product categories "Clothing" and "Books" that meet the
specified condition.
Set-Comparison Operators:
- Are used to compare values in one set to values in another set. These operators include EXISTS, IN,
and UNIQUE.
-
EXISTS:
- The EXISTS operator is used to check if a subquery returns any rows. If the subquery
returns at least one row, the EXISTS condition is true; otherwise, it is false.
Syntax:
SELECT column1
FROM table1
WHERE EXISTS (SELECT column2 FROM table2 WHERE condition);
Example: Suppose we have two tables’ "Orders" and "Customers". We want to find customers
who have placed orders. We can use EXISTS as follows:
SELECT CustomerID, Name
FROM Customers
WHERE EXISTS (SELECT * FROM Orders WHERE [Link] =
[Link]);
IN:
- The IN operator is used to check if a value matches any value in a list or subquery. If the
value matches any value in the list or subquery, the IN condition is true; otherwise, it is
false.
Syntax:
SELECT column1
FROM table1
WHERE column2 IN (value1, value2, ...);
Example: Suppose we want to find orders that belong to specific customers. We can use IN as
follows:
SELECT OrderID
FROM Orders
WHERE CustomerID IN (101, 102, 103);
UNIQUE:
- The UNIQUE operator is used to ensure that all values returned by a query are unique. It
eliminates duplicate rows from the result set.
Syntax:
SELECT UNIQUE column1, column2
FROM table1;
Example: Suppose we have a table "Employees" with duplicate records. We want to retrieve
unique records. We can use UNIQUE as follows:
SELECT UNIQUE EmployeeID, Name
FROM Employees;
Negated versions:
1. NOT EXISTS:
- The negated version of EXISTS checks if a subquery returns no rows. If the subquery
returns no rows, the NOT EXISTS condition is true; otherwise, it is false.
Syntax:
SELECT column1
FROM table1
WHERE NOT EXISTS (SELECT column2 FROM table2 WHERE condition);
2. NOT IN:
- The negated version of IN checks if a value does not match any value in a list or
subquery. If the value does not match any value in the list or subquery, the NOT IN
condition is true; otherwise, it is false.
Syntax:
SELECT column1
FROM table1
WHERE column2 NOT IN (value1, value2, ...);
3. ALL:
- The ALL operator is used to compare a value with all values returned by a subquery. It
returns true if the comparison is true for all rows returned by the subquery.
Syntax:
SELECT column1
FROM table1
WHERE column2 > ALL (SELECT column3 FROM table2 WHERE condition);
Logical Connectives AND, OR, and NOT
- Are used to combine conditions in WHERE clauses to filter data from tables. Let's
describe each of these logical connectives along with examples:
1. AND:
- The AND operator is used to retrieve rows that satisfy multiple conditions
simultaneously. It returns true if all the conditions separated by AND are true.
Syntax
SELECT column1
FROM table
WHERE condition1 AND condition2;
Example: Suppose we want to retrieve employees who are in the IT department and have a
salary greater than $50,000. We can use the AND operator as follows:
SELECT *
FROM Employees
WHERE Department = 'IT' AND Salary > 50000;
1. OR:
- The OR operator is used to retrieve rows that satisfy at least one of the conditions
specified. It returns true if at least one of the conditions separated by OR is true.
Syntax:
SELECT column1
FROM table
WHERE condition1 OR condition2;
Example: Suppose we want to retrieve employees who are either in the IT department or have a
salary greater than $50,000. We can use the OR operator as follows:
SELECT *
FROM Employees
WHERE Department = 'IT' OR Salary > 50000;
2. NOT:
- The NOT operator is used to negate a condition. It returns true if the condition is false and
false if the condition is true.
Syntax:
SELECT column1
FROM table
WHERE NOT condition;
Example: Suppose we want to retrieve employees who are not in the IT department. We can use
the NOT operator as follows:
SELECT *
FROM Employees
WHERE NOT Department = 'IT';
These logical connectives help build complex conditions in SQL queries, allowing users to
retrieve data based on various criteria and conditions.
Data Storage and Indexing
Tapes
- Slower storage devices such as tapes and disks play an important role in database
systems because the amount of data is typically very large.
- Tapes are relatively inexpensive and can store very large amounts of data.
- They are a good choice for archival storage, that is, when we need to maintain data
for a long period but do not expect to access it very often.
- The main drawbacks of tape storage devices is their sequential access nature. Unlike disk
storage, where data can be accessed randomly, tapes require sequential access, meaning that
data is read or written sequentially from the beginning to the end of the tape.
- Tapes are unsuitable for storing operational data, which requires frequent and random access.
Operational data, such as databases used in online transaction processing (OLTP) systems, often
requires rapid access to specific records or transactions. Using tapes for operational data storage
would result in poor performance and inefficiency.
Magnetic Disks
- Magnetic disks, also known as hard disk drives (HDDs), allow for direct access to specific
locations or blocks of data stored on the disk.
- This means that data can be retrieved or written to any location on the disk without having to
sequentially read or write through preceding data.
- This direct access capability is essential for efficient data retrieval and manipulation in database
applications, where quick access to specific records or data blocks is often required.
Disk Structure:
- Description: Magnetic disks store data in units called disk blocks, which are contiguous
sequences of bytes. These blocks are organized into concentric rings called tracks on one
or more platters.
- Definition: Disk block is the unit in which data is written to and read from a disk. Tracks
are circular paths on the disk surface where data is stored.
Cylinders and Sectors:
- Description: Tracks with the same diameter across all platter surfaces form a cylinder.
Each track is divided into arcs called sectors, which have a fixed size determined by the
disk.
- Definition: Cylinder is the set of tracks with the same diameter, resembling a cylinder
shape. Sectors are divisions within a track where data is stored, with a fixed size
determined by the disk.
Disk Head Movement:
- Description: Disk heads are moved as a unit to position them over specific disk blocks.
To read or write data, the disk head must be aligned with the desired block.
- Definition: Disk head movement refers to the physical repositioning of the read/write
heads over the disk surface to access data blocks.
Seek Time and Rotational Delay:
- Description: Seek time is the time taken for the disk heads to move to the track
containing the desired block. Rotational delay is the waiting time for the desired block to
rotate under the disk head.
- Definition: Seek time is the time required for the disk heads to move to the desired track,
while rotational delay is the time for the disk to rotate to the correct position for accessing
the block.
Transfer Time:
- Description: Transfer time is the time taken to actually read or write data from/to the
disk block once the disk head is positioned.
- Definition: Transfer time is the duration required for the disk to read/write the data in the
block after the head is positioned over it.
Disk Controller:
- Description: A disk controller interfaces the disk drive with the computer, implementing
commands to read or write data sectors. It also computes checksums for data integrity
verification.
- Definition: Disk controller is a hardware component responsible for managing data
transfer between the disk drive and the computer, as well as ensuring data integrity
through checksum computation.
RAID
Redundant Array of Independent Disks is a data storage technology that combines multiple physical disk
drives into a single logical unit for improved performance, redundancy, or both. RAID is commonly used
in enterprise environments to enhance data reliability, availability, and performance።
1. Structure:
- RAID organizes multiple physical disk drives into a logical array, presenting them to the
operating system as a single storage device. The data is distributed across the array in various
ways, depending on the RAID level configuration.
- RAID arrays can be implemented using hardware RAID controllers, which are dedicated
hardware devices, or software RAID, which is managed by the operating system.
2. Components:
- Physical Disks: The physical disk drives are the individual storage devices that make up the
RAID array. These disks can be of various types (e.g., HDDs, SSDs) and capacities.
- RAID Controller: In hardware RAID implementations, the RAID controller is responsible
for managing the RAID array and handling data storage and retrieval operations. It typically
includes a dedicated processor, cache memory, and firmware.
- RAID Array: The RAID array is the logical unit presented to the operating system. It
consists of multiple physical disks configured according to the RAID level chosen.
- RAID Levels: RAID supports different configurations known as RAID levels, each offering
specific features and benefits in terms of performance, redundancy, and capacity utilization.
Common RAID levels include RAID 0, RAID 1, RAID 5, RAID 6, RAID 10, and RAID 50.
3. RAID Levels:
- RAID 0 (Nonredundant): Striping without redundancy. Data is distributed across multiple
disks for increased performance but without fault tolerance. No redundant information is
maintained.
- RAID 1: Mirroring without striping. Data is duplicated across two or more disks for
redundancy, providing fault tolerance but sacrificing capacity.
- RAID 5: Striping with distributed parity. Data is striped across multiple disks, and parity
information is distributed for fault tolerance. RAID 5 requires a minimum of three disks.
- RAID 6: Similar to RAID 5 but with dual parity for enhanced fault tolerance. RAID 6 can
withstand the failure of up to two disks simultaneously.
- RAID 10 (RAID 1+0): Combination of RAID 1 mirroring and RAID 0 striping. Data is
mirrored and then striped across multiple disk pairs for both redundancy and performance.
- RAID 50 (RAID 5+0): Combination of RAID 5 striping and RAID 0 striping. Data is striped
across multiple RAID 5 arrays for improved performance and fault tolerance.
4. Benefits and Considerations:
- Performance: RAID can improve data access speeds by distributing data across multiple
disks and allowing for parallel read/write operations.
- Redundancy: Certain RAID levels provide fault tolerance by creating redundant copies of
data or using parity information for data reconstruction in case of disk failures.
- Capacity Utilization: RAID allows for efficient use of storage capacity by distributing data
across multiple disks while maintaining redundancy, depending on the RAID level chosen.
- Complexity and Cost: Implementing RAID may require additional hardware (e.g., RAID
controllers) and configuration complexity. Hardware RAID solutions tend to be more
expensive than software RAID.
- RAID Rebuild Time: In the event of a disk failure, RAID arrays may need to undergo a
rebuild process to restore redundancy. The time required for RAID rebuilds can vary
depending on the RAID level and disk capacities.
Generally, RAID is a data storage technology that offers improved performance, redundancy,
or both by combining multiple physical disk drives into a single logical unit.
Buffer Manager
A Buffer Manager is a crucial component of a Database Management System (DBMS)
responsible for efficiently managing the movement of data between the disk storage and main
memory (RAM) of a computer. It acts as an intermediary layer between the disk and the
database, optimizing data access and retrieval operations.
1. Purpose:
- The primary purpose of a Buffer Manager is to reduce the latency associated with disk I/O
operations by caching frequently accessed data in main memory.
- It helps improve overall system performance by minimizing the number of physical disk
reads and writes, which are typically slower compared to accessing data from memory.
2. Functionality:
- Buffer Pool: The Buffer Manager maintains a portion of main memory known as the buffer
pool, which serves as a cache for storing data pages retrieved from disk.
- Page Replacement: When a database query requests a data page that is not currently in the
buffer pool, the Buffer Manager is responsible for selecting an appropriate page to evict (if
the buffer pool is full) and replacing it with the requested page from disk.
- Read and Write Operations: The Buffer Manager coordinates read and write operations
between the disk and the buffer pool, ensuring that data is properly transferred and updated.
- Dirty Pages: Data pages that have been modified in memory but not yet written back to disk
are referred to as "dirty" pages. The Buffer Manager tracks these dirty pages and ensures they
are written back to disk during appropriate checkpoints or flush operations to maintain data
consistency.
3. Buffer Pool Management:
- Page Pinning: Some data pages may need to be pinned in memory to prevent them from
being evicted by the Buffer Manager. Pinning is typically used for critical system metadata
or frequently accessed data that must always reside in memory.
- LRU (Least Recently Used) Policy: The Buffer Manager often employs an LRU-based page
replacement policy, where the least recently used pages are candidates for eviction when new
pages need to be loaded into the buffer pool.
- Buffer Pool Size: The size of the buffer pool is configurable and depends on factors such as
available system memory, database workload, and performance requirements. A larger buffer
pool can accommodate more data pages in memory, reducing the frequency of disk I/O
operations.
4. Integration with Database Engine:
- The Buffer Manager works closely with other components of the database engine, such as the
query optimizer and execution engine, to ensure efficient query processing.
- It provides data pages to the query processor as needed, reducing disk latency and improving
query performance.
- The Buffer Manager also coordinates with the transaction manager to ensure that database
transactions are properly isolated and that changes to data are logged and flushed to disk in a
timely manner to maintain data durability.
5. Performance Considerations:
- Efficient buffer pool management is critical for database performance. Poorly configured
buffer pool sizes or ineffective page replacement policies can lead to excessive disk I/O and
degrade system performance.
- The Buffer Manager's performance can be influenced by factors such as disk speed, memory
availability, workload characteristics, and concurrency levels.
In summary, the Buffer Manager plays a vital role in optimizing data access and retrieval in a
database system by managing the movement of data between disk storage and main memory. It
employs various caching and page replacement strategies to minimize disk I/O latency and
improve overall system performance. Efficient buffer pool management is essential for achieving
optimal database performance and scalability.
Heap file and Indexes:
1. Heap File:
A heap file is a basic file organization structure used in databases for storing records. It is called
a "heap" because records are typically inserted wherever there is space available within the file,
without any specific ordering or sorting criteria.
Structure:
- Records are stored in arbitrary order, with no inherent ordering based on keys or attributes.
- Each record occupies a fixed-size block or variable-sized space within the file.
- Records can be accessed sequentially or through a scan of the entire file.
Insertion and Deletion:
- Insertions are straightforward and involve appending new records to the end of the file or
using available free space within the file.
- Deletions may leave gaps in the file, resulting in fragmentation and inefficient space
utilization.
Search and Retrieval:
- Searching for specific records within a heap file typically requires scanning the entire file
sequentially, which can be slow for large datasets.
- Since records are not ordered or indexed, there is no efficient way to locate records based on
their key values.
Usage:
- Heap files are suitable for scenarios where data access patterns do not require frequent
searches or ordered retrievals.
- They are commonly used for append-only or logging applications where records are
continuously added but rarely updated or deleted.
Advantages and Disadvantages:
- Advantages: Simple and efficient for insertion, suitable for unordered datasets, minimal
overhead.
- Disadvantages: Slow for searching and retrieval, prone to fragmentation, inefficient for
ordered access.
2. Indexes:
An index is a data structure associated with a database table that improves the speed of data
retrieval operations by providing quick access to rows based on key values.
Structure:
- An index consists of key-value pairs, where the key is typically a column or combination of
columns from the table.
- Each key in the index points to the corresponding record or records in the table.
- Indexes can be organized in various ways, including B-trees, hash tables, and bitmap
indexes.
Types of Indexes:
- Primary Index: Created on the primary key column(s) of a table. Provides direct access to
records based on their primary key values.
- Secondary Index: Created on non-primary key columns to speed up search operations on
those columns.
- Clustered Index: Organizes the physical order of records in the table based on the index key.
Each table can have only one clustered index.
- Non-Clustered Index: Stores a separate copy of the indexed column(s) along with pointers
to the corresponding records in the table.
Benefits:
- Improved query performance: Indexes allow for rapid lookup of records based on key values,
reducing the need for full-table scans.
- Efficient data retrieval: Indexes enable database systems to locate specific records quickly,
even in large datasets.
- Enhanced data integrity: Indexes can enforce unique constraints and ensure data consistency
by preventing duplicate entries.
Drawbacks:
- Increased storage overhead: Indexes require additional storage space to maintain the index
structures and pointers.
- Overhead on data modification: Insertions, updates, and deletions may require index
maintenance, impacting performance.
- Index fragmentation: Over time, indexes may become fragmented, leading to decreased
query performance and increased maintenance overhead.
In summary, heap files provide a basic storage structure for unordered data, while indexes
enhance data retrieval performance by facilitating quick access to records based on key values.
Effective database design often involves a balance between heap files and indexes to optimize
data storage and retrieval operations based on application requirements and access patterns.