Unit 1 DBMS
Unit 1 DBMS
Language
1
OVERVIEW
Introduction
Data type
DDL
2
Introduction
3
DATATYPES
CHAR : char(n)
fixed-length character strings
specify a string length between 1 and 2000 bytes. The
default is 1 byte.
shorter value blank-padded to the fixed length
To large value returns an error
4
Cond…
VARCHAR:varchar(n)
5
Cond…
VARCHAR2:varchar2(n)
6
Cond…
Difference:
VARCHAR -2000 bytes of characters
VARCHAR2 -4000 bytes of characters
VARCHAR -occupy space for NULL values
VARCHAR2 -not occupy any space
Ename varchar(10)
Input: ‘SANJAY ’ 6+3 spaces= 9 bytes
Ename varchar2(10)
Input: ‘SANJAY ’ 6 bytes
Similarity:
VARCHAR and VARCHAR2 both are of variable character
7
Cond…
NUMBER: NUMBER(p,s)
Stores fixed and floating-point numbers
Number having precision p and scale s.
precision p - range from 1 to 38 and scale s can range
from -84 to 127
Input Data Specified As Stored As
7456123.89 NUMBER 7456123.89
7456123.89 NUMBER(*,1) 7456123.9
7456123.89 NUMBER(9) 7456124
7456123.89 NUMBER(9,2) 7456123.89
7456123.89 NUMBER(9,1) 7456123.9
7456123.89 NUMBER(6) (not accepted, exceeds precision)
7456123.89 NUMBER(7,-2) 7456100
7456123.89 NUMBER(-7,2) exceeds precision
8
Find the output
9
Cond…
When Precision is smaller than Scale (e.g NUMBER(2, 5):
The number will not have any integer part, only fractional
part.
In fact, if you specify just 1 digit in the integer part, it will
always return an error.
The fractional part is divided into 2 parts, significant
numbers and zeros.
Significant numbers are specified by Precision, and
minimum number of zeros equals (Scale - Precision).
Example :
10
Find the output
NUMBER(6,9)
insert .0000123
-- prints: 0.0000123;
insert .000012345
-- prints: 0.000012345
insert 12.0000123
-- error
insert .00001234567
-- prints: 0.000012346
11
Cond…
Integer or int
INTEGER is equivalent to NUMBER(38,0)
INTEGER: input:12.2 => 12
INTEGER: input: 12.5 => 13
12
DDL
Data Definition Language
Define and modify the schema the database
Schema
Employee:
Ename
EID
Address
13
DDL Commands
CREATE – is used to create the database or its objects
(like table, index, function, views, store procedure and
triggers)
CREATE TABLE table_name(column1 data_type(size),
column2 data_type(size), column3 data_type(size), .... );
14
Cond…
DESC or either DESCRIBE:
View the structure of table
15
DDL - DROP
DROP - delete a whole database
16
DDL - ALTER
ALTER -add, delete/drop or modify columns in the
existing table
17
DDL-ALTER
ALTER TABLE-MODIFY
to change data type of any column or to modify its size.
ALTER TABLE table_name MODIFY(column_name
column_type);
18
DDL-ALTER
ALTER TABLE – DROP
19
DDL-ALTER
ALTER TABLE- RENAME
20
DDL-TRUNCATE
TRUNCATE
Removes the data from the table
21
DDL- Comment
Comments can be written in the following three formats:
22
DDL-RENAME
RENAME
- set a new name for any existing table
23
Quick Review
CREATE
DROP
ALTER
TRUNCATE
COMMENT
RENAME
24
1
OVERVIEW- DML
Insert
Update
Delete
Select
2
DML
Data Manipulation Language
deals with the manipulation of data present in the database
INSERT
INSERT INTO table_name VALUES (value1, value2,
value3,…);
3
DML- UPDATE
UPDATE table_name SET column1 = value1, column2 =
value2,... WHERE condition;
6
Comparison Operator
= Equality test.
7
DML-Delete
DELETE FROM table_name WHERE some_condition;
10
DML-Select-OR
To fetch all the records from Student table where NAME
is Ram or NAME is SUJIT.
SELECT * FROM Student WHERE NAME = 'Ram'
OR NAME = 'SUJIT';
11
DML- SELECT- AND OR
SELECT * FROM table_name WHERE condition1 AND
(condition2 OR condition3);
To fetch all the records from Student table where Age is
18 NAME is Ram or Raj.
12
SELECT in INSERT
INSERT INTO first_table SELECT * FROM second_table;
13
SELECT in CREATE
Create an exact copy of a table with or without the data
14
SELECT in CREATE
Copy both the structure and data of a table
CREATE TABLE employees_copy AS SELECT *
FROM employees;
15
SELECT in CREATE
Copy only structure of the table without the data
16
Quick Review
Insert
Update
Delete
Select
17
Review Questions
GATE CS 2011
19
SQL- Structured Query
Language
1
Constraints
are the rules enforced on the data columns of a table.
2
Types of Constraints
NOT NULL Constraint − Ensures that a column cannot have
NULL value.
UNIQUE Constraint − Ensures that all values in a column
are different.
PRIMARY Key − Uniquely identifies each row/record in a
database table.
FOREIGN Key − Uniquely identifies a row/record in any of
the given database table.
DEFAULT Constraint − Provides a default value for a
column when none is specified.
CHECK Constraint − The CHECK constraint ensures that all
the values in a column satisfies certain conditions.
3
NOT NULL Constraint
CREATE TABLE Persons (
SID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
4
Identify the output
insert into Persons values(22,'xxx','yyy',34);
1 row(s) inserted
insert into Persons(SID) values(23);
cannot insert NULL into
("SQL_UFKDRHKBIOEIZJOLORWBUWGRH"."PERS
ONS"."LASTNAME")
insert into Persons(SID,LastName) values(23,'GGG');
1 row(s) inserted
5
UNIQUE Constraint
Single Column Constraint:
CREATE TABLE Persons (ID int UNIQUE, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);
CREATE TABLE Persons (ID int , LastName
varchar(25) NOT NULL, FirstName varchar(25), Age int,
CONSTRAINT UC_Person UNIQUE (ID) );
6
Unique- Alter
CREATE TABLE Persons (ID int, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);
7
PRIMARY KEY Constraint
Single Column Constraint:
CREATE TABLE Persons (ID int primary key LastName
varchar(25) NOT NULL, FirstName varchar(25), Age int);
CREATE TABLE Persons (ID int , LastName
varchar(25) NOT NULL, FirstName varchar(25), Age int,
CONSTRAINT PC_Person primary key (ID) );
8
Primary key- Alter
CREATE TABLE Persons (ID int, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);
9
CHECK Constraint
CREATE TABLE Persons (ID int Primary key, LastName
varchar(25),FirstName varchar(25),
Age number(3) CHECK (Age>=18));
CREATE TABLE Persons ( ID int Primary key, LastName
varchar(25), FirstName varchar(25), Age int,
CONSTRAINT CHK_Person CHECK (Age>=18));
11
DEFAULT Constraint
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘Coimbatore'
);
12
DEFAULT Constraint
ALTER TABLE <table_name> MODIFY
<column_name> <column_data_type> DEFAULT
<default_value>;
13
FOREIGN KEY Constraint
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
14
Cond…
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_Person
FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
15
Foreign key in Alter
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons
(PersonID);
16
Foreign key with Cascade
DELETE
CREATE TABLE supplier ( supplier_id number(10),
supplier_name varchar2(50), contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY
(supplier_id) );
17
Foreign key with set null on
delete
CREATE TABLE products (product_id INT PRIMARY
KEY, product_name VARCHAR(50) NOT NULL,
category VARCHAR(25) );
18
Foreign key in Drop
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
19
Levels of Constraints
Column level constraint applies only to individual
columns
CREATE TABLE sample1(name CHAR(10) NOT NULL, id
INTEGER REFERENCES idtable(id), age INTEGER
CHECK (age > 0));
1
AGENDA
Set Functions
Aggregate Functions
More options in Select
2
3
Union
SELECT column_name FROM table1 UNION
SELECT column_name FROM table2;
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
4
SELECT * FROM First UNION SELECT * FROM
Second;
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
5
SELECT * FROM First UNION ALL SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
6
supplier_na company_id company_name
supplier_id
me 1000 Microsoft
1000 Microsoft 3000 Apple
2000 Oracle 7000 Sony
3000 Apple 8000 IBM
4000 Samsung
SELECT supplier_id, supplier_name FROM suppliers WHERE
supplier_id > 2000 UNION SELECT company_id, company_name
FROM companies WHERE company_id > 1000
supplier_id supplier_name
3000 Apple
4000 Samsung
7000 Sony
8000 IBM
7
Intersect
SELECT column_name FROM table1 INTERSECT
SELECT column_name FROM table2;
ID NAME
3 Jackson
8
supplier_na company_id company_name
supplier_id
me 1000 Microsoft
1000 Microsoft 3000 Apple
2000 Oracle 7000 Sony
3000 Apple 8000 IBM
4000 Samsung
SELECT supplier_id, supplier_name FROM suppliers WHERE
supplier_id > 2000 INTERSECT SELECT company_id,
company_name FROM companies WHERE company_id > 1000
supplier_id supplier_name
3000 Apple
9
MINUS
SELECT column_name FROM table1 MINUS
SELECT column_name FROM table2;
supplier_na
supplier_id
me
4000 Samsung
10
Cond…
SELECT company_id, company_name FROM
companies WHERE company_id > 1000 MINUS
SELECT supplier_id, supplier_name FROM
suppliers WHERE supplier_id > 2000
company_id company_name
7000 Sony
8000 IBM
11
Quick Review
Union
Union all
Intersect
Intersect all
minus
12
Aggregate Functions
14
COUNT
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120
15
Count
Count total number of records in the table Product
SELECT COUNT(*) FROM PRODUCT;
10
16
Display the average salary for each department
17
Where vs Having
Both the WHERE and the HAVING clause are very similar
and are used to restrict the rows that are returned in a
SELECT query.
The difference between WHERE and HAVING clause are:
The WHERE clause is used to filter rows before the
grouping is performed.
The HAVING clause is used to filter rows after the
grouping is performed. It often includes the result of
aggregate functions and is used with GROUP BY.
18
Cond…
19
Display the average salary for each department
where the average salary is more than 3000
20
Count total number of products in
each company
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120
21
Cond…
Com1 5
Com2 3
Com3 2
22
Count total number of products in each
company with the rate of the product is
more than 15
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120
23
Cond…
Com1 3
Com2 3
Com3 1
24
Count total number of products in each
company where the number of products are
more than 2
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120
25
Cond…
Com1 5
Com2 3
26
Cond…
Count total number of products in each company where
the rate of the product is more than 15 and the number
of products are more than 2
Com1 3
Com2 3
27
Cond…
Sum():
sum(salary)
310
sum(Distinct salary)
250
Avg():
Avg(salary)
Sum(salary) / count(salary) = 310/5
o/p: 62
Count(*) Avg(Distinct salary)
6 sum(Distinct salary) / Count(Distinct Salary) =
Count(salary) 250/4
5 o/p: 62
Count(Distinct Salary) Min(salary)
4 40
Max(salary)
80
28
ORDER BY
Sort the fetched data in either ascending or
descending according to one or more columns.
By default ORDER BY sorts the data
in ascending order.
use the keyword DESC to sort the data in
descending order and the keyword ASC to sort
in ascending order.
29
SELECT * FROM Student ORDER BY ROLL_NO DESC;
ROLL_NO NAME ADDRESS PHONE Age
32
Cond…
SELECT TOP value PERCENT column1,column2
FROM table_name;
33
Query order of execution
FROM
WHERE. ...
GROUP BY. ...
HAVING. ...
SELECT. ...
DISTINCT. ...
ORDER BY. ...
LIMIT
34
More options in SELECT
35
SQL- Alias
Aliases are the temporary names given to table or
column
Aliases are created to make table or column names more
readable
Aliases are useful when table or column names are big or
not very readable
These are preferred when there are more than one table
involved in a query
SELECT column as alias_name FROM table_name;
SELECT column FROM table_name as alias_name;
36
Cond…
To fetch ROLL_NO from Student table using CODE as
alias name
SELECT ROLL_NO AS CODE FROM Student;
37
SQL- Arithmetic Operators
Operator Description Example
+ (unary) Makes operand positive SELECT +3 FROM DUAL;
- (unary) Negates operand SELECT -4 FROM DUAL;
/ Division (numbers and SELECT SAL / 10 FROM
dates) EMP;
* Multiplication SELECT SAL * 5 FROM
EMP;
+ Addition (numbers and SELECT SAL + 200 FROM
dates) EMP;
- Subtraction (numbers SELECT SAL - 100 FROM
and dates) EMP;
38
SQL-Character Operators
Operator Description Example
|| Concatenates character SELECT 'The Name of the employee
strings is:’ || ENAME FROM EMP;
39
SQL-Comparison Operators
Operator Description Example
= Equality test. SELECT ENAME "Employee" FROM EMP
WHERE SAL = 1500;
!=, ^=, <> Inequality test. SELECT ENAME FROM EMP WHERE SAL ^=
5000;
> Greater than test. SELECT ENAME "Employee", JOB "Title" FROM
EMP WHERE SAL > 3000;
< Less than test. SELECT * FROM PRICE WHERE MINPRICE <
30;
>= Greater than or equal to SELECT * FROM PRICE WHERE MINPRICE >=
test. 20;
<= Less than or equal to test. SELECT ENAME FROM EMP WHERE SAL <=
1500;
BETWEEN greater than or equal SELECT ENAME, JOB FROM EMP WHERE
x and y to x and less than or SAL BETWEEN 3000 AND 5000;
equal to y.
(an inclusive Range)
40
SQL-Logical Operators
Operator Description Example
NOT Returns TRUE if the
following condition SELECT * FROM EMP WHERE NOT (sal
is FALSE. BETWEEN 1000 AND 2000)
Returns FALSE if it
is TRUE. If it
is UNKNOWN, it
remains UNKNOWN.
AND Returns TRUE if both SELECT * FROM EMP WHERE
component conditions job='CLERK' AND deptno=10
are TRUE.
Returns FALSE if either
is FALSE; otherwise
returns UNKNOWN.
OR Returns TRUE if either SELECT * FROM emp WHERE
component condition job='CLERK' OR deptno=10
is TRUE.
Returns FALSE if both
are FALSE. Otherwise,
returns UNKNOWN.
41
Cond…
Find all the Employee name whose salary is not in the
range of 30000 and 45000
42
Like operator
It uses wildcards to perform pattern matching in a
query.
LIKE condition is used in the WHERE clause of a
SELECT, INSERT, UPDATE, or DELETE statement.
Wildcard Explanation
match any string of any
%
length (including zero length)
_ match on a single character
43
Cond… PRODUCT
Id
ProductNa
List all products with names that start with 'Ca' me
SupplierId
SELECT *FROM Product WHERE ProductName UnitPrice
LIKE 'Ca%‘; Package
IsDiscontin
ued
List all products that start with 'Cha' or 'Chan' and
have one more character.
44
Cond…
Find all last_name values from the customers table where
the last_name contains the letter 'e‘
SELECT last_name FROM customers WHERE
last_name LIKE '%e%’;
Selects all customers with a CustomerName ending with "a“
SELECT * FROM CustomersWHERE CustomerName
LIKE '%a';
Selects all customers with a CustomerName that have "or"
in any position
SELECT * FROM CustomersWHERE CustomerName
LIKE '%or%';
45
Cond…
Selects all customers with a CustomerName that have "r" in
the second position
SELECT * FROM CustomersWHERE CustomerName
LIKE '_r%';
selects all customers with a CustomerName that starts with
"a" and are at least 3 characters in length
SELECT * FROM CustomersWHERE CustomerName
LIKE 'a_ _%';
selects all customers with a ContactName that starts with "a"
and ends with "o”
SELECT * FROM CustomersWHERE ContactName
LIKE 'a%o';
46
Cond…
Selects all customers with a CustomerName that does NOT
start with "a“
SELECT * FROM CustomersWHERE CustomerName
NOT LIKE 'a%';
Find all records from the categories table where the
category-id is 2-digits long and ends with '5’
SELECT * FROM categories WHERE category_id
LIKE '_5';
47
Quick Review
Like
Wildcards: % and _
Not like
48
NULL
Values of attributes that may be unknown or not apply to a
tuple (different from zero)
When a NULL is involved in a comparison operation, the
result is considered to be UNKNOWN
Select type+100 from emp; if type is i)NULL ii) 0
49
Test the NULL values:
Rather than using = or to compare an attribute value to
NULL, SQL uses IS and IS NOT.
Find the Fname, Lname of the Employee having no
Super_ssn.
SELECT Fname, Lname FROM Employee WHERE
Super_ssn IS NULL;
Find the Fname, Lname of the Employee having
Super_ssn.
SELECT Fname, Lname FROM Employee WHERE
Super_ssn IS NOT NULL;
50
Review Questions
GATE CS 2012
P : An SQL query can contain a HAVING clause even if it does not have a
GROUP BY clause
Q : An SQL query can contain a HAVING clause only if it has a GROUP BY
clause
R : All attributes used in the GROUP BY clause must appear in the SELECT
clause
S : Not all attributes used in the GROUP BY clause need to appear in the
SELECT clause
(A) P and R
(B) P and S
(C) Q and R
(D) Q and S
Answer: (B)
51
Thank You
52
SQL- Structured Query
Language
1
AGENDA
2
StudentCourse
3
Cond…
4
Combine Multiple Tables
SELECT table1.column1 ,
table1.column2, table2.column1...
FROM table1, table2;
SELECT table1.column1 ,
table1.column2, table2.column1...
FROM table1 CROSS JOIN table2;
5
Cond…
CARTESIAN JOIN:
The CARTESIAN JOIN is also known as
CROSS JOIN.
is a join for each row of one table to every
row of another table.
Number of rows in the result-set is the product
of the number of rows of the two tables.
6
7
8
StudentCourse
9
SELECT NAME, AGE, COURSE_ID FROM Student,
StudentCourse;
10
Cond…
11
Cond…
Roll_No Name Course_ID
1 Ram 1
2 Ramesh 2
3 Sujit 2
4 Suresh 3
12
Cond…
Display name and roll numbers of the
students who enrolled the course number 2
13
Cond…
Roll_No Name
2 Ramesh
3 Sujit
14
JOIN
INNER JOIN
15
16
Example
SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE
FROM Student INNER JOIN StudentCourse ON
Student.ROLL_NO = StudentCourse.ROLL_NO;
17
OUTER JOIN
18
19
Display the students who registered the
course and also the students who not
registered the courses
20
LEFT JOIN or LEFT OUTER
JOIN
SELECT * FROM table1 LEFT JOIN table2 ON
table1.matching_column = table2.matching_column;
21
Example
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
22
FULL JOIN
SELECT table1.column1,table1.column2,table2.column1
FROM table1 FULL JOIN table2 ON
table1.matching_column = table2.matching_column;
23
24
Display the courses that are enrolled by the
students and also display the courses not selected
by the students
25
RIGHT JOIN
SELECTtable1.column1,table1.column2,table2.column1,
FROM table1 RIGHT JOIN table2 ON
table1.matching_column = table2.matching_column;
26
Cond…
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
27
28
Example
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
29
Natural Join
30
Example
SELECT * FROM company INNER JOIN foods ON
company.company_id = foods.company_id;
31
Cond…
SELECT * FROM company NATURAL JOIN foods;
32
Natural Outer Joins
SELECT * FROM company NATURAL RIGHT JOIN
foods;
SELECT * FROM company NATURAL LEFT JOIN
foods;
SELECT * FROM company NATURAL FULL JOIN
foods;
33
Cond…
Customer(ID_customer, name)
Addresses(ID, address)
34
Faculty Incharge
Dr.S.Sarathambekai
1
Database system concepts and
Architecture
2
Data Models
Data abstraction
Types:
Low-level or physical data models
High-level or conceptual data models
Representational (or implementation) data models (record-
based data models)
Relational data model
Network data model
Hierarchical model
Object data model
Self-describing data models
3
4
5
Schema(intension)
Design of the DB
• Schema evolution
6
Instance or extension of schema
Database state or snapshot
Difference between Schema and Instance
Valid state
7
Three-Schema Architecture
8
Data Independence
capacity to change the schema at one level of a database
system without having to change the schema at the next
higher level.
Two types:
Logical data independence
Physical data independence
9
DBMS Languages
Data Definition Language (DDL)
Storage Definition Language (SDL)
View Definition Language (VDL)
Data Manipulation Language (DML)
10
Types of DML
High-level or nonprocedural DML: Set-at-a-time or set-oriented
DMLs.
Select * from stud;
Low-level or procedural DML: Record-at-a-time
tell the system what data is needed and how to take the data.
Procedural DML is embedded into a high-level programming language.
try{
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM students");
while(rs.next){
String s = rs.getString(1);
//dst...
}
} catch(SQLException e){}
11
Cond…
Host Language
Data Sublanguage
Query Language
12
13
Thank you
14
1
Databases and Database Users
2
AGENDA
Discussed
Database
DBMS
DBS
Char of DBS
Actors on the Scene
Workers behind the Scene
Advantages and Disadvantages of DBMS
References
3
Actors on the Scene
Database Administrators
-responsible for monitoring and managing all the
activities related to database system
installing and Configuration of database
Deciding the hardware device
Decides content of the database
Database accessibility: authorizing access
Decides Data Recovery and Back up method
4
Cond…
Database Designers
understand their requirements
identifying the data to be stored in the database
choosing appropriate structures to represent and
store this data
5
Cond…
End Users – Access the DB
Casual end users- Manager
use a sophisticated database query interface to specify their
requests (need different information each time)
Naive or parametric end users (mobile apps are also
available to perform this thru’ mobile)
constantly querying and updating the database, using standard
types of queries and updates—Canned transactions
Bank customers -check account balances, withdrawals
and deposits
Reservation customers- check availability, make reservations,
cancellation
Social media users- Post, Read, Like
6
Cond…
Sophisticated end users - Engineers, Scientists,
business analysts
Develop applications to access the DB
Standalone users
personal databases
ready-made program- provide easy-to-use menu-based
or graphics-based interfaces.
financial software package that stores a variety of
personal financial data
7
Cond…
System Analysts and Application Programmers
(Software Engineers)
System analysts- determine the requirements of end users
and develop specifications for standard canned transactions
Application programmers- implement these specifications
as programs; then they test, debug, document, and maintain
these canned transactions.
Software developers or software engineers analysts and
programmers
8
Workers behind the Scene
DBMS system designers and implementers
design and implement the DBMS modules and interfaces
as a software package
Tool developers- design and implement tools
Operators and maintenance personnel
actual running and maintenance of the hardware and
software environment for the database system
9
Quick Review
Actors on the Scene
Database Administrators
Database Designers
End Users
Software developers or Software Engineers
Workers behind the Scene
DBMS system designers and implementers
Tool developers
Operators and maintenance personnel
10
Review Question
-------- is responsible for deciding which hardware
device will suit the company requirements.
a) DBA
b) DBD
c) Software Engineer
d) System analysts
11
Review Question
Identify whether Actor/Worker
System designers
System analysts
Software developers
Tool developers
12
Advantages of using the DBMS
Approach
Controlling Redundancy
FPS: Redundancy (independent of files)
Duplication
storage space is wasted
Inconsistent
DBS : No redundancy (interrelated data)
No Duplication
storage space is not wasted
Consistent
13
Cond…
Restricting Unauthorized Access
FPS: File level security
DBS: Different levels of security
14
Cond…
Providing Persistent Storage for Program Objects
E.g.: Java, C++ Complex data structures
The values of program variables or objects
Permanent storage – files Need conversions
15
Cond…
Providing Storage Structures and Search techniques
for Efficient Query Processing
FPS: OS- disk-to-memory buffering
DBS: DBMS
Storage management (buffering or caching) module
Indexing - tree data structures or hash data
structures
query processing and optimization module
16
Cond…
Providing Backup and Recovery
Backup and recovery subsystem
-Restore the data if the system fails
17
Cond…
Providing Multiple User Interfaces
types of users with varying levels of technical knowledge
apps
mobile users
query languages
casual users
programming language interfaces
application programmers
forms and command codes
parametric users
menu-driven interfaces and natural language interfaces
standalone users 18
Cond…
Representing Complex Relationships among Data
19
Cond…
Enforcing Integrity Constraints
Data type for each data item
E.g.:
Name must be a string of no more than 30 alphabetic
characters
Age between 19 and 25
Referential integrity
Unique constraint
20
Cond…
Rules and Triggers
21
Quick Review
Controlling Redundancy
Restricting Unauthorized Access
Providing Persistent Storage for Program Objects
Providing Storage Structures and Search Techniques for
Efficient Quercy processing
Providing Backup and Recovery
Providing Multiple User Interfaces
Representing Complex Relationships among Data
Enforcing Integrity Constraints
Rules and Triggers
22
Disadvantage of DBMS
High initial investment in hardware, software, and training
Overhead for providing security, concurrency control,
recovery, and integrity functions
23
Review Questions
A __________ is a special kind of a store procedure
that executes in response to certain action on the table
like insertion, deletion or updation of data.
a) Procedures
b) Triggers
c) Functions
24
Cond…
This is a collection of descriptions about data objects
that is created for the benefit of programmers and others
who might need to refer to them.
a. data dictionary
b. stored procedure
c. Virtual File Allocation table
d. Virtual Address extension
25
Thank you
26
*
Data modeling using Entity Relationship
model (E-R Model)
1
*
*The ER or (Entity Relational Model) is a high-
level conceptual data model diagram.
*ER modeling helps you to analyze data
requirements systematically to produce a well-
designed database
*ER diagrams is a diagram which is helpful to
represent the ER model.
*Proposed by Peter Chen in 1971
2
* Components of the ER Diagram
Entities
Attributes
Relationships
3
*
4
*
1. Key attribute
2. Composite attribute
3. Multivalued attribute
4.Derived attribute 5
6
7
*
An employee assigned a project.
Teacher teaches a student.
Author writes a book.
8
*Degree of relationship
*Unary relationship
An employee(manager) supervises another employee.
9
*Degree of relationship
Binary Relationship
10
*Cardinality
*One-to-One Relationships(1:1)
*One-to-Many Relationships(1:N)
*Many to One Relationships(N:1)
*Many-to-Many Relationships(M:N)
11
1:1 N:1
M:N 12
13
A Student allotted a project
14
*
16
*Role Name: Recursive
Relationships
17
*Weak Entity Partial key or discriminator
key
20
*
* An entity type PROJECT with attributes Name,
Number, Location, and Controlling_department.
Both Name and Number are (separate) key
attributes.
21
*
* An entity type EMPLOYEE with attributes Name, Ssn, Sex,
Address, Salary, Birth_date, Department, and Supervisor.
Name is a composite attributes. The components of Name—
First_name, Middle_initial, Last_name. An employee can work
on several projects, and the database has to store the
number of hours per week an employee works on each
project. This can be represented by a multivalued composite
attribute of EMPLOYEE called Works_on with the simple
components (Project, Hours)
22
*
* An entity type DEPENDENT with attributes Employee,
Dependent_name, Sex, Birth_date, and Relationship (to the
employee).
23
*
24
*SUPERVISION, a 1:N relationship type
between EMPLOYEE (in the supervisor role)
and EMPLOYEE (in the supervisee role). Both
participations are determined to be partial,
after the users indicate that not every
employee is a supervisor and not every
employee has a supervisor.
*
25
*
26
*DEPENDENTS_OF, a 1:N relationship
type between EMPLOYEE and
DEPENDENT, which is also the
identifying relationship for the weak
entity type DEPENDENT.
The participation of EMPLOYEE is
partial, whereas that of DEPENDENT is
total.
*
27
*
28
*CONTROLS, a 1:N relationship type between
DEPARTMENT and PROJECT. The participation of
PROJECT is total.
29
*
*
*WORKS_ON, determined to be an M:N (many-
to-many) relationship type with attribute
Hours, after the users indicate that a project
can have several employees working on it.
Both participations are determined to be total.
*WORKS_FOR, a 1:N (one-to-many) relationship
type between DEPARTMENT and EMPLOYEE.
Both participations are total.
30
*
31
*MANAGES, which is a 1:1(one-to-one)
relationship type between EMPLOYEE and
DEPARTMENT. EMPLOYEE participation is
partial.
*
32
33
*The library contains one or several copies of the same book. Every
copy of a book has a copy number and is located at a specific location
in a shelf. A copy is identified by the copy number and the ISBN
number of the book. Every book has a unique ISBN, a publication
year, a title, an author, and a number of pages. Books are published by
publishers. A publisher has a name as well as a location. Within the
library system, books are assigned to one or several categories. A
category can be a subcategory of exactly one other category. A
category has a name and no further properties. Each reader needs to
provide his/her family name, his/her first name, his/her city, and
his/her date of birth to register at the library. Each reader gets a unique
reader number. Readers borrow copies of books. Upon borrowing the
return date is stored.
*
34
*A copy is identified by the copy number and the ISBN number
of the book
*Every book has a unique ISBN, a publication year, a title, an
author, and a number of pages
*A publisher has a name as well as a location.
*A category has a name and no further properties
*Each reader needs to provide his/her family name, his/her first
name, his/her city, and his/her date of birth to register at the
library
*
35
*A copy is identified by the copy number and the ISBN
number of the book.
*Books are published by publishers
*Within the library system, books are assigned to one or
several categories.
*A category can be a subcategory of exactly one other
category.
*Readers borrow copies of books.
*
36
*
37
*Mapping the ER Model
to Relational Database
38
39
40
*Mapping the ER Model to
Relational Database
Two Relations:
Persons (SSN, FirstName, LastName, Address, Birthdate)
Persons_Hobbies(SSN, Hobby)
41
*
42
43
44
*One-to-One Relationships(1:1)Either one(PK)
*One-to-Many Relationships(1:N)N side(PK)
*Many to One Relationships(N:1) N side(PK)
*Many-to-Many Relationships(M:N)MN(PK)
Reduced Relation
*One-to-One Relationships(1:1):No separate relation for
relationship (Place any one of the 1 side PK in another)
*One-to-Many Relationships(1:N) and Many to One
Relationships(N:1) No separate relation for relationship
(Place 1 side PK in N-side )
*
45
46
*
47
*
48
*
GATE CS 2008
49
*
GATE-CS-2005
Let E1 and E2 be two entities in an E/R diagram with
simple single-valued attributes. R1 and R2 are two
relationships between E1 and E2, where R1 is one-to-
many and R2 is many-to-many. R1 and R2 do not have
any attributes of their own. What is the minimum
number of tables required to represent this situation
in the relational model?
(A) 2
(B) 3
(C) 4
(D) 5
50
*
GATE CS 2018
51
*
*EER is a high-level data model that incorporates the
extensions to the original ER model.
*It includes the concept of specialization and
generalization.
*Sub Class and Super Class
Sub class and Super class relationship leads the
concept of Inheritance.
52
*
*Generalization is the process of generalizing the entities which
contain the properties of all the generalized entities.
*It is a bottom approach, in which two lower level entities combine
to form a higher level entity.
*Generalization is the reverse process of Specialization.
*It defines a general entity type from a set of specialized entity
type.
*It minimizes the difference between the entities by identifying the
common features.
53
*
*Specialization is a process that defines a group entities
which is divided into sub groups based on their
characteristic.
*It is a top down approach, in which one higher entity can
be broken down into two lower level entity.
*It maximizes the difference between the members of an
entity by identifying the unique characteristic or attributes
of each member.
*It defines one or more sub class for the super class and
also forms the superclass/subclass relationship.
54
*
55
*
*Two entities Student and Teacher:
Attributes of Entity Student are: Name, Address and Grade
Attributes of Entity Teacher are: Name, Address and Salary
56
*
57
*
*Predicate-defined (or condition-defined) subclasses or
attribute-defined specialization
*User defined specialization
58
*
*Disjointness constraint:
(o)verlap: may be a member of more than one subclass
(d)isjoint: entities may only be one subclass
59
*
60
*
*Completeness (or totalness) constraint
Total or Partial
Based on disjointness and completeness constraints:
Four possible constraints on a specialization:
*Disjoint, total
*Disjoint, partial
*Overlapping, total
*Overlapping, partial
61
*
62
*
* The database keeps track of three types of persons: employees, alumni, and
students. A person can belong to one, two, or all three of these types. Each
person has a name, SSN, sex, address, and birth date.
* Every employee has a salary, and there are three types of employees:
faculty, staff, and student assistants. Each employee belongs to exactly one
of these types.
* For each alumnus, a record of the degree or degrees that he or she earned at
the university is kept, including the name of the degree, the year granted,
and the major department. Each student has a major department.
* Each faculty has a rank, whereas each staff member has a staff position.
Student assistants are classified further as either research assistants or
teaching assistants, and the percent of time that they work is recorded in
the database. Research assistants have their research project stored,
whereas teaching assistants have the current course they work on.
* Students are further classified as either graduate or undergraduate, with the
specific attributes degree program (M.S., Ph.D., M.B.A., and so on) for
graduate students and class (freshman, sophomore, and so on) for under-
graduates.
63
64
*
*
*Threeentity types: PERSON, BANK, and
COMPANY.
In a database for motor vehicle registration, an owner
of a vehicle can be a person, a bank (holding a lien on
a vehicle), or a company.
65
*
66
67
68
*
69
70
71
72 *
Unit - 2
Relational Algebra
1
Relational Algebra
O Procedural query language
O Basic Relational Algebra Operations:
Relational Algebra divided in various groups
Unary Relational Operations
• SELECT (symbol: σ)
• PROJECT (symbol: π)
• RENAME (symbol: ρ)
Relational Algebra Operations From Set Theory
• UNION (∪)
• INTERSECTION (∩)
• DIFFERENCE (-)
Binary Relational Operations
• CARTESIAN PRODUCT ( x )
• JOIN(⋈ )
• DIVISION(÷)
2
Unary Relational Operations
O SELECT (σ)
selecting a subset of the tuples according to a given
selection condition
σp(r)
r stands for relation which is the name of the table
p is predicate
attribute <comparison> constant
attribute1 <comparison> attribute2
<comparison> is the usual =, ≠, ≥, < , >, ≤
attribute is null or is not null
logical operations and, or, and not
3
Example
Selects tuples from Tutorials where topic =
'Database'.
σ topic = "Database" (Tutorials)
Selects tuples from Tutorials where the topic is
'Database' and 'author' is Guru
σ topic = "Database" and author = "guru"( Tutorials)
Selects tuples from Customers where sales is
greater than 50000
σ sales > 50000 (Customers)
4
Examples
Selects tuples from books where subject is
'database'.
σsubject = "database"(Books)
Selects tuples from books where subject is
'database' and 'price' is 450.
σ subject = "database" and price = 450(Books)
Selects tuples from books where subject is
'database' and 'price' is 450 or those books
published after the year 2010.
σsubject = "database" and price = 450 or year > 2010(Books)
5
Project Operation (∏)
It projects column(s) that satisfy a given
predicate.
∏A1, A2, An (r)
Where A1, A2 , An are attribute names of
relation r.
Duplicate rows are automatically eliminated, as
relation is a set.
6
Example
O Selects the columns named as subject and
author from the relation Books
∏subject, author (Books)
7
Example
O Select the columns Name and Age for the
students who are having the CGPA is more
than or equal to 8.5
∏Name, Age(σCGPA≥8.5(Students))
(or)
O S ← σCGPA≥8.5(Students)
O RESULT ← ∏Name, Age(S)
8
Rename Operation (ρ)
O Rename the relation
ρ(RelationNew, RelationOld)
E.g:
Student: Sname,Rollno
Rename Table:
ρ(Stud, Student) Stud: Sname,Rollno
Rename Column:
ρ(Sname, Rno) (Student) Student:Sname,Rno
9
Set Operators
Union Operation (∪)
-fetch data from two relations
Condition: r and s are relations
O r and s must have the same number of
attributes.
O Attribute domains must be compatible
O Duplicate tuples are automatically eliminated
10
Set Operators
O Intersection(∩)
- Common tuples from two relations
O Set Difference (-)
- Tuples present in left relation not in
right relation
11
Example- Books, Articles
O Display the names of the authors who have
either written a book or an article or both.
∏ author_Name (Books) ∪ ∏ author_Name (Articles)
O Display the names of the authors who have
written a book but not an article
∏ author_Name (Books) - ∏ author_Name (Articles)
O Display the names of the authors who have
written a book and also an article
∏ author_Name (Books) ∩ ∏ author_Name (Articles)
12
Example-
RegularClass and ExtraClass
O Display the name of Students who are
attending either regular classes or extra classes
or both
∏Sname(RegularClass) ∪ ∏Studname(ExtraClass)
O Find name of students who attend the regular
class but not the extra class
∏Sname(RegularClass) - ∏Studname(ExtraClass)
O Find name of students who attend the regular
class and also the extra class
∏Sname(RegularClass) ∩∏Studname(ExtraClass) 13
Binary Relational Operations
O Cartesian Product (X)
-All possible combination of two relations
Relations:
Stud(Rno, Sname, Address, Semester)
StudCGPA(Roll, CGPA)
O Find the name of the students who are maintaining the
CGPA is more than 8.0
∏Sname(σ(Stud.Rno=CGPA.Roll)and(CGPA>8.0) (Stud X StudCGPA))
14
Joins
Inner Joins:
O Theta join
O EQUI join
O Natural join
Outer join:
O Left Outer Join
O Right Outer Join
O Full Outer Join
15
Inner Joins
A ⋈θ B
O A ⋈ A.column 2 > B.column 2 (B)
O A ⋈ A.column 2 = B.column 2 (B)
O A*B
Find the name of the students who are maintaining the
CGPA is more than 8.0
Stud(Rno, Sname, Address, Semester)
StudCGPA(Roll, CGPA)
∏name(σCGPA>8.0 (Stud ⋈ SRno=Roll (StudCGPA))
(or)
∏name(σCGPA>8.0 (Stud * ρ (Rno,CGPA) (StudCGPA))
16
Outer Join
O Left Outer Join (A B)
O Right Outer Join: ( A B )
O Full Outer Join: ( A B)
17
Example
Student : Rno, Name
CourseEnroll: Rno, Cno
O Find the name of the students who registered for the
course and also not registered the course
∏Name,Cno(Student CourseEnroll)
O List the name of the courses registered by the
students and also not registered by the students
∏Name,Cno(Student CourseEnroll)
18
19
Example
O Select the tuples for all employees who either work in
department 4 and make over 25,000 per year, or work in
department 5 and make over 30,000
σ(Dno=4 AND Salary>25000) OR (Dno=5 AND Salary>30000)(EMPLOYEE)
20
Example
O Find the regno,make,modelyear and color of
the cars of year 1996 model, where faults have
been found in the inspection for year 1999.
21
Answer
22
Extended Relational-Algebra-
Operations
O Generalized Projection
Extends the projection operation by allowing
arithmetic functions to be used in the
projection list
O Aggregate Functions
24
Division
Division operator A÷B can be applied if and only if:
O Attributes of B is proper subset of Attributes of A
O The relation returned by division operator will have
attributes = (All attributes of A – All Attributes of B)
O The relation returned by division operator will
return those tuples from relation A which are
associated to every B’s tuple.
25
The operation is valid as attributes in ALL_SPORTS is
a proper subset of attributes in STUDENT_SPORTS.
Output:
STUDENT_SPORTS÷ ALL_SPORTS 26
Find the output
27
Output:
28
*
Introduction to Database Keys
1
2
DBMS has following seven types of Keys
each have their different functionality:
*Super Key
*Primary Key
*Candidate Key
*Alternate Key
*Foreign Key
*Compound Key and Composite Key
*Surrogate Key
*
3
*Super Key - A super key is a group of single or
multiple keys which identifies rows in a table.
*
4
*Candidate Key - is a set of attributes that
uniquely identify tuples in a table. Candidate
Key is a super key with no repeated
attributes.
*Primary Key - is a column or group of
columns in a table that uniquely identify
every row in that table.
*Alternate Key - is a column or group of
columns in a table that uniquely identify
every row in that table.
5
*
*
6
*Foreign Key - is a column that creates a
relationship between two tables.
*
7
*COMPOUND KEY and COMPOSITE 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.
*
8
COMPOSITE KEY
*
9
COMPOUND KEY
*
10
SURROGATE KEYS
*isan artificial key which aims to uniquely identify
each record is called a surrogate key.
*Surrogate key is usually an integer.
*A surrogate key is a value generated right before the
record is inserted into a table.
11
*
* https://www.studytonight.com/dbms/databas
e-key.php
* https://www.guru99.com/dbms-keys.html
*
12