0% found this document useful (0 votes)
5 views80 pages

Unit V

The document outlines the architecture and features of distributed databases, defining them as interconnected databases managed to appear as a single entity. It discusses the types of distributed database management systems (DDBMS) - homogeneous and heterogeneous - and their respective advantages and complexities. Additionally, it covers data storage strategies, including replication and fragmentation, and the importance of data transparency and distributed transactions in ensuring efficient database management.

Uploaded by

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

Unit V

The document outlines the architecture and features of distributed databases, defining them as interconnected databases managed to appear as a single entity. It discusses the types of distributed database management systems (DDBMS) - homogeneous and heterogeneous - and their respective advantages and complexities. Additionally, it covers data storage strategies, including replication and fragmentation, and the importance of data transparency and distributed transactions in ensuring efficient database management.

Uploaded by

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

Unit V

Distributed Databases: Architecture


• Distributed database definitions
• A distributed database is a collection of multiple, logically interconnected
databases spread physically across various locations that communicate via
computer network.
• A distributed DBMS manages the distributed database in a manner that
makes it appear as one single database to users.
• Distributed database system: It is a centralized software system that manages
or controls a distributed database in a manner as if it were all stored in a
single location.
Features of Distributed Database
• Data is physically stored across multiple sites. Data in each site can be
managed by a DBMS independent of the other sites.
• The processors in the site are connected via a network. They do not
have any multiprocessor configuration.
Distributed database system
• A database user can access a distributed database through:
• Local application: applications that do not require data from other sites.
• Global applications: applications that require data from other sites.
• A DDBMS is mainly classified into two types:
• Homogeneous distributed database management systems: Have identical
software and hardware running all database instances, and may appear
through a single interface as if it were a single database.
• Heterogeneous Distributed database management systems may have
different hardware, operating systems, database management systems, and
even data models for different databases.
Homogeneous DDBMS
• In a homogeneous distributed database, all sites have identical
software and are aware of each other and agree to cooperate in
processing user requests.
• The homogeneous system is much easier to design and manage.
• The operating system used at each location must be the same or
compatible.
• The database application used at each location must be same or
compatible.
Heterogeneous DDBMS
• In a Heterogeneous distributed database, different sites may use different
schemas and software.
• In a heterogeneous system, different nodes may have different hardware
and software, and data structures at various nodes or locations are also
incompatible.
•Different computers and operating systems, database applications, or data
models may be used at each of the locations.
Comparison between Homogeneous and
Heterogeneous DDBMS
Feature Homogeneous DDBMS Heterogeneous DDBMS
Schema Same across all sites Different schemas
Software Same DBMS software Different DBMS software
Hardware Similar or identical Different hardware setups
Operating System Usually the same May vary across locations
Data Models Uniform May differ (e.g., relational vs
object-oriented)
Communication Easier due to compatibility Requires translation or middleware
Management Complexity Lower Higher due to incompatibility
Advantages of DDBMS
• Improved ease and flexibility of application development - Developing and
maintaining applications at geographically distributed sites of an organization is
facilitated owing to the transparency of data distribution and control.
• Increased reliability and availability - When the data and DDBMS software
are distributed over several sites, one site may fail while other sites continue to
operate. Only the data and software that exist at the failed site cannot be accessed.
This improves both reliability and availability.
• Improved performance. A distributed DBMS fragments the database by keeping the
data closer to where it is needed most. Data localization reduces the contention for
CPU and I/O services and simultaneously reduces access delays involved in wide area
networks.
• Easier expansion. In a distributed environment, the expansion of the system in terms
of adding more data, increasing database sizes, or adding more processors is much
easier.
Distributed Database Architecture
Parallel versus Distributed Architectures
Two main types of multiprocessor system architectures that are commonplace:
■ Shared memory (tightly coupled) architecture. Multiple processors share
secondary (disk) storage and also share primary memory.
■ Shared disk (loosely coupled) architecture. Multiple processors share
secondary (disk) storage, but each has their own primary memory.
Database management systems developed using the above types of architectures are
termed parallel database management systems rather than DDBMSs, since they
utilize parallel processor technology.
Shared nothing architecture
Another type of multiprocessor architecture is called shared nothing architecture in
which every processor has its own primary and secondary (disk) memory, no common
memory exists, and the processors communicate over a high-speed interconnection
network (bus or switch).
Shared nothing Architecture
A network architecture with
centralized database at one of the
sites.
A Distributed Database Architecture
General Architecture of Distributed
Database
Logical Architecture:
Provides a unified global view of data across all distributed nodes using the Global Conceptual Schema (GCS).
Each site has:
•Local Internal Schema (LIS) – describes physical data organization.
•Local Conceptual Schema (LCS) – describes logical data structure at that site.
GCS, LCS, and their mappings ensure network, fragmentation, and replication transparency.
Component Architecture:
Extends the centralized DBMS architecture.
Global Query Compiler uses GCS from the global catalog to check constraints.
Global Query Optimizer:
Generates optimized local queries from global ones.
Evaluates query strategies using a cost function (based on CPU, I/O, network latency, and join result
sizes).
Selects the least-cost strategy for execution.
Each local DBMS includes:
Local optimizer, transaction manager, execution engine, and system catalog.
Global Transaction Manager coordinates distributed transactions across sites by working with local transaction
managers.
Step-by-Step of Global Query
Optimizer
1. Input: Global Query
(GQO)
User submits a query against the Global Conceptual Schema(GCS)
Example:
SELECT A.name, B.salary
FROM Dept A JOIN Emp B ON A.dept_id = B.dept_id
WHERE A.location = 'NY’;
2. Semantic Check & Validation
Global Query Compiler
Reads the GCS from the Global System Catalog
Verifies that all referenced tables, columns, and constraints exist
3. Decomposition & Fragment Mapping
GQO consults the fragmentation/replication mappings:
Determines which fragments of Dept and Emp live on which sites
If replicated, it identifies all candidate sites.
4. Generation of Candidate Local Plans
For each relevant site:
GQO rewrites the global query into one or more local sub-queries on
that site’s Local Conceptual Schema (LCS).
E.g., On Site 1:
SELECT A.dept_id, A.name
FROM Dept_fragment_1 A
WHERE A.location = 'NY’;
On Site 2:
SELECT B.dept_id, B.salary
FROM Emp_fragment_2 B;
5. Cost Estimation
For every possible combination of site allocations and join orders, GQO:
1. Estimate I/O and CPU cost using local statistics from each site’s Local System Catalog.
2. Estimate the network cost for shipping intermediate results between sites
3. Estimate intermediate result sizes (critical for joins)
6. Plan Selection
• GQO compares total costs of each candidate plan
• Selects the plan with the lowest estimated cost (sum of CPU + I/O + network)
7. Dispatch to Local Optimizers
For each site involved, GQO:
• Sends the optimized local sub-query to that site’s Local Query Optimizer
• Attaches any required hints (e.g., join methods, access paths)
8. Local Optimization & Execution
Local Query Optimizer may further refine the sub-query using site-specific statistics
Local Execution Engine runs the query fragment, producing either final results or intermediate tuples
9. Assembly & Final Result
• Intermediate results are shipped back (as needed) and joined/aggregated per GQO’s plan
• Global Transaction Manager coordinates commit/rollback across all sites
Federated Database Schema Architecture

