0% found this document useful (0 votes)
3 views30 pages

UNIT-II Lecture Notes

The document provides an overview of the Relational Model, including key concepts such as integrity constraints, attributes, tuples, and relations. It discusses various types of integrity constraints like domain, entity, referential, and key constraints, as well as SQL commands for data definition, manipulation, control, and querying. Additionally, it covers the importance of NULL values and the structure of SQL commands for creating, altering, and managing database tables.

Uploaded by

Swaroopa Rani
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)
3 views30 pages

UNIT-II Lecture Notes

The document provides an overview of the Relational Model, including key concepts such as integrity constraints, attributes, tuples, and relations. It discusses various types of integrity constraints like domain, entity, referential, and key constraints, as well as SQL commands for data definition, manipulation, control, and querying. Additionally, it covers the importance of NULL values and the structure of SQL commands for creating, altering, and managing database tables.

Uploaded by

Swaroopa Rani
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

R20 CMRTC Dept of CSE(AI&ML)

UNIT-II

Introduction to the Relational Model: Integrity constraint over relations, enforcing integrity
constraints, querying relational data, logical data base design, introduction to views, destroying/altering
tables and views. Relational Algebra, Tuple relational Calculus, Domain relational calculus.

Introduction to Relational Model:

Relational Model was proposed by E.F. Codd to model data in the form of relations or
tables.
After designing the conceptual model of Database using ER diagram, we need to convert
the conceptual model in the relational model.
Relational Model represents how data is stored in Relational Databases.
A relational database stores data in the form of relations (tables).

Domain:

A domain is the original sets of atomic values used to model data.


By atomic value, we mean that each value in the domain is indivisible as far as the
relational model is concerned.
A domain is a set of acceptable values that a column is allowed to contain.
Ex:

o The domain of Marital Status has a set of possibilities: Married, Single, Divorced.
o The domain of Shift has the set of all possible days: {Mon, Tue, Wed…}.
o The domain of Salary is the set of all floating-point numbers greater than 0 and
less than 200,000.
o The domain of First Name is the set of character strings that represents names of
people.

Attribute:

Attributes are the properties that define a relation.


Ex: ROLL_NO,NAME

Tuple:

Each row in the relation is known as tuple.

1 RAM DELHI 9455123451 18

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Relation:

A relation is nothing but a table of values.

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156244344 18

Cardinality:

The number of tuples in a relation is known as cardinality.

Importance of NULL values:

The SQL NULL is the term used to represent a missing value (Unknown).
A NULL value in a table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value.

Constraints:

Constraints are the rules enforced on the data columns of a table


These are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the database.
Constraints could be either on a column level or a table level.

Integrity Constraints

Integrity constraints are a set of rules. It is used to maintain the quality of information.
Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.
Thus, integrity constraint is used to guard against accidental damage to the database.

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Types of Integrity Constraint:

1. Domain constraints

o Domain constraints can be defined as the definition of a valid set of values for an
attribute.

o The data type of domain includes string, character, integer, time, date, currency,
etc. The value of the attribute must be available in the corresponding domain.

Example:

2. Entity integrity constraints

o The entity integrity constraint states that primary key value can't be null.

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

o This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those
rows.

o A table can contain a null value other than the primary key field.

Example:

3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.

o In the Referential integrity constraints, if a foreign key in Table 1 refers to the


Primary Key of Table 2, then every value of the Foreign Key in Table 1 must be
available in Table 2.

Example:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

4. Key constraints

o Keys are the entity set that is used to identify an entity within its entity set
uniquely.

o An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and not null value in the
relational table.

Example:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

NOT NULL Constraint:

NOT NULL constraint makes sure that a column does not hold NULL value.
When we don’t provide value for a particular column while inserting a record into a table, by
default it takes NULL value.
By specifying NOT NULL constraint, we can be sure that a particular column(s) cannot have
NULL values.

Ex:

Create table student

rollno int NOT NULL,

name varchar2(40),

address varchar2(100)

);

SQL> insert into student(name,address) values ('subhash', 'Kakinada');


insert into student(name,address) values ('subhash', 'Kakinada')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SYSTEM"."STUDENT"."ROLLNO")

UNIQUE constraint:

UNIQUE Constraint enforces a column or set of columns to have unique values.


If a column has a Unique constraint, it means that particular column cannot have duplicate
values in a table.
Ex:
create table customer
(
cid int UNIQUE,
cname varchar2(40),
caddress varchar2(100)

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

);
SQL> insert into customer values(101,'subhash','kakinada');
1 row created.
SQL> insert into customer values(101,'ramana','Hyderabad');
insert into customer values(101,'ramana','Hyderabad')
*
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.SYS_C007811) violated

