0% found this document useful (0 votes)
18 views

DBMS Unit-2

Uploaded by

whtpepsi1999
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

DBMS Unit-2

Uploaded by

whtpepsi1999
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit-2

Relational data model is the primary data model, which is used widely around the world for
data storage and processing. This model is simple and it has all the properties and
capabilities required to process data with storage efficiency.

Concepts

Tables − In relational data model, relations are saved in the format of Tables. This format
stores the relation among entities. A table has rows and columns, where a row represents
records and columns represent the attributes.

Tuple − A single row of a table, which contains a single record for that relation is called a
tuple.

Relation instance − A finite set of tuples in the relational database system represents
relation instance. Relation instances do not have duplicate tuples.

Relation schema − A relation schema describes the relation name (table name), attributes,
and their names.

Relation key − Each row has one or more attributes, known as relation key, which can
identify the row in the relation (table) uniquely.

Attribute domain − Every attribute has some pre-defined value scope, known as attribute
domain.

Constraints

Every relation has some conditions that must hold for it to be a valid relation. These
conditions are called Relational Integrity Constraints. There are three main integrity
constraints −

 Key constraints

 Domain constraints

 Referential integrity constraints

Key Constraints
There must be at least one minimal subset of attributes in the relation, which can identify a
tuple uniquely. This minimal subset of attributes is called key for that relation. If there are
more than one such minimal subsets, these are called candidate keys.

Key constraints force that −

 in a relation with a key attribute, no two tuples can have identical values for key
attributes.

 a key attribute can not have NULL values.

Key constraints are also referred to as Entity Constraints.

Domain Constraints

Attributes have specific values in real-world scenario. For example, age can only be a
positive integer. The same constraints have been tried to employ on the attributes of a
relation. Every attribute is bound to have a specific range of values. For example, age cannot
be less than zero and telephone numbers cannot contain a digit outside 0-9.

Referential integrity Constraints

Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a
key attribute of a relation that can be referred in other relation.

Referential integrity constraint states that if a relation refers to a key attribute of a different
or same relation, then that key element must exist.

What are Keys in DBMS?

KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple)
in a relation(table). They allow you to find the relation between two tables. Keys help you
uniquely identify a row in a table by a combination of one or more columns in that table.
Key is also helpful for finding unique record or row from the table. Database key is also
helpful for finding unique record or row from the table.

Example:

Employee ID FirstName LastName

11 Andrew Johnson

22 Tom Wood

33 Alex Hale
In the above-given example, employee ID is a primary key because it uniquely identifies an
employee record. In this table, no other employee can have the same employee ID.

Types of Keys in DBMS (Database Management System)

There are mainly Eight different types of Keys in DBMS and each key has it’s different
functionality:

1. Super Key

2. Primary Key

3. Candidate Key

4. Alternate Key

5. Foreign Key

6. Compound Key

 Super Key – A super key is a group of single or multiple keys which identifies rows
in a table.

 Primary Key – is a column or group of columns in a table that uniquely identify


every row in that table.

 Candidate Key – is a set of attributes that uniquely identify tuples in a table.


Candidate Key is a super key with no repeated attributes.

 Alternate Key – is a column or group of columns in a table that uniquely identify


every row in that table.

 Foreign Key – is a column that creates a relationship between two tables. The
purpose of Foreign keys is to maintain data integrity and allow navigation between
two different instances of an entity.

What is the Super key?

A superkey is a group of single or multiple keys which identifies rows in a table. A Super
key may have additional attributes that are not needed for unique identification.
Example:

EmpSSN EmpNum Empname

9812345098 AB05 Shown

9876512345 AB06 Roslyn

199937890 AB07 James

In the above-given example, EmpSSN and EmpNum name are superkeys.

What is a Primary Key?

PRIMARY KEY in DBMS is a column or group of columns in a table that uniquely


identify every row in that table. The Primary Key can’t be a duplicate meaning the same
value can’t appear more than once in the table. A table cannot have more than one primary
key.

Rules for defining Primary key:

 Two rows can’t have the same primary key value

 It must for every row to have a primary key value.

 The primary key field cannot be null.

 The value in a primary key column can never be modified or updated if any foreign
key refers to that primary key.

Example:

In the following example, StudID is a Primary Key.

StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is the Alternate key?


ALTERNATE KEYS is a column or group of columns in a table that uniquely identify
every row in that table. A table can have multiple choices for a primary key but only one
can be set as the primary key. All the keys which are not primary key are called an Alternate
Key.