• An FDBS allows integration of autonomous, distributed, and heterogeneous databases while


maintaining their independence. To support this, a five-level schema architecture is used.
1. Local Schema
• Represents the complete conceptual schema of each component database (DBS).
• Defined using the native data model of the component DBMS.
• Not directly exposed to the federation.
2. Component Schema
• A canonical (common) representation of the Local Schema.
• Translated into a common data model (CDM) for the FDBS.
• Includes mappings to convert operations on the Component Schema to the Local Schema.
3. Export Schema
• A subset of the Component Schema that the component system agrees to share with the
federation.
• Controls data visibility and access at the federated level.
Five-level schema architecture in a
Federated database system
4. Federated Schema
• Represents the integrated global view of all the Export Schemas from participating databases.
• Acts like a Global Conceptual Schema.
• Queries are written at this level and later decomposed.
5. External Schema
• Tailored views derived from the Federated Schema.
• Specific to applications or user groups.
• Similar in role to external schemas in the traditional three-level architecture.
Three-Tier Client-Server Architecture
Distributed database applications often use a three-tier client-server
architecture, especially in Web-based environments.
Three Layers in the Architecture
1. Presentation Layer (Client Tier)
Function: Handles user interaction through a graphical/web interface.
Tools & Technologies:
• Web browsers, HTML, JavaScript, CSS, Java, Flash, SVG, etc.
Responsibilities:
• Accept user inputs (e.g., search queries)
• Display output (e.g., query results)
• Manage navigation
Communication: Sends requests to the application layer using HTTP.
2. Application Layer (Middle Tier or Business Logic)
Function: Acts as the logic controller and coordinator.
Responsibilities:
• Build queries from user input
• Perform security checks, identity verification
• Interact with multiple databases via:
• ODBC, JDBC, SQL/CLI
• Format results and send them to the client layer
Other Capabilities:
• Refer to a data dictionary to understand data distribution
• Decompose global queries into local ones
• Coordinate execution and merge results
• Ensure distributed concurrency control and atomicity
3. Database Server (Back-End Tier)
Function: Stores and processes data.
Responsibilities:
• Handle query/update requests from the application server
• Execute SQL commands (relational or object-relational)
• May return data in XML format
Typically, a full centralized DBMS (e.g., SQL Server, Oracle) resides here.
How a Query Flows in a Three-Tier Architecture
1. User inputs a query via the client interface.
2. The application server:
• Interprets and decomposes it
• Sends subqueries to appropriate database servers
3. Each database server:
• Execute local subqueries
• Returns results (possibly in XML)
4. The application server:
Combines the results
Formats them (e.g., into HTML)
Sends them back to the client
Distributed Data Storage
• Replication
• System maintains multiple copies of data, stored in different sites, for faster
retrieval and fault tolerance.
• Fragmentation
• The relation is partitioned into several fragments stored in distinct sites
• Replication and fragmentation can be combined
• Relation is partitioned into several fragments: the system maintains several
identical replicas of each such fragment.
DATA STORAGE TYPES
In Distributed Databases (DDBs), data must be fragmented, replicated, and
allocated efficiently to improve performance, reliability, and local access.
These operations are planned during distributed database design.
Data Fragmentation
Fragmentation breaks a database into logical units called fragments.
A fragment can be:
• A subset of rows (horizontal)
• A subset of columns (vertical)
• Or a combination of both (mixed)

Goal:
• Place data closer to where it’s used
• Improve query performance
• Enhance availability and parallelism
Data Replication
• A relation or fragment of a relation is replicated if it is stored
redundantly in two or more sites.
• Full replication of a relation is the case where the relation is stored at
all sites.
• Fully redundant databases are those in which every site contains a
copy of the entire database.
Data Replication (Cont.)
• Advantages of Replication
• Availability: failure of a site containing relation r does not result in the unavailability of
r if replicas exist.
• Parallelism: Queries on r may be processed by several nodes in parallel.
• Reduced data transfer: relation r is available locally at each site containing a replica of
r.
• Disadvantages of Replication
• Increased cost of updates: each replica of relation r must be updated.
• Increased complexity of concurrency control: Concurrent updates to distinct replicas
may lead to inconsistent data unless special concurrency control mechanisms are
implemented.
• One solution: choose one copy as the primary copy and apply concurrency control operations on
the primary copy
Data Fragmentation
• Division of relation r into fragments r1, r2, …, rn which contain sufficient
information to reconstruct relation r.
• Horizontal fragmentation: each tuple of r is assigned to one or more fragments
• Vertical fragmentation: the schema for relation r is split into several smaller
schemas
• All schemas must contain a common candidate key (or superkey) to ensure lossless join
property.
• A special attribute, the tuple-id attribute may be added to each schema to serve as a
candidate key.
• Example : relation account with following schema
• Account-schema = (branch-name, account-number, balance)
Horizontal Fragmentation of account
Relation
branch-name account-number balance

Hillside A-305 500


Hillside A-226 336
Hillside A-155 62

account1=branch-name=“Hillside”(account)

branch-name account-number balance

Valleyview A-177 205


Valleyview A-402 10000
Valleyview A-408 1123
Valleyview A-639 750

account2=branch-name=“Valleyview”(account)
Vertical Fragmentation of employee-info
Relation
branch-name customer-name tuple-id

Hillside Lowman 1
Hillside Camp 2
Valleyview Camp 3
Valleyview Kahn 4
Hillside Kahn 5
Valleyview Kahn 6
Valleyview Green 7
deposit1=branch-name, customer-name, tuple-id(employee-info)
account number balance tuple-id

