UNIT I
RELATIONAL
DATABASES
Database System – Data Models – Database System
Architecture – Relational Model – Keys – Relational Algebra –
SQL fundamentals – Advanced SQL
features – Embedded SQL
INTRODUCTION DATABASE SYSTEM
Database is collection of data which is related by some
aspect. Data is collection of facts and figures which can
be processed to produce information.
A database management system stores data, in such a
way which is easier to retrieve, manipulate and helps to
produce information.
So a database is a collection of related data that we can
use for
Defining - specifying types of data
Constructing - storing & populating
Manipulating - querying, updating, reporting
DISADVANTAGES OF FILE SYSTEM OVER DB
Drawbacks of using file systems to store data:
Data redundancy and inconsistency
Difficulty in accessing data
Data isolation — multiple files and formats
Integrity problems
- Hard to add new constraints or change existing ones
Atomicity problem
E.g. transfer of funds from one account to another should either
complete or not happen at all
Concurrent access anomalies
- Concurrent accessed needed for performance
Security problems
Database systems offer solutions to all the above problems
PURPOSE OF DATABASE SYSTEM
[Link] redundancy and inconsistency:
In file processing, every user group maintains its own files
for handling its data processing applications.
Storing the same data multiple times is called data
[Link] redundancy leads to several problems.
• Need to perform a single logical update multiple times.
• Storage space is wasted.
• Files that represent the same data may become
inconsistent.
Data inconsistency is the various copies of the same data
may no larger Agree. Example: One user group may enter a
student's birth date erroneously as JAN-19-1984, whereas
[Link] in accessing data
File processing environments do not allow needed data to be
retrieved in a convenient and efficient manner.
[Link] isolation
Because data are scattered in various files, and files may be in
different formats, writing new application programs to retrieve
the appropriate data is difficult.
[Link] problems
The data values stored in the database must satisfy certain types of
consistency constraints. Developers enforce these constraints in the
system by addition appropriate code in the various application
programs
[Link] problems
Atomic means the transaction must happen in its entirety or
not at all. It is difficult to ensure atomicity in a conventional file
[Link] access anomalies
For the sake of overall performance of the system
and faster response, many systems allow multiple
users to update the data simultaneously.
[Link] problems
Enforcing security constraints to the file processing
system is difficult.
APPLICATION OF DATABASE
Banking: all transactions
Airlines: reservations, schedules
Universities: registration, grades
Sales: customers, products, purchases
Manufacturing: production, inventory, orders, supply
chain
Human resources: employee records, salaries, tax
deductions
Telecommunication: Call History, Billing
Credit card transactions: Purchase details, Statements
VIEWS OF DATA
Data abstraction
Instances and schemas
Data abstraction has three level of abstractions
Physical level
DATA MODELS IN DBMS
A Data Model is a logical structure of Database. It describes the design of
database to reflect entities, attributes, relationship among data,
constrains etc
Types of Data Models:
1. E-R Model
An entity–relationship model (ER model) is a systematic way of describing
and defining a business process. An ER model is typically implemented as
2. Object oriented Model
An object data model is a data model based on object-oriented programming,
associating methods (procedures) with objects that can benefit from class
hierarchies.
Record based logical Models
These models specify logical structure of database with records, fields and
attributes.
1. Relational Model
2. Hierarchical
Model
3. Network Model – Network Model is same as hierarchical model except
that it has graph-like structure rather than a tree-based structure. Unlike
hierarchical model, this model allows each record to have more than one
parent record.
Physical Data Models – These models describe data at the lowest level of
abstraction
DATABASE System (Three Schema)
Architecture
1. The internal level
2. The conceptual level
3. The External or View level
COMPONENTS OF DBMS
Database Users are differentiated by the way they expect to interact with the
system
• Application programmers
• Sophisticated users
• Naïve users
• Database Administrator
• Specialized users etc,.
RELATIONAL
DATABASE
A relational database is a database system in which the database is
organized and accessed according to the relationships between data items
without the need for any consideration of physical orientation and
relationship.
Relationships between data items are expressed by means of tables.
RELATIONAL DATABASE MANAGEMENT SYSTEM
A Relational Database Management System (RDBMS) is a system, which allows
us to perceive data as tables (and nothing but tables), and operators
necessary to manipulate that data are at the user’s disposal.
Features of an RDBMS
The features of a relational database are as follows:
The ability to create multiple relations (tables) and enter data into them
An interactive query language
Retrieval of information stored in more than one table
Provides a Catalog or Dictionary, which itself consists of tables ( called
system tables )
Catalog:
A catalog consists of all the information of the various schemas
(external, conceptual and internal) and also all of the
corresponding mappings (external/conceptual,
conceptual/internal).
It contains detailed information regarding the various objects that are of
interest to the system itself; e.g., tables, views, indexes, users, integrity
rules, security rules, etc.
KEYS AND THEIR USE
Key: An attribute or set of attributes whose values uniquely identify each
entity in an entity set is called a key for that entity set.
Super Key
Primary Key
Foreign Key
Secondary Key
Referential Integrity
Referential Integrity can be defined as an integrity constraint that specifies
that the value (or existence) of an attribute in one relation depend on the
value (or existence) of an attribute in the same or another relation.
Relational Model
Relational data model is the primary data model, which is used widely
around the world for data storage and processing.
Concepts
Tables
Relation
instance
Relation
schema
Relation key
Attribute
domain
Constraints
Relational
Integrity
Relational Algebra
The fundamental operations of relational algebra are as follows −
Select Select Operation (σ)
For example −
σsubject = "database"(Books)
Output − Selects tuples from books where subject is 'database'.
σsubject = "database" and price = "450"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450 or
those books published after 2010
Project
For example −∏subject, author (Books)
Selects and projects columns named as subject and author from the relation
Books.
Union Notation − r U s
Duplicate tuples are
automatically eliminated.
∏ author (Books) ∪ ∏
Set
different
Notation − r
−s
Finds all the
tuples that
are present
in r but not in
s.
∏ author
(Books) − ∏
author
(Articles)
Output −
Provides the
name of
authors who
have written
books but not
articles
Cartesian
product Notation
SQL FUNDAMENTALS:
SQL is a standard computer language for accessing and manipulating
databases.
SQL stands for Structured Query Language
SQL allows you to access a database
SQL is an ANSI standard computer language
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert new records in a database
SQL can delete records from a database
SQL can update records in a database
SQL is easy to learn
SQL Database Tables
A database most often contains one or more tables. Each table is identified
by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with
data. Below is an example of a table called "Persons":
SQL Queries
With SQL, we can query a database and have a result set returned.
A query like this:
SELECT LastName FROM Persons
Gives a result set like this:
LastName
Hansen Svendson
Pettersen
SQL Data Manipulation Language (DML)
SELECT - extracts data from a database table
UPDATE - updates data in a database table
DELETE - deletes data from a database table
INSERT INTO - inserts new data into a
database table
SQL Data Definition Language (DDL)
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database
table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
The SQL SELECT
Statement SQL SELECT
Example
SELECT LastName,FirstName FROM Persons
Select All
Columns
To select only DIFFERENT values from the column named "Company" we
use a SELECT DISTINCT statement like this:
The WHERE clause is used to specify a selection
criterion The WHERE Clause
To conditionally select data from a table, a WHERE clause can be added to
the SELECT statement.
Syntax
SELECT column FROM
table WHERE column
operator value
With the WHERE clause,
the following operators
can be used:
Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a WHERE
clause to the
SELECT statement:
SELECT * FROM
Persons WHERE
City='Sandnes'
Using Quotes
For text
values:
This is
correct:
SELECT * FROM Persons WHERE
FirstName='Tove' This is wrong:
SELECT * FROM Persons WHERE
FirstName=Tove For numeric values:
This is correct:
SELECT * FROM Persons WHERE
Year>1965 This is wrong:
The LIKE Condition
A "%" sign can be used to define wildcards (missing letters in the pattern) both before
and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start
with an 'O': SELECT * FROM Persons
WHERE FirstName LIKE 'O%'
The following SQL statement will return persons with first names that end
with an 'a': SELECT * FROM Persons
WHERE FirstName LIKE '%a'
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into
a table. Syntax
INSERT INTO table_name
VALUES (value1,
value2,....)
You can also specify the columns for which you want to
insert data: INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
UPDATE statement
UPDATE table_name
SET column_name = new_value
WHERE column_name =
some_value
The DELETE Statement
The DELETE statement is used to delete rows in a
table. Syntax
DELETE FROM table_name
WHERE column_name = some_value
The ORDER BY keyword is used to sort the
result.
ADVANCED SQL
FEATURES
GROUP
BY
EMBEDDED SQL
Embedded SQL is a method of inserting inline SQL statements or queries
into the code of a programming language, which is known as a host
language. Because the host language cannot parse SQL, the inserted
SQL is parsed by an embedded SQL preprocessor.
Structure of embedded SQL
EXEC SQL BEGIN DECLARE SECTION;
int STD_ID;
char STD_NAME
[15]; char
ADDRESS[20];
EXEC SQL END
DECLARE
SECTION;
int main() {
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
int OrderID; /* Employee ID (from
user) */ int CustID; /* Retrieved
customer ID */
char SalesPerson[10] /* Retrieved salesperson
name */ char Status[6] /* Retrieved order status
*/
EXEC SQL END DECLARE SECTION;
/* Set up error processing */
EXEC SQL WHENEVER SQLERROR GOTO
query_error; EXEC SQL WHENEVER NOT FOUND
GOTO bad_number;
/* Prompt the user for order
number */ printf ("Enter order
number: "); scanf_s("%d",
&OrderID);
/* Execute the SQL query */
EXEC SQL SELECT CustID, SalesPerson,
Status FROM Orders
WHERE OrderID = :OrderID
INTO :CustID, :SalesPerson, :Status;
/* Display the results */
printf ("Customer number: %d\n",
CustID); printf ("Salesperson: %s\n",
SalesPerson); printf ("Status: %s\n",
Status);
exit();
query_erro
r:
printf ("SQL error: %ld\n", sqlca-
>sqlcode); exit();
bad_number:
printf ("Invalid order number.\
n"); exit();
}
EXECUTE
This statement is used to compile and execute the SQL statements
prepared in DB.
EXEC SQL EXECUTE sql_query;