Example:

In this table, StudID, Roll No, Email are qualified to become a primary key. But since
StudID is the primary key, Roll No, Email becomes the alternative key.

StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is a Candidate Key?

CANDIDATE KEY in SQL is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes. The Primary key should be
selected from the candidate keys. Every table must have at least a single candidate key. A
table can have multiple candidate keys but only a single primary key.

Properties of Candidate key:

 It must contain unique values

 Candidate key in SQL may have multiple attributes

 Must not contain null values

 It should contain minimum fields to ensure uniqueness

 Uniquely identify each record in a table

Candidate key Example: In the given table Stud ID, Roll No, and email are candidate keys
which help us to uniquely identify the student record in the table.

StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]


StudID Roll No First Name LastName Email

Candidate Key in DBMS

What is the Foreign key?

FOREIGN KEY is a column that creates a relationship between two tables. The purpose of
Foreign keys is to maintain data integrity and allow navigation between two different
instances of an entity. It acts as a cross-reference between two tables as it references the
primary key of another table.

Example:

DeptCode DeptName

001 Science

002 English

005 Computer

Teacher ID Fname Lname

B002 David Warner

B017 Sara Joseph

B009 Mike Brunton

In this key in dbms example, we have two table, teach and department in a school. However,
there is no way to see which search work in which department.
In this table, adding the foreign key in Deptcode to the Teacher name, we can create a
relationship between the two tables.

Teacher ID DeptCode Fname

B002 002 David

B017 002 Sara

B009 001 Mike

This concept is also known as Referential Integrity.

What is the Compound key?

COMPOUND KEY has two or more attributes that allow you to uniquely recognize a
specific record. It is possible that each column may not be unique by itself within the
database. However, when combined with the other column or columns the combination of
composite keys become unique. The purpose of the compound key in database is to
uniquely identify each record in the table.

Example:

OrderNo ProductID Product Name

B005 JAP102459 Mouse

B005 DKT321573 USB

B005 OMG446789 LCD Monitor

B004 DKT321573 USB

B002 OMG446789 Laser Printer

In this example, OrderNo and ProductID can’t be a primary key as it does not uniquely
identify a record. However, a compound key of Order ID and Product ID could be used as it
uniquely identified each record.
Relational Algebra

Relational algebra is a procedural query language. It gives a step by step process to obtain
the result of the query. It uses operators to perform queries.

Types of Relational operation

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.

o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and
NOT. These relational can use as relational operators like =, ≠, ≥, <, >, ≤.
For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in the result.
Rest of the attributes are eliminated from the table.

o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)

Where

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY

Jones Harrison
Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the tuples
that are either in R or S or both in R & S.

o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S

A union operation must hold the following condition:

o R and S must have the attribute of the same number.

o Duplicate tuples are eliminated automatically.

Example:

DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176
Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME
Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection:

o Suppose there are two tuples R and S. The set intersection operation contains all
tuples that are in both R & S.

o It is denoted by intersection ∩.

1. Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:
CUSTOMER_NAME

Smith

Jones

5. Set Difference:

o Suppose there are two tuples R and S. The set intersection operation contains all
tuples that are in R but not in S.

o It is denoted by intersection minus (-).

1. Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product

o The Cartesian product is used to combine each row in one table with each row in the
other table. It is also known as a cross product.

o It is denoted by X.
1. Notation: E X D

Example:

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales
1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

7. Rename Operation:

The rename operation is used to rename the output relation. It is denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.

1. ρ(STUDENT1, STUDENT)

Join Operations:

condition is satisfied. It is denoted by ⋈.


A Join operation combines related tuples from different relations, if and only if a given join

Example:

EMPLOYEE

EMP_CODE EMP_NAME
101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

1.

2. Operation: (EMPLOYEE ⋈ SALARY)

Result:

Advertisement

EMP_CODE EMP_NAME SALARY

101 Stephan 50000

102 Jack 30000

103 Harry 25000

Types of Join operations:


1. Natural Join:

o A natural join is the set of tuples of all combinations in R and S that are equal on
their common attribute names.

o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:

Input:

1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

Output:

EMP_NAME SALARY
Stephan 50000

Jack 30000

Harry 25000

2. Outer Join:

The outer join operation is an extension of the join operation. It is used to deal with missing
information.

Example:

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000


Hari TCS 50000

Input:

1. (EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderaba TCS 50000


d

An outer join is basically of three types:

a. Left outer join

b. Right outer join

c. Full outer join

a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R and S that are equal
on their common attribute names.

o In the left outer join, tuples in R have no matching tuples in S.

o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY


Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R and S that are
equal on their common attribute names.

o In right outer join, tuples in S have no matching tuples in R.

o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru Hyderabad


street
Kuber HCL 30000 NULL NULL

c. Full outer join:

o Full outer join is like a left or right join except that it contains all rows from both
tables.

o In full outer join, tuples in R that have no matching tuples in S and tuples in S that
have no matching tuples in R in their common attribute name.

o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:

It is also known as an inner join. It is the most common join. It is based on matched data as
per the equality condition. The equi join uses the comparison operator(=).

Example:

CUSTOMER RELATION
CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

Input:

1. CUSTOMER ⋈ PRODUCT

Output:

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

2 Harry 2 Mumbai

3 Harry 3 Noida

Why it is called Relational Calculus?


It is based on Predicate calculus, a name derived from branch of symbolic language. A
predicate is a truth-valued function with arguments. On substituting values for the
arguments, the function result in an expression called a proposition. It can be either true or
false. It is a tailored version of a subset of the Predicate Calculus to communicate with the
relational database.

Many of the calculus expressions involves the use of Quantifiers. There are two types
of quantifiers:

o Universal Quantifiers: The universal quantifier denoted by ∀ is read as for all


which means that in a given set of tuples exactly all tuples satisfy a given condition.

o Existential Quantifiers: The existential quantifier denoted by ∃ is read as for all


which means that in a given set of tuples there is at least one occurrences whose
value satisfy a given condition.

Before using the concept of quantifiers in formulas, we need to know the concept of Free

A tuple variable t is bound if it is quantified which means that if it appears in any


occurrences a variable that is not bound is said to be free.

Free and bound variables may be compared with global and local variable of programming
languages.

Types of Relational calculus:

1. Tuple Relational Calculus (TRC)


It is a non-procedural query language which is based on finding a number of tuple variables
also known as range variable for which predicate holds true. It describes the desired
information without giving a specific procedure for obtaining that information. The tuple
relational calculus is specified to select the tuples in a relation. In TRC, filtering variable
uses the tuples of a relation. The result of the relation can have one or more tuples.

Notation:

A Query in the tuple relational calculus is expressed as following notation

1. {T | P (T)} or {T | Condition (T)}

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

1. { T.name | Author(T) AND T.article = 'database' }

Output: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).

For example:

1. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.

2. Domain Relational Calculus (DRC)

The second form of relation is known as Domain relational calculus. In domain relational

same operators as tuple calculus. It uses logical connectives ∧ (and), ∨ (or) and ┓ (not). It
calculus, filtering variable uses the domain of attributes. Domain relational calculus uses the

uses Existential (∃) and Universal Quantifiers (∀) to bind the variable. The QBE or Query
by example is a query language related to domain relational calculus.

Notation:

1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where
a1, a2 are attributes
P stands for formula built by inner attributes

For example:

1. {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational javatpoint,
where the subject is a database.

SQL Commands

o SQL commands are instructions. It is used to communicate with the database. It is


also used to perform specific tasks, functions, and queries of data.

o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table, altering
a table, etc.

o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.

Here are some commands that come under DDL:

o CREATE

o ALTER

o DROP

o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100),


DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;

Example

1. DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.

Syntax:

1. TRUNCATE TABLE table_name;

Example:

1. TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all form of
changes in the database.

o The command of DML is not auto-committed that means it can't permanently save
all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT

o UPDATE

o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of
a table.

Syntax:

1. INSERT INTO TABLE_NAME

2. (col1, col2, col3,.... col N)

3. VALUES (value1, value2, value3, .... valueN);

Or

1. INSERT INTO TABLE_NAME

2. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [


WHERE CONDITION]

For example:

1. UPDATE students

2. SET User_Name = 'Sonoo'


3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint

2. WHERE Author="Sonoo";

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant

o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_US


ER;

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.

These operations are automatically committed in the database that's why they cannot be
used while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK

o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS

2. WHERE AGE = 25;

3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS

2. WHERE AGE = 25;

3. ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling
back the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.

Syntax:

1. SELECT expressions

2. FROM TABLES

3. WHERE conditions;

For example:

1. SELECT emp_name

2. FROM employee

3. WHERE age > 20;

You might also like