A-305 500 1
A-226 336 2
A-177 205 3
A-402 10000 4
A-155 62 5
A-408 1123 6
A-639 750 7
deposit2=account-number, balance, tuple-id(employee-info)
1. Horizontal Fragmentation
Definition: Divides a relation by rows (tuples)
Uses a condition (e.g., Dno=5) to select relevant tuples.
Each fragment stores specific rows of a relation.
EMPLOYEE1 = σDno=5(EMPLOYEE)
EMPLOYEE2 = σDno=4(EMPLOYEE)
Key Concepts:
Complete: All tuples are covered by the fragments.
Disjoint: No tuple appears in more than one fragment.
Derived Fragmentation: Use the partitioning of a primary relation to fragment related secondary relations.
2. Vertical Fragmentation
Definition: Divides a relation by columns (attributes).
Each fragment has some attributes and includes the primary key to allow rejoining.
Example:
Fragment 1:{Ssn, Name, Bdate, Address, Sex}
Fragment 2: {Ssn, Salary, Super_ssn, Dno}
Key Concepts:
Complete: All attributes are included across fragments.
Disjoint: Only primary keys can repeat between fragments.
3. Mixed (Hybrid) Fragmentation
Definition: Combination of horizontal and vertical fragmentation.
First, horizontally fragment based on some condition, then apply vertical fragmentation to
each horizontal fragment (or vice versa).
πL1(σDno=5(EMPLOYEE)), where L1 = {Ssn, Name}
Advantages of Fragmentation
• Horizontal:
• allows parallel processing on fragments of a relation
• allows a relation to be split so that tuples are located where they are most
frequently accessed
• Vertical:
• allows tuples to be split so that each part of the tuple is stored where it is
most frequently accessed
• tuple-id attribute allows efficient joining of vertical fragments
• allows parallel processing on a relation
• Vertical and horizontal fragmentation can be mixed.
• Fragments may be successively fragmented to an arbitrary depth.
Data Transparency
• Data transparency: Degree to which system user may remain
unaware of the details of how and where the data items are stored in
a distributed system
• Consider transparency issues in relation to:
• Fragmentation transparency
• Replication transparency
• Location transparency
Distributed Transactions
• Transaction may access data at several sites.
• Each site has a local transaction manager responsible for:
• Maintaining a log for recovery purposes
• Participating in coordinating the concurrent execution of the transactions
executing at that site.
• Each site has a transaction coordinator, which is responsible for:
• Starting the execution of transactions that originate at the site.
• Distributing subtransactions at appropriate sites for execution.
• Coordinating the termination of each transaction that originates at the site,
which may result in the transaction being committed at all sites or aborted at
all sites.
Transaction System Architecture
Commit Protocols
• Commit protocols are used to ensure atomicity across sites
• a transaction which executes at multiple sites must either be committed at all
the sites, or aborted at all the sites.
• not acceptable to have a transaction committed at one site and aborted at
another
• The two-phase commit (2 PC) protocol is widely used
• The three-phase commit (3 PC) protocol is more complicated and
more expensive, but avoids some drawbacks of two-phase commit
protocol.
Two Phase Commit Protocol (2PC)
• Assumes fail-stop model – failed sites simply stop working, and do
not cause any other harm, such as sending incorrect messages to
other sites.
• Execution of the protocol is initiated by the coordinator after the last
step of the transaction has been reached.
• The protocol involves all the local sites at which the transaction
executed
• Let T be a transaction initiated at site Si, and let the transaction
coordinator at Si be Ci
Phase 1: Obtaining a Decision
• Coordinator asks all participants to prepare to commit transaction Ti.
• Ci adds the records <prepare T> to the log and forces log to stable storage
• sends prepare T messages to all sites at which T executed
• Upon receiving message, transaction manager at site determines if it
can commit the transaction
• if not, add a record <no T> to the log and send abort T message to Ci
• if the transaction can be committed, then:
• add the record <ready T> to the log
• force all records for T to stable storage
• send ready T message to Ci
Phase 2: Recording the Decision
• T can be committed of Ci received a ready T message from all the
participating sites: otherwise T must be aborted.
• Coordinator adds a decision record, <commit T> or <abort T>, to the
log and forces record onto stable storage. Once the record stable
storage it is irrevocable (even if failures occur)
• Coordinator sends a message to each participant informing it of the
decision (commit or abort)
• Participants take appropriate action locally.
Handling of Failures - Site Failure
When site Si recovers, it examines its log to determine the fate of
transactions active at the time of the failure.
• Log contain <commit T> record: site executes redo (T)
• Log contains <abort T> record: site executes undo (T)
• Log contains <ready T> record: site must consult Ci to determine the fate of T.
• If T committed, redo (T)
• If T aborted, undo (T)
• The log contains no control records concerning T replies that Sk failed before responding
to the prepare T message from Ci
• since the failure of Sk precludes the sending of such a
response C1 must abort T
• Sk must execute undo (T)
Handling of Failures- Coordinator
Failure
• If coordinator fails while the commit protocol for T is executing then
participating sites must decide on T’s fate:
1. If an active site contains a <commit T> record in its log, then T must be committed.
2. If an active site contains an <abort T> record in its log, then T must be aborted.
3. If some active participating site does not contain a <ready T> record in its log, then
the failed coordinator Ci cannot have decided to commit T. Can therefore abort T.
4. If none of the above cases holds, then all active sites must have a <ready T> record
in their logs, but no additional control records (such as <abort T> of <commit T>).
In this case active sites must wait for Ci to recover, to find decision.
• Blocking problem : active sites may have to wait for failed coordinator to
recover.
Handling of Failures - Network
Partition
• If the coordinator and all its participants remain in one partition, the
failure has no effect on the commit protocol.
• If the coordinator and its participants belong to several partitions:
• Sites that are not in the partition containing the coordinator think the
coordinator has failed, and execute the protocol to deal with failure of the
coordinator.
• No harm results, but sites may still have to wait for decision from coordinator.
• The coordinator and the sites are in the same partition as the
coordinator think that the sites in the other partition have failed, and
follow the usual commit protocol.
• Again, no harm results
Three Phase Commit (3PC)
• Assumptions:
• No network partitioning
• At any point, at least one site must be up.
• At most K sites (participants as well as coordinator) can fail
• Phase 1: Obtaining Preliminary Decision: Identical to 2PC Phase 1.
• Every site is ready to commit if instructed to do so
• Phase 2 of 2PC is split into 2 phases, Phase 2 and Phase 3 of 3PC
• In phase 2 coordinator makes a decision as in 2PC (called the pre-commit decision) and records it in multiple (at least K)
sites
• In phase 3, coordinator sends commit/abort message to all participating sites,
• Under 3PC, knowledge of pre-commit decision can be used to commit despite coordinator failure
• Avoids blocking problem as long as < K sites fail
• Drawbacks:
• higher overheads
• assumptions may not be satisfied in practice
Operating System Support for Transaction Management
• The following are the main benefits of operating system (OS)-supported
transaction management:
• Typically, DBMSs use their own semaphores to guarantee mutually exclusive
access to shared resources. Since these semaphores are implemented in
userspace at the level of the DBMS application software, the OS has no
knowledge about them. Hence if the OS deactivates a DBMS process holding
a lock, other DBMS processes wanting this lock resource get queued. Such a
situation can cause serious performance degradation. OS-level knowledge of
semaphores can help eliminate such situations.
• Specialized hardware support for locking can be exploited to reduce
associated costs. This can be of great importance, since locking is one of the
most common DBMS operations.
• Providing a set of common transaction support operations though the kernel
allows application developers to focus on adding new features to their
products as opposed to reimplementing the common functionality for each
application. For example, if different DDBMSs are to coexist on the same
machine and they chose the two-phase commit protocol, then it is more
beneficial to have this protocol implemented as part of the kernel so that the
DDBMS developers can focus more on adding new features to their products.
Query Processing and Optimization in Distributed
Databases
In Distributed Database Systems (DDBS), query processing and optimization are critical for ensuring that user
queries execute efficiently across multiple distributed sites. Below is a detailed explanation:
1. What is Query Processing?
Query processing in DDB involves:
Translating a high-level query (like SQL) into a low-level execution plan.
Accessing and retrieving data from multiple distributed fragments located at different sites.
Ensuring correctness, completeness, and efficiency of results.
2. Challenges in Distributed Query Processing
Data Distribution: Data may be fragmented and stored across different locations.
Communication Cost: Data transmission between sites is expensive.
Heterogeneity: Different sites may have different DBMSs.
Latency: Query response time increases with remote access.
Concurrency and Synchronization: Coordinating multiple data sources is complex.
3. Steps in Distributed Query Processing
Step Description
Break down the SQL query into an algebraic query tree
1. Query Decomposition
or logical plan.
2. Data Localization Identify the fragments and sites involved in the query.
Generate alternative query plans using relational
3. Global Optimization
algebra.
4. Local Optimization Optimize query execution at individual sites.
Schedule and execute subqueries in parallel across the
5. Distributed Execution
network.

4. Query Optimization in DDB


Query optimization selects the most efficient execution strategy among many
possibilities. It aims to minimize:
Communication Cost
Disk I/O
CPU usage
Response time
• Types of Optimization
Type Description
Uses predefined rules to choose plans (e.g., "do
Rule-based
selection before join").
Evaluates costs (I/O, transmission) of multiple plans
Cost-based
and selects the least expensive one.

5. Query Optimization Strategies


A. Reduction of Data Movement
Perform selection and projection operations at local sites before transferring data.
Example: Filter employees locally before joining with department data on another site.
B. Semi-Join Strategy
A semi-join fetches only the required matching rows instead of full join tables.
Reduces the amount of data transferred between sites.
C. Join Ordering Optimization
Joins are ordered to reduce intermediate result sizes and communication overhead.
D. Use of Parallelism
Execute subqueries in parallel at multiple sites to reduce total execution time.
6. Example Workflow
SELECT E.name, D.dept_name
FROM Employee E, Department D
WHERE E.dept_id = D.dept_id AND D.location = 'Chennai’;
Optimization Steps:
1. Decompose query into join and selection operations.
2. Localize data: Find that Employee and Department fragments
are on different sites.
3. Push selection (D.location = 'Chennai') to the site containing
Department
4. Use a semi-join to reduce data transferred from Employee site.
5. Join results and project required attributes.
7. Cost Model in Optimization
Optimization depends on estimating:
CPU cost
I/O cost
Communication cost (dominant in DDB)
Formula-based cost models help determine the best plan.
8. Distributed Query Execution Plan (DQEP)
Specifies:
Order of operations (joins, selections)
Locations where each operation takes place
Communication paths and methods
9. Conclusion
Query processing and optimization in distributed databases are more complex than in centralized systems due
to:
Data fragmentation,
Site autonomy,
Network communication overhead.
A well-optimized query ensures:
• Minimal response time,
• Efficient resource use,
• Reduced data transmission,
NoSQL Databases
Introduction, Advanced Databases, Queries and Commands
Introduction to NoSQL
• Definition:
NoSQL (Not Only SQL) databases are a category of database
management systems that do not use the traditional relational
database model. They are designed to handle large volumes of
unstructured, semi-structured, and structured data, often with high
performance and horizontal scalability.
Why NoSQL?
Limitations of RDBMS:
• Not suitable for big data or real-time web applications.
• Poor performance with high write/read throughput.
• Difficult to scale horizontally (across multiple machines).
Advantages of NoSQL:
• Schema-less or dynamic schema.
• Highly scalable horizontally (cloud-friendly).
• Supports distributed architecture.
• Suitable for unstructured data (e.g., JSON, XML).
Types of NoSQL Databases
Type Description Example
Stores data as documents (usually
1. Document Store MongoDB, CouchDB
JSON/BSON/XML).
Data stored as key-value pairs. Very
2. Key-Value Store Redis, DynamoDB
fast and simple.
Stores data in columns instead of
3. Column Store Apache Cassandra, HBase
rows. Best for analytical workloads.
Uses nodes and edges to represent
4. Graph Database Neo4j, Amazon Neptune
relationships.
Features of NoSQL
• Flexible data model – No fixed schema.
• Horizontal scaling – Easily add more machines.
• High performance – Suitable for real-time apps.
• Replication and Partitioning – Built-in data distribution.
• Open-source and cloud compatible.
Use Cases of NoSQL
Use Case Suitable NoSQL Type
User profile storage Document Store (MongoDB)
Caching session data Key-Value Store (Redis)
Real-time analytics Column Store (Cassandra)
Social network connections Graph Database (Neo4j)
Popular NoSQL Databases
Advanced NoSQL Databases:
• MongoDB: Document-oriented. Uses BSON format. Dynamic schema.
• Apache Cassandra: High availability, column-family store.
• Neo4j: Graph database with Cypher query language.
• Amazon DynamoDB: Key-value store, managed by AWS.
• CouchDB: Document store using JSON and HTTP/REST.
NoSQL vs SQL
Feature SQL (RDBMS) NoSQL
Data Format Tables (rows, columns) JSON, key-value, graphs
Schema Fixed schema Dynamic/Schema-less
Scaling Vertical Horizontal
Query Language SQL Varies (MongoDB, Cypher)
Best for Structured data Big, semi/unstructured data
MongoDB Commands
• Insert: db.students.insertOne({name: 'John'})
• Find: db.students.find({age: {$gt: 18}})
• Update: db.students.updateOne({name: 'John'}, {$set: {age: 21}})
• Delete: db.students.deleteOne({name: 'John'})
Redis & Cassandra

SET name "John"


GET name
DEL name
Cassandra (Column Store - CQL)
-- Creating a keyspace
CREATE KEYSPACE college WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};

-- Creating a table
CREATE TABLE college.students (id int PRIMARY KEY, name text, age int);

-- Inserting data
INSERT INTO college.students (id, name, age) VALUES (1, 'John', 20);

-- Querying data
SELECT * FROM college.students;
Neo4j Queries
• // Creating nodes
CREATE (s:Student {name:'John', age:20})
CREATE (c:Course {name:'DBMS'})

• // Creating relationship
MATCH (s:Student), (c:Course)
WHERE s.name='John' AND c.name='DBMS’
CREATE (s)-[:ENROLLED_IN]->(c)

// Querying relationships
MATCH (s:Student)-[:ENROLLED_IN]->(c:Course)
RETURN s.name, c.name
Key terminologies
Term Meaning
Sharding Distributing data across multiple servers.
Replication Copying data across servers for availability.
A distributed database can only guarantee 2 of
CAP Theorem Consistency, Availability, and Partition Tolerance at a
time.
Basically Available, Soft state, Eventual consistency –
BASE Model
NoSQL model vs ACID (SQL).
NoSQL
• NoSQL supports big data, real-time, and flexible applications.
• Understanding types, features, and queries is essential.
• Vital for modern apps in AI/ML, IoT, and cloud environments.
CAP Theorem: Concept and Proof
Introduction
The CAP Theorem, also known as Brewer's Theorem, is a fundamental concept in distributed database
systems. It states that a distributed system cannot simultaneously guarantee all three of the following properties:
1. Consistency (C)
2. Availability (A)
3. Partition Tolerance (P)
This theorem is extremely important for understanding the trade-offs in NoSQL and distributed databases.
Key Terms Explained
1. Consistency
Every read receives the most recent write.
All nodes return the same data even if read at the same time.
2. Availability
Every request receives a (non-error) response, without guarantee that it contains the most recent data.
3. Partition Tolerance
The system continues to operate despite network failures (message loss or delays) between nodes in a
distributed system.
CAP Theorem Statement
In the presence of a network partition, a distributed system can provide only two of the three guarantees: Consistency, Availability, or Partition
Tolerance.
So, a system must sacrifice one of the properties when there is a partition.
Proof:
Let's assume a distributed system with two nodes (Node A and Node B), and a network partition occurs (A cannot communicate with B).
Suppose:
A client writes data to Node A.
At the same time, another client tries to read from Node B.
Now the system must choose:
Case 1: Prioritize Availability and Partition Tolerance
Node B responds to the read request (Available) despite not getting the latest write from A (Inconsistent).
So, it satisfies Partition Tolerance, Availability, but not Consistency.
Case 2: Prioritize Consistency and Partition Tolerance
Node B refuses the read or delays it until the partition resolves (to ensure consistency).
So, it satisfies Partition Tolerance, Consistency, but not Availability.
Case 3: Prioritize Consistency and Availability
This would require no network partition, because consistency requires communication between A and B.
But partition tolerance is a must in real-world systems ⇒ Not feasible in distributed systems.
You must choose 2 out of 3, not all 3, especially in the presence of a partition.
CAP Combinations and Examples
Chosen Properties Sacrificed Database Examples
Rare in real systems (single node
Consistency + Availability Partition Tolerance
systems)
Consistency + Partition Tolerance Availability HBase, MongoDB (in CP mode)
Availability + Partition Tolerance Consistency Cassandra, CouchDB (in AP mode)

• CAP Theorem guides how to design distributed databases.


• No system can guarantee all three properties simultaneously in case of a network partition.
• System designers must choose a trade-off depending on the application needs (e.g., banking needs
C + P, social networks may prefer A + P).
Introduction to Database Security Issues
Types of Database Security
Database security refers to the measures and controls that ensure the confidentiality, integrity, and availability of
data stored in a database. It encompasses a wide range of concerns, from legal policies to technical
implementations.
1. Legal and Ethical Issues
Certain types of information are governed by laws and ethical standards. Unauthorized access to such information is not only
unethical but often illegal.
Examples:
• Medical records are protected under laws such as HIPAA (in the U.S.).
• Personal identity information (like SSNs or Aadhaar numbers) cannot be accessed without proper authorization.
2. Policy Issues (Governmental/Corporate/Institutional)
Policies dictate what types of data can be made public or must be kept private.
Examples:
• Government policies may classify documents as confidential or public.
• Companies may restrict access to financial data, credit scores, or intellectual property.
3. System-Related Issues
These issues
Levelinvolve determining at what level the security mechanisms
Description should be applied.
Levels ofPhysical
Enforcement:
Level Locks, restricted room access, secure servers
Operating System Level File permissions, user authentication
DBMS Level User roles, query restrictions, data encryption
4. Multilevel Security and Classification
Some organizations require multi-tiered security models, especially in defence or government sectors.
Classification of Data & Users:

Classification Access Level


Top Secret Highest restriction
Secret Restricted to specific roles
Confidential Limited to certain groups
Unclassified Accessible by most users
Threats to Database
• Loss of integrity - Database integrity refers to the requirement that information be
protected from improper modification. Integrity is lost if unauthorized changes are
made to the data by either intentional or accidental acts.
• Loss of availability - Database availability refers to making objects available to a
human user or a program to which they have a legitimate right.
• Loss of confidentiality. Database confidentiality refers to the protection of data from
unauthorized disclosure. The impact of unauthorized disclosure of confidential
information can range from violation of the Data Privacy Act to the jeopardization of
national security.
To protect databases against these types of threats, it is common to implement
four kinds of control measures:
• access control,
• inference control,
• flow control, and
• encryption.
Database Security and Authorization Subsystem
• A DBMS typically includes a database security and authorization subsystem that
is responsible for ensuring the security of portions of a database against unauthorized
access.
• Discretionary security mechanisms. These are used to grant privileges to users,
including the capability to access specific data files, records, or fields in a specified
mode (such as read, insert, delete, or update).
• Mandatory security mechanisms. These are used to enforce multilevel security by
classifying the data and users into various security classes (or levels) and then
implementing the appropriate security policy of the organization.
• For example, a typical security policy is to permit users at a certain classification
(or clearance) level to see only the data items classified at the user’s own (or
lower) classification level. An extension of this is role-based security, which
enforces policies and privileges based on the concept of organizational roles.
Four control measures
1. Access Control - Access control is a mechanism that restricts access to the database system only to authorized
users. It is handled by creating user accounts and passwords to control the login process by the
DBMS.
2. Inference Control - Security for statistical databases must ensure that information about
individuals cannot be accessed. It is sometimes possible to deduce or infer certain facts
concerning individuals from queries that involve only summary statistics on groups;
consequently, this must not be permitted either. This problem, called statistical database
security, and the corresponding control measures are called inference control measures.
3. Flow Control - Another security issue is that of flow control, which prevents information
from flowing in such a way that it reaches unauthorized users.
• Channels that are pathways for information to flow implicitly in ways that violate the
security policy of an organization are called covert channels.
4. Data encryption - A final control measure is data encryption, which is used to protect
sensitive data (such as credit card numbers) that is transmitted via some type of
communications network. Encryption can be used to provide additional protection for sensitive
portions of a database as well.
The data is encoded using some coding algorithm. An unauthorized user who
accesses encoded data will have difficulty deciphering it, but authorized users are given
decoding or decrypting algorithms (or keys) to decipher the data
Access Control based on Privileges
1. Privilege Enforcement in SQL
• Discretionary Access Control is enforced by granting and revoking privileges to/from users (or accounts).
• SQL provides statements like GRANT and REVOKE for this purpose.
2. Two Levels of Privileges
(i) Account Level Privileges
Privileges granted independently of relations.
Examples:
CREATE SCHEMA, CREATE TABLE, CREATE VIEW, ALTER, DROP, MODIFY, SELECT
(ii) Relation (Table/View) Level Privileges
Privileges granted on specific relations or views.
SQL2 supports:
SELECT, INSERT, DELETE, UPDATE, REFERENCES
3. Ownership and Granting Privileges
Owner of a relation is the account that created it.
Owner has all privileges on that relation.
Owner can use GRANT to give specific privileges to others.
4. Views for Authorization
Views can restrict access:
To specific columns.
To specific tuples.
Helps implement fine-grained access control.
E.g., Account A creates a view V over R with selected columns/rows and grants SELECT on V to Account B.
5. Revoking Privileges
Use REVOKE command to remove privileges.
Useful for temporary access.
When revoked, the system must track and remove propagated privileges (if applicable).
6. Privilege Propagation with GRANT OPTION
When using GRANT ... WITH GRANT OPTION the recipient can further grant the privilege.
Privileges can propagate like a tree.
If the original privilege is revoked, the system must recursively revoke all propagated privileges.
Example:
• A grants SELECT on R to B with GRANT OPTION.
• B grants it to C (also with GRANT OPTION).
• If A revokes from B, then C also loses it (if C only got it through B).
7. Multiple Grant Sources
If a user receives the same privilege from multiple sources:
• Revocation from one source does not remove the privilege.
• The privilege is lost only when all sources revoke.
Granting and Revoking Privileges – Example
1. DBA creates Accounts - Account Created: A1, A2, A3, A4
2. Allow Only A1 to Create Tables - GRANT CREATETAB TO A1;
3. A1 Creates Tables: A1 creates EMPLOYEE, DEPARTMENT
A1 is the owner and has all privileges on both tables.
4. A1 Grants Privileges to A2 (No Propagation) - GRANT INSERT, DELETE ON EMPLOYEE, DEPARTMENT TO
A2;
5. A1 Grants SELECT with Propagation to A3 - GRANT SELECT ON EMPLOYEE, DEPARTMENT TO A3 WITH
GRANT OPTION;
6. A1 Revokes SELECT from A3 - REVOKE SELECT ON EMPLOYEE FROM A3;

You might also like