0% found this document useful (0 votes)
13 views10 pages

Distributed Database Overview: Key Features

DBMS study material

Uploaded by

vecnaog
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)
13 views10 pages

Distributed Database Overview: Key Features

DBMS study material

Uploaded by

vecnaog
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/ 10

Distributed Database Overview

distributed database in dbms

A distributed database in DBMS (Database Management System) refers to a database that is


distributed across multiple physical locations. These databases are not confined to a single machine or
server but are spread across various servers, which may be located in different geographical locations.

Key Features:

1. Distribution Transparency: The user or application does not need to know where the data is
stored or how it's managed across different locations.
2. Replication: Data can be copied across multiple sites for redundancy and high availability.
3. Fragmentation: Data can be divided into fragments and stored across different locations to
improve efficiency and load balancing.
4. Scalability: Distributed databases can scale horizontally by adding more servers or nodes to the
system.
5. Fault Tolerance: Since data is often replicated, the failure of one node does not result in data loss
or complete system failure.

Types of Distributed Databases:

1. Homogeneous Distributed Database: All sites use the same DBMS software, ensuring uniformity
in structure and operation.
2. Heterogeneous Distributed Database: Different DBMS systems are used at different sites,
requiring middleware to enable communication between them.

Advantages:

Improved Performance: Data is closer to the user, reducing access times.


Fault Tolerance: Data redundancy ensures higher reliability.
Flexibility and Scalability: Distributed databases can handle large amounts of data efficiently.

Disadvantages:

Complexity: Managing a distributed system is more complex than a centralized database.


Consistency Issues: Ensuring data consistency across distributed sites can be challenging.
Network Dependency: The system relies heavily on network connectivity.

In summary, distributed databases are crucial for applications requiring high availability, scalability, and
fault tolerance across multiple locations.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/10
data dictionary

A data dictionary is a centralized repository of metadata, which contains definitions, descriptions, and
characteristics of data used in a database management system (DBMS). It serves as a catalog for the
database's structure and provides detailed information about the database objects, such as tables,
views, indexes, constraints, relationships, and more.

Key Components of a Data Dictionary:

1. Table Definitions: Information about the tables, including table names, column names, data types,
and constraints (e.g., primary keys, foreign keys).
2. Field Definitions: Descriptions of the attributes or fields in each table, including data type, size,
and allowed values.
3. Relationships: Data on relationships between tables, such as one-to-many or many-to-many
relationships, including foreign key constraints.
4. Indexes: Information about indexes on tables, including the fields indexed and their properties.
5. Views: Descriptions of virtual tables that are defined by a query.
6. Stored Procedures & Functions: Definitions of any stored procedures, functions, or triggers used
in the database.
7. Access Control Information: Details about user permissions and access rights to various parts of
the database.

Types of Data Dictionaries:

1. Active Data Dictionary: Managed and maintained automatically by the DBMS. It is updated as
changes are made to the database structure (e.g., when new tables or columns are added).
2. Passive Data Dictionary: Maintained manually or by external tools, typically used in older systems
or smaller-scale applications.

Importance of Data Dictionary:

Improves Data Management: Provides a central reference for understanding the database
structure and usage.
Ensures Consistency: Helps in maintaining consistency in data definition and usage across the
system.
Supports Data Integrity: Ensures that constraints and relationships are properly defined and
adhered to.
Facilitates Database Maintenance: Aids in database design, modifications, and troubleshooting
by offering detailed descriptions of all objects.
Enables Data Governance: Helps with data compliance and auditing by tracking access controls
and data definitions.

In essence, a data dictionary acts as an essential tool for managing, understanding, and securing a
database system by providing insights into its structure and components.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/10
branching and looping constructs in ansisql

In ANSI SQL, there aren't direct branching and looping constructs like in traditional programming
languages (e.g., `if`, `while`). However, SQL does offer mechanisms to achieve similar behavior
through conditional expressions and control flow statements within stored procedures or functions.
Here's an overview of how to handle branching and looping in ANSI SQL:

Branching Constructs in ANSI SQL

Branching is usually done using conditional expressions or CASE statements in SQL queries or using
control flow statements in stored procedures.

1. CASE Statement: The `CASE` statement is the main way to implement branching in SQL. It allows
you to perform conditional logic directly in SQL queries.
Syntax:

sql

SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END as result_column
FROM table_name;

Example:

sql

SELECT employee_name,
CASE
WHEN salary > 50000 THEN 'High Salary'
WHEN salary BETWEEN 30000 AND 50000 THEN 'Average Salary'
ELSE 'Low Salary'
END as salary_range
FROM employees;

2. IF Statement (within stored procedures): In a stored procedure or function, the `IF` statement
can be used to execute conditional logic.

Syntax:

sql

IF condition THEN
-- SQL statement
ELSE

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/10
-- SQL statement
END IF;

Example:

sql

DELIMITER $$

CREATE PROCEDURE check_salary()


BEGIN
DECLARE salary INT;
SET salary = (SELECT salary FROM employees WHERE employee_id = 1);
IF salary > 50000 THEN
SELECT 'High Salary';
ELSE
SELECT 'Low Salary';
END IF;
END$$

DELIMITER ;

Looping Constructs in ANSI SQL

ANSI SQL does not provide direct loop constructs like `FOR` or `WHILE` in the query language. However,
in procedural SQL (such as PL/SQL in Oracle or T-SQL in SQL Server), loops can be implemented inside
stored procedures.

1. WHILE Loop (in stored procedures): You can use a `WHILE` loop to execute a block of SQL code
repeatedly based on a condition.
Syntax:

sql

WHILE condition DO
-- SQL statement(s)
END WHILE;

Example:

sql

DELIMITER $$

CREATE PROCEDURE loop_example()


BEGIN
DECLARE counter INT DEFAULT 1;
WHILE counter <= 10 DO
INSERT INTO numbers_table (number) VALUES (counter);
SET counter = counter + 1;
END WHILE;
END$$

DELIMITER ;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/10
2. LOOP (for MySQL): MySQL also supports the `LOOP` construct within stored procedures. A loop will
repeat until a specific condition is met, using `LEAVE` to exit.

Syntax:

sql

LOOP
-- SQL statement(s)
IF condition THEN
LEAVE loop_label;
END IF;
END LOOP;

Example:

sql

DELIMITER $$

CREATE PROCEDURE loop_example()


BEGIN
DECLARE counter INT DEFAULT 1;
loop_label: LOOP
IF counter > 10 THEN
LEAVE loop_label;
END IF;
INSERT INTO numbers_table (number) VALUES (counter);
SET counter = counter + 1;
END LOOP;
END$$

DELIMITER ;

Summary:

Branching: Done using `CASE` for inline conditions and `IF` for procedural flow in stored
procedures.
Looping: Done using `WHILE` and `LOOP` (in procedural SQL) to iterate over a block of code.

For pure SQL queries (outside stored procedures), your branching is limited to `CASE`, and for looping,
procedural SQL constructs (like `WHILE`) are needed.

cursor

A cursor in SQL is a database object used to retrieve, manipulate, and traverse through a result set row-
by-row. It acts as a pointer that allows you to fetch individual rows from a query result and perform
operations on them one at a time. Cursors are mainly used in procedural SQL (such as PL/SQL in Oracle,
T-SQL in SQL Server) when a result set needs to be processed row-by-row.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/10
Key Features:

Row-by-Row Processing: Cursors allow you to fetch one row at a time and perform specific
operations on it, which is useful for complex processing or iterative logic.
Control Flow: They allow for more fine-grained control when working with a result set, enabling
actions like updating or inserting rows based on certain conditions.

Types of Cursors:

1. Implicit Cursor:
Automatically created by the database management system when a `SELECT` statement is
executed.
The user does not explicitly declare or manage it.
Used for single queries where no explicit row-by-row processing is required.
2. Explicit Cursor:
Explicitly declared and controlled by the user.
Typically used in stored procedures or functions when the need for row-by-row operations
arises.
Provides more control over the fetching and processing of rows.

Basic Operations on Cursors:

1. Declare: Create a cursor and associate it with a SQL query.


2. Open: Execute the query and prepare the cursor for fetching data.
3. Fetch: Retrieve the rows from the cursor one at a time.
4. Close: Release the cursor and free up resources once it's no longer needed.

Example of Using an Explicit Cursor:

sql

DECLARE cursor_name CURSOR FOR


SELECT column1, column2
FROM table_name
WHERE condition;

-- Declare variables to hold fetched data


DECLARE @var1 INT, @var2 VARCHAR(50);

-- Open the cursor


OPEN cursor_name;

-- Fetch the first row


FETCH NEXT FROM cursor_name INTO @var1, @var2;

-- Process the fetched data


WHILE @@FETCH_STATUS = 0
BEGIN
-- Perform actions on the row data
PRINT @var1;
PRINT @var2;

-- Fetch the next row


FETCH NEXT FROM cursor_name INTO @var1, @var2;
END;

-- Close the cursor


CLOSE cursor_name;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/10
-- Deallocate the cursor (optional)
DEALLOCATE cursor_name;

Cursor Lifecycle:

1. Declaration: The cursor is declared and associated with a `SELECT` statement.


2. Opening: The `SELECT` statement is executed, and the cursor is positioned before the first row of
the result set.
3. Fetching: The `FETCH` statement retrieves the next row from the cursor and moves the pointer
forward.
4. Closing: After processing all rows, the cursor is closed, releasing resources.
5. Deallocating (Optional): The cursor can be deallocated to remove it from memory completely.

Advantages of Cursors:

Row-by-Row Processing: Cursors are ideal when you need to perform complex operations on each
row of a result set that cannot be handled in a single query.
Control Over Execution: Allows for fine-grained control over which rows are fetched and how
they're processed.

Disadvantages of Cursors:

Performance: Cursors are generally slower than set-based operations because they involve
processing each row individually, leading to increased resource consumption and execution time.
Complexity: Managing cursors can be cumbersome, especially with large result sets, and may lead
to more complex code.

When to Use Cursors:

When you need to process each row of a result set individually (e.g., complex business logic, row-
based calculations).
When no set-based SQL operation (like `JOIN`, `UPDATE`, `DELETE`, etc.) can be used to achieve the
desired result.
When you're working with a database that does not support more advanced SQL operations, or the
logic requires procedural steps.

In general, set-based operations (working with entire sets of rows at once) should be preferred over
cursors due to better performance and simplicity. Cursors should be used only when absolutely
necessary.

exception handling

Exception handling in SQL is the process of handling errors that occur during the execution of SQL
statements, particularly in stored procedures or functions. The goal of exception handling is to ensure
that errors are caught, dealt with, and don't cause the entire operation or system to fail unexpectedly.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/10
SQL exceptions are typically runtime errors, such as violations of integrity constraints (e.g., attempting
to insert a duplicate value into a primary key column) or issues related to resources (e.g., trying to divide
by zero).

Common SQL Exception Handling Constructs:

The way exceptions are handled in SQL depends on the specific database system being used. However,
most systems that support procedural SQL (e.g., PL/SQL in Oracle, T-SQL in SQL Server, PL/pgSQL in
PostgreSQL) have their own exception handling mechanisms.

1. PL/SQL (Oracle)

In Oracle, exception handling is managed using the `EXCEPTION` block. You can catch predefined
exceptions like `NO_DATA_FOUND` or `TOO_MANY_ROWS`, or define your own exceptions.

Syntax:

sql

BEGIN
-- SQL statements
-- Code that might cause an error
EXCEPTION
WHEN exception_name THEN
-- Handle the error (e.g., log, re-raise, or return an error message)
-- You can also perform corrective actions
WHEN OTHERS THEN
-- This is a generic handler for any exception not explicitly caught
-- You can log the error or raise a custom message
END;

Example:

sql

DECLARE
v_employee_name VARCHAR2(50);
BEGIN
SELECT employee_name INTO v_employee_name
FROM employees
WHERE employee_id = 100;

-- Additional code that may cause an error

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found!');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Query returned more than one row!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);
END;

2. T-SQL (SQL Server)

In SQL Server, exception handling is done using `TRY...CATCH` blocks. If an error occurs within the `TRY`
block, control is transferred to the `CATCH` block where you can handle the error.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/10
Syntax:

sql

BEGIN TRY
-- SQL statements that might cause an error
END TRY
BEGIN CATCH
-- Handle the error
-- You can use ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_SEVERITY(), etc., to get details
PRINT 'Error Message: ' + ERROR_MESSAGE();
PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR(10));
END CATCH;

Example:

sql

BEGIN TRY
-- Attempting to divide by zero
DECLARE @result INT;
SET @result = 10 / 0;
END TRY
BEGIN CATCH
PRINT 'Error occurred: ' + ERROR_MESSAGE();
PRINT 'Error number: ' + CAST(ERROR_NUMBER() AS VARCHAR(10));
END CATCH;

3. PL/pgSQL (PostgreSQL)

PostgreSQL uses the `EXCEPTION` block in `PL/pgSQL` for error handling. Similar to Oracle, you can catch
specific exceptions or use a general `WHEN OTHERS` block.

Syntax:

sql

BEGIN
-- SQL statements that might cause an error
EXCEPTION
WHEN exception_name THEN
-- Handle the error
WHEN OTHERS THEN
-- General error handler
END;

Example:

sql

DO $$
BEGIN
-- SQL statements that might cause an error
RAISE NOTICE 'This will cause a division by zero error:';
PERFORM 10 / 0;
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Caught division by zero error';
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/10
WHEN OTHERS THEN
RAISE NOTICE 'An unexpected error occurred';
END;
$$;

Key Concepts in Exception Handling:

1. Predefined Exceptions: These are standard exceptions provided by the DBMS (e.g.,
`NO_DATA_FOUND`, `TOO_MANY_ROWS`, `ZERO_DIVIDE`, etc.).
2. User-Defined Exceptions: You can create your own exceptions in your code, especially if specific
errors need to be handled in a particular way.

3. Exception Propagation: After an exception is caught, it can either be handled and suppressed, or
re-raised to propagate the error to a higher level (e.g., the caller of the procedure).

4. SQLERRM / ERROR_MESSAGE: These functions help in retrieving detailed information about the
error that occurred, such as the error message or code.

5. WHEN OTHERS: This is a generic exception handler that catches any errors not explicitly handled
by previous `WHEN` clauses.

Best Practices for Exception Handling:

Graceful Handling: Catch errors and provide meaningful error messages or take corrective
actions, rather than letting the program fail silently.
Logging: Log errors for further analysis and debugging, especially in production systems.
Avoid Nested Exceptions: Limit the nesting of exception handlers to avoid confusion or
complexity.
Re-raise Errors: In cases where you cannot handle an exception, re-raise it to the calling
application or system.

Conclusion:

Exception handling is critical in SQL, particularly in procedural SQL programming (stored procedures,
triggers). It helps to ensure that errors are managed properly, maintaining data integrity and enhancing
the user experience by providing meaningful error messages or corrective actions.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/10

You might also like