Check Constraint:

The CHECK Constraint enables a condition to check the value being entered into a record.
If the condition evaluates to false, the record violates the constraint and isn't entered the
table.
Ex:
SQL> create table voterlist(vid number not null,vname varchar2(30),vage number
check(vage>=18));
SQL> insert into voterlist values(103,'Mr.Z',17);
insert into voterlist values(103,'Mr.Z',17)
*
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C007747) violated

DEFAULT Constraint:

The DEFAULT constraint provides a default value to a column when there is no value
provided while inserting a record into a table.
Ex:
Create table employee
(
eid int,
ename varchar2(40),
salary float DEFAULT 10000
);

SQL> insert into employee(eid,ename) values(103,'Shakir');

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

1 row created.

SQL> select * from employee;

EID ENAME SALARY


---------- ---------------------------------------- ----------
101 subhash 120000
102 ramana 100000
103 Shakir 10000

PRIMARY KEY Constraint:

A primary key is a field in a table which uniquely identifies each row/record in a database
table.
Primary keys must contain unique values.
A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields.
When multiple fields are used as a primary key, they are called a composite key.

Ex:

create table customer


(
cid int,
cname varchar2(40),
address varchar2(100),
PRIMARY KEY(cid)

);

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

create table customer


(
cid int,
cname varchar2(40), address
varchar2(100), PRIMARY
KEY(cid,cname)

);

FOREIGN KEY Constraint:

A FOREIGN KEY is a key used to link two tables together.


A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY
KEY in another table.
The table containing the foreign key is called the child table, and the table containing the
candidate key is called the referenced or parent table.

Ex:
Create table customers
(
cid int,
cname varchar2(40),
address varchar2(100),
PRIMARY KEY(cid)

);

Create table orders


(

order_id int,
order_date date,
customer_id int,

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

amount float,
FOREIGN KEY(customer_id) references customers(cid)
);

Basic SQL

SQL stands for Structured Query Language.


It is designed for managing data in a relational database management system (RDBMS).
It is pronounced as S-Q-L or sometime See-Qwell.
SQL is a database language, it is used for database creation, deletion, fetching rows, and
modifying rows, etc.
SQL is based on relational algebra and tuple relational calculus.
All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL
Server use SQL as standard database language.

Categories of SQL Commands:

DDL-Data Definition Language:

Create:

MySQL allows us to create a table into the database by using the CREATE TABLE command.

Syntax:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

CREATE TABLE table_name(

column_definition1,

column_definition2,

........,

table_constraints

);

Ex:

Drop:

MYSQL uses a Drop Table statement to delete the existing table.


This statement removes the complete data of a table along with the whole structure or
definition permanently from the database.

Syntax:

DROP TABLE table_name;

Ex:

drop table employee;

Alter:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

MySQL ALTER statement is used when you want to change the name of the table or
field.
It is also used to add or delete a column in a table.
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands
according to the situation.

ADD a new column:

Syntax:

ALTER TABLE table_name

ADD new_column_name column_definition;

Ex:

MODIFY column:

The MODIFY command is used to change the column definition

Syntax:

ALTER TABLE table_name

MODIFY column_name column_definition

Ex:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

DROP column:

It is used to delete an existing column from the table

Syntax:

ALTER TABLE table_name

DROP COLUMN column_name;

RENAME column:

It is used to change the name of the column.

Syntax:

ALTER TABLE table_name

CHANGE COLUMN old_name new_name column_definition

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

RENAME table:

It is used to change the name of the table.

Syntax:

ALTER TABLE table_name

RENAME TO new_table_name;

Ex:

Syntax:

RENAME TABLE old_tab TO new_tab;

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Truncate:

We use this command when we want to delete an entire data from a table without
removing the table structure.
The TRUNCATE command works the same as a DELETE command without using a
WHERE clause that deletes complete rows from a table.

Syntax:

TRUNCATE TABLE table_name;

Ex:

truncate table employee;

DML-Data Manipulation Language:

Insert:

INSERT statement is used to store or add data in the table.


We can perform insertion of records in two ways using a single query in MySQL:
1. Insert one row at a time
2. Insert multiple rows at a time

Syntax-1:

INSERT INTO table_name ( field1, field2,...fieldN )

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

Syntax-2:

INSERT INTO table_name VALUES

( value1, value2,...valueN )

( value1, value2,...valueN )

...........

( value1, value2,...valueN );

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Ex-1:

Ex-2:

Update:

UPDATE statement is used to modify the data of the table.


The UPDATE statement is used with the SET and WHERE clauses.
The SET clause is used to change the values of the specified column.
We can update single or multiple columns at a time.

Syntax:

UPDATE table_name

SET column_name1 = new-value1

[WHERE Condition]

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Delete:

DELETE statement is used to remove records from the table


It also allows us to delete more than one record from the table within a single query

Syntax:

DELETE FROM table_name WHERE condition;

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

DCL- Data Control Language:

Grant:

The grant statement enables system administrators to assign privileges and roles to the
MySQL user accounts so that they can use the assigned permission on the database
whenever required.

Syntax:

GRANT privilege_name(s)

ON object

TO user_account_name;

Ex:

Revoke:

The revoke statement enables system administrators to revoke privileges and roles to the
MySQL user accounts so that they cannot use the assigned permission on the database in
the past.

Syntax:

REVOKE privilege_name(s)

ON object

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

FROM user_account_name;

Ex:

TCL-Transaction Control Language:

Commit:

We will use a COMMIT statement to commit the current transaction. It allows the
database to make changes permanently.
We will use a SET auto-commit statement to disable/enable the auto-commit mode for
the current transaction. By default, the COMMIT statement executed automatically. So if
we do not want to commit changes automatically, use the below statement:

Ex: SET autocommit=OFF;

After restarting MySQL client:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Rollback:

We will use a ROLLBACK statement to roll back the current transaction. It allows the
database to cancel all changes and goes into their previous state.

Savepoint:

It allows all statements that are executed after savepoint would be rolled back.
So that the transaction restores to the previous state it was in at the point of the savepoint.

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

If we have set multiple savepoints in the current transaction with the same name, the
newly savepoint is responsible for rollback.

The ROLLBACK TO SAVEPOINT statement allows us to rolls back all transactions to


the given savepoint was established without aborting the transaction.
The RELEASE SAVEPOINT statement destroys the named savepoint from the current
transaction without undoing the effects of queries executed after the savepoint was
established.
After these statements, no rollback command occurs. If the savepoint does not exist in the
transaction, it gives an error.

Syntax:

SAVEPOINT savepoint_name

ROLLBACK TO [SAVEPOINT] savepoint_name

RELEASE SAVEPOINT savepoint_name

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

DQL- Data Query Language:

Select:

The SELECT statement is used to fetch data from one or more tables.
We can retrieve records of all fields or specified fields that match specified criteria using
this statement.

Syntax:

SELECT field_name1,field_name2,…field_nameN1

FROM table1,table2 … tableN

[Where condition]

Ex:

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Logical Database Design: (ER Diagrams to Relational Model)

Transforming from ER Diagrams to SQL Statements

ER Diagram: Entity Relationship Diagram

eid ename age salary

Employee

Attributes- oval – eid,ename,age,salary

Entity- Rectangle-Employee

Schema: Employee(eid:int,ename:varchar(40),age:int,salary:float(10,2));

SQL Statement:

Create Table Employee( eid int,ename varchar(40), age int, salary float(10,2) ,primary key(eid));

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

ER Diagram:

did dname budget

Department

Entity- Department- Rectangle

Attributes- did,dname,budget-oval

Schema: department(did:int,dname:varchar(40),budget:float(10,2));

SQL Statement:

Create table department(did int,dname varchar(40),budget float(10,2),primary key(did));

ER Diagram:

did dname budget


eid ename age salary

Employee Manages Department

since

Entity- Employee, Department

Attributes-eid,ename,age,salary

did,dname,budget

since

Relationship-manages-Diamond, Rhombus

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Schema:

manages(eid:int, did:int,since: date, foreign key (eid) references employee(eid), foreign key (did)
references department(did));

SQL Statement:

Create table manages(eid int references employee(eid), did int references department(did),since
date);

Introduction to Views:

View:

A view is like a virtual table produced by executing a query.


Views allow you to store complex queries in the database.
For example, instead of issuing a complex SQL query each time you want to see the data,
you just need to issue a simple query as follows:

SELECT column_list
FROM view_name;

Views help you pack the data for a specific group of users. For example, you can create a
view of salary data for the employees for Finance department.
Views help in maintaining database security. Rather than give the users access to
database tables, you create a view to revealing only necessary data and grant the users to
access to the view.

Create View:

Syntax:

CREATE VIEW view_name


AS
SELECT-statement
Ex:

Create view smallbooks

As select btitle from book

Where bpages < 100;

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Alter View:

The ALTER VIEW statement is used to modify or update the already created VIEW
without dropping it.

Syntax:

ALTER VIEW view-name AS

SELECT columns

FROM table

WHERE condition;

Ex:

Alter view smallbooks as

Select btitle,bpages from book

Where bpages < 100;

Drop View:

Syntax:

DROP VIEW view_name;

Ex:

Drop view smallbooks;

Relational Algebra:

Relational algebra is a procedural query language, which takes instances of relations as


input and yields instances of relations as output.
It uses operators to perform queries.
An operator can be either unary or binary.
They accept relations as their input and yield relations as their output.
Relational algebra is performed recursively on a relation and intermediate results are also
considered relations.
The fundamental operations of relational algebra are as follows −

o Select
o Project

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

o Union
o Set different
o Cartesian product
o Rename

Select Operation (σ)

It selects tuples that satisfy the given predicate from a relation.

Notation − σp(r)

Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula
which may use connectors like and, or, and not. These terms may use relational operators like −
=, ≠, ≥, < , >, ≤.

Ex:

σ 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 Operation (∏)

It projects column(s) that satisfy a given predicate.


Notation − ∏A1, A2, An (r)
Where A1, A2 , An are attribute names of relation r.
Duplicate rows are automatically eliminated, as relation is a set.
For example −
∏subject, author (Books)
Output: Selects and projects columns named as subject and author from the relation Books.

Union Operation (∪ )

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

It performs binary union between two given relations and is defined as −


r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
For a union operation to be valid, the following conditions must hold −

r and s must have the same number of attributes.


Attribute domains must be compatible.
Duplicate tuples are automatically eliminated.
Ex:
∏ author (Books) ∪ ∏ author (Articles)
Output − Projects the names of the authors who have either written a book or an article or both.

Set Difference (−)

The result of set difference operation is tuples, which are present in one relation but are not in
the second relation.
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 (Χ):

Combines information of two different relations into one.


Notation − r Χ s
Where r and s are relations and their output will be defined as −
r Χ s = { q t | q ∈ r and t ∈ s}
σ author = 'subhash'(Books Χ Articles)
Output :Yields a relation, which shows all the books and articles written by subhash.

Rename Operation (ρ)

The results of relational algebra are also relations but without any name.
The rename operation allows us to rename the output relation.
'rename' operation is denoted with small Greek letter rho ρ.
Notation − ρx (E)

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Where the result of expression E is saved with name of x.


Additional operations are −

Set intersection
Assignment
Natural join

Relational Calculus

In contrast to Relational Algebra, Relational Calculus is a non-procedural query language,


that is, it tells what to do but never explains how to do it.
Relational calculus exists in two forms −

Tuple Relational Calculus (TRC):


Filtering variable ranges over tuples
Notation − {T | Condition}
Returns all tuples T that satisfies a condition.

For example −
{ [Link] | Author(T) AND [Link] = 'database' }
Output − Returns tuples with 'name' from Author who has written article on 'database'.
TRC can be quantified. We can use Existential (∃ ) and Universal Quantifiers (∀ ).
For example –
{ R| ∃T ∈ Authors([Link]='database' AND [Link]=[Link])}
Output − The above query will yield the same result as the previous one.

Domain Relational Calculus (DRC):


In DRC, the filtering variable uses the domain of attributes instead of entire tuple values
(as done in TRC, mentioned above).
Notation −
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where a1, a2 are attributes and P stands for formulae built by inner attributes.
For example −
{< article, page, subject > | ∈ TutorialsPoint ∧ subject = 'database'}

Database Management Systems SWAROOPA RANI B


R20 CMRTC Dept of CSE(AI&ML)

Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where
subject is database.
Just like TRC, DRC can also be written using existential and universal quantifiers.
DRC also involves relational operators.
The expression power of Tuple Relation Calculus and Domain Relation Calculus is
equivalent to Relational Algebra.
Expressive Power of Algebra and Calculus
We presented two formal query languages for the relational model.
Are they equivalent in power?
Can every query that can be expressed in relational algebra also be expressed in relational
calculus? The answer is yes, it can.
Regarding expressiveness, we can show that every query that can be expressed using a
safe relational calculus query can also be expressed as a relational algebra query.
The expressive power of relational algebra is often used as a metric of how powerful a
relational database query language is.
If a query language can express all the queries that we can express in relational algebra,
it is said to be relationally complete.
A practical query language is expected to be relationally complete;
in addition, commercial query languages typically support features that allow us to
express some queries that cannot be expressed in relational algebra.

*****

Database Management Systems SWAROOPA RANI B

You might also like