0% found this document useful (0 votes)
112 views301 pages

Unit 1 DBMS

This document provides an overview of SQL (Structured Query Language) including data types, DDL (Data Definition Language) commands, and DML (Data Manipulation Language) commands. It discusses various SQL data types such as CHAR, VARCHAR, VARCHAR2, NUMBER, INTEGER, and DATE. It describes key DDL commands for defining and modifying database schema including CREATE, DROP, ALTER, TRUNCATE, COMMENT, and RENAME. It also explains important DML commands for manipulating data like INSERT, UPDATE, DELETE, and SELECT including usage of operators like AND, OR in SELECT statements.

Uploaded by

kumar
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)
112 views301 pages

Unit 1 DBMS

This document provides an overview of SQL (Structured Query Language) including data types, DDL (Data Definition Language) commands, and DML (Data Manipulation Language) commands. It discusses various SQL data types such as CHAR, VARCHAR, VARCHAR2, NUMBER, INTEGER, and DATE. It describes key DDL commands for defining and modifying database schema including CREATE, DROP, ALTER, TRUNCATE, COMMENT, and RENAME. It also explains important DML commands for manipulating data like INSERT, UPDATE, DELETE, and SELECT including usage of operators like AND, OR in SELECT statements.

Uploaded by

kumar
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
You are on page 1/ 301

SQL- Structured Query

Language

1
OVERVIEW

฀ Introduction
฀ Data type
฀ DDL

2
Introduction

฀ SQL Structured Query Language


฀ Standard language for dealing with Relational Databases
E.g.:
Relational databases: MySQL, Oracle, Ms SQL server,
Sybase

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

E.g: Ename char(10) ฀allocate 10 bytes


Input: SANJAY฀ 6 characters+4 Spaces

4
Cond…
VARCHAR:varchar(n)

฀ Variable-length character string


฀ store up to 2000 bytes of characters
฀ shorter value ฀ blank-padded are not added
฀ To large value ฀returns an error

E.g: Ename varchar(10)


Input: SANJAY฀ only 6 bytes

5
Cond…
VARCHAR2:varchar2(n)

฀ Variable-length character string


฀ store up to 4000 bytes of characters
฀ shorter value ฀ blank-padded are not added
฀ To large value ฀returns an error
E.g: Ename varchar2(10)
Input: SANJAY฀ only 6 bytes

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

NUMBER: input: 12.2 => 12.2


NUMBER: input: 12.5 => 12.5
฀ Date: The default format is a 2-digit day, a 3-letter
month, and a 2-digit year
Input: ‘01-JAN-99’

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), .... );

CREATE TABLE Employee (ENAME varchar2(20),


EID INT, Address varchar2(20) );

14
Cond…
DESC or either DESCRIBE:
View the structure of table

DESC Employee; OR DESCRIBE Employee;


Name Null Type
NAME VARCHAR2(20)
EID INT
ADDRESS VARCHAR2(20)

15
DDL - DROP
฀ DROP - delete a whole database

DROP TABLE table_name;

Drop table Students;

16
DDL - ALTER
฀ ALTER -add, delete/drop or modify columns in the
existing table

ALTER TABLE – ADD


ALTER TABLE table_name ADD (Columnname_1
datatype, Columnname_2 datatype, … Columnname_n
datatype);

ALTER TABLE Employee ADD (City varchar(20));

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);

ALTER TABLE Employee MODIFY(City varchar(40));

18
DDL-ALTER
฀ ALTER TABLE – DROP

ALTER TABLE table_name DROP COLUMN


column_name;

ALTER TABLE Employee DROP COLUMN


City;

19
DDL-ALTER
฀ ALTER TABLE- RENAME

ALTER TABLE Tablename RENAME COLUMN


OLDNAME TO NEWNAME;

ALTER TABLE Employee RENAME COLUMN Ename


TO EmpName;

20
DDL-TRUNCATE
฀ TRUNCATE
Removes the data from the table

TRUNCATE TABLE Employee;

Difference between Drop and Truncate

21
DDL- Comment
฀ Comments can be written in the following three formats:

Single line comments


-- drop table stud;
Multi line comments
/* multi line comment another comment */
In line comments
Create table stud /* this is a stud table; */( name….)

22
DDL-RENAME
฀ RENAME
- set a new name for any existing table

RENAME TABLE old_table_name to new_table_name;

RENAME TABLE student to students_info;

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,…);

INSERT INTO Employee VALUES (‘HARI’, 5, ‘kovai’);

 INSERT INTO Employee (ENAME,EID) VALUES


(‘PRATIK’,56);

3
DML- UPDATE
UPDATE table_name SET column1 = value1, column2 =
value2,... WHERE condition;

UPDATE Student SET NAME = 'PRATIK';


4
DML-Update
UPDATE Student SET NAME = 'PRATIK' WHERE
Age = 20;
ROLL_NO NAME ADDRESS PHONE Age
XXXXXXXX
1 Ram Delhi 18
XX
XXXXXXXX
2 RAMESH GURGAON 18
XX
XXXXXXXX
3 PRATIK ROHTAK 20
XX
XXXXXXXX
4 SURESH Delhi 18
XX
XXXXXXXX
3 PRATIK ROHTAK 20
XX
XXXXXXXX
2 RAMESH GURGAON 18
XX
5
SQL Basic Operators
Precedence
Level SQL Operator
1 Unary + - arithmetic operators
2 * / arithmetic operators
3 Binary + - arithmetic operators, || character operators

4 All comparison operators


5 NOT logical operator
6 AND logical operator
7 OR logical operator

6
Comparison Operator
= Equality test.

!=, ^=, <> Inequality test.

> Greater than test.

< Less than test.

>= Greater than or equal to test.

<= Less than or equal to test.

7
DML-Delete
DELETE FROM table_name WHERE some_condition;

DELETE FROM Student;


or
DELETE * FROM Student;

DELETE FROM Student WHERE NAME = 'Ram';


DELETE FROM Student WHERE Age = 20;
DELETE FROM Student WHERE Age = 20 and
Name=‘Ram’;
8
DML-SELECT
Select cloumn name,… from tablename where condition;

 SELECT * FROM Employee;

 SELECT * FROM Employee WHERE Age=30;

To fetch Name and Address of students with ROLL_NO


greater than 3
SELECT ROLL_NO,NAME,ADDRESS FROM Student
WHERE ROLL_NO > 3;
9
DML-Select -AND
To fetch all the records from Student table where Age is
18 and ADDRESS is Delhi.
SELECT * FROM Student WHERE Age = 18 AND
ADDRESS = 'Delhi';

To fetch all the records from Student table where NAME


is Ram and Age is 18.
SELECT * FROM Student WHERE Age = 18 AND
NAME = 'Ram';

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';

To fetch all the records from Student table where NAME


is Ram or Age is 20.
SELECT * FROM Student WHERE NAME = 'Ram'
OR Age = 20;

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.

SELECT * FROM Student WHERE Age = 18 AND


(NAME = 'Ram' OR NAME = 'Raj');

SELECT * FROM Student WHERE Age = 18 AND NAME


= 'Ram' OR NAME = 'Raj';  Incorrect

12
SELECT in INSERT
INSERT INTO first_table SELECT * FROM second_table;

INSERT INTO Student SELECT * FROM LateralStudent;

INSERT INTO first_table(names_of_columns1) SELECT


names_of_columns2 FROM second_table;

INSERT INTO Student(ROLL_NO, NAME, Age) SELECT


ROLL_NO, NAME, Age FROM LateralStudent;

13
SELECT in CREATE
Create an exact copy of a table with or without the data

CREATE TABLE table_name_1 AS


SELECT [*]/column_name(s) FROM table_name_2
WHERE expression;

14
SELECT in CREATE
Copy both the structure and data of a table
CREATE TABLE employees_copy AS SELECT *
FROM employees;

Copy specific columns of a table along with their data


CREATE TABLE employees_copy AS SELECT
first_name, last_name, email FROM employees;

15
SELECT in CREATE
Copy only structure of the table without the data

add a where clause which will never set to be true or


always false

CREATE TABLE employees_copy AS SELECT


first_name, last_name, email FROM employees
WHERE 1=0;

16
Quick Review
 Insert
 Update
 Delete
 Select

17
Review Questions
GATE CS 2011

Consider a database table T containing two columns X and Y


each of type integer. After the creation of the table, one record
(X=1, Y=1) is inserted in the table.
Let MX and My denote the respective maximum values of X and
Y among all records in the table at any point in time. Using MX
and MY, new records are inserted in the table 128 times with X
and Y values being MX+1, 2*MY+1 respectively. It may be
noted that each time after the insertion, values of MX and MY
change. What will be the output of the following SQL query after
the steps mentioned above are carried out?
SELECT Y FROM T WHERE X=7;
(A) 127
(B) 255
(C) 129
(D) 257
18
Cond…

19
SQL- Structured Query
Language

1
Constraints
฀ are the rules enforced on the data columns of a table.

฀ used to limit the type of data that can go into 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
);

ALTER TABLE Persons MODIFY Age int NOT NULL;

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) );

Multiple Column Constraint:


฀ CREATE TABLE Persons (ID int , LastName
varchar(25) NOT NULL, FirstName varchar(25), Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName) );

6
Unique- Alter
฀ CREATE TABLE Persons (ID int, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);

Add constraint to Persons table on column ID


ALTER TABLE Persons ADD UNIQUE (ID);
ALTER TABLE Persons ADD CONSTRAINT
UC_Person UNIQUE (ID);

Remove the constraint from Persons


ALTER TABLE Persons DROP CONSTRAINT
UC_Person;

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) );

Multiple Column Constraint:


฀ CREATE TABLE Persons (ID int , LastName
varchar(25) NOT NULL, FirstName varchar(25), Age int,
CONSTRAINT PC_Person primary key (ID, LastName));

8
Primary key- Alter
฀ CREATE TABLE Persons (ID int, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);

Add constraint to Persons table on column ID


ALTER TABLE Persons ADD primary key (ID);
ALTER TABLE Persons ADD CONSTRAINT
PC_Person primary key (ID);

Remove the constraint from Persons


ALTER TABLE Persons DROP CONSTRAINT
PC_Person;

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));

Add multiple conditions:


฀ CREATE TABLE Persons ( ID int Primary key, LastName
varchar(25), FirstName varchar(25), Age int,
CONSTRAINT CHK_Person CHECK (Age>=18 and
LastName=‘xxx’));
10
Check-Alter
฀ CREATE TABLE Persons (ID int, LastName
varchar(25) NOT NULL,FirstName varchar(25), Age int);

Add constraint to Persons table on column Age


ALTER TABLE Persons ADD CHECK (Age>=18);
ALTER TABLE Persons ADD CONSTRAINT
CC_Person CHECK (Age>=18);

Remove the constraint from Persons


ALTER TABLE Persons DROP CONSTRAINT
CC_Person;

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>;

฀ ALTER TABLE STUDENTS MODIFY EXAM_FEE


INT DEFAULT 10000;

13
FOREIGN KEY Constraint
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

OrderID OrderNumber PersonID


1 77895 3
2 44678 3
3 22456 2
4 24562 1

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);

฀ ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
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) );

฀ CREATE TABLE products ( product_id number(10),


supplier_id number(10), CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id) REFERENCES
supplier(supplier_id) ON DELETE CASCADE );

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) );

฀ CREATE TABLE inventory ( inventory_id INT


PRIMARY KEY, product_id INT, quantity INT,
min_level INT, max_level INT, CONSTRAINT
fk_inv_product_id FOREIGN KEY (product_id)
REFERENCES products (product_id) ON DELETE
SET NULL );

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));

฀ Table level constraints apply to groups of one or more


columns
CREATE TABLE sample2(firstname CHAR(20) NOT NULL,
lastname CHAR(20) NOT NULL, UNIQUE(firstname,
lastname));
20
SQL- Structured Query
Language

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

Both tables should have same number of columns to perform set


operations

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;

SELECT * FROM First INTERSECT SELECT * FROM


Second;

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;

SELECT supplier_id, supplier_name FROM suppliers WHERE


supplier_id > 2000 MINUS SELECT company_id, company_name
FROM companies WHERE company_id > 1000

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

Select aggregate function(Column name) from table


name;
13
Cond…

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

Count total number of different companies in the table Product


SELECT COUNT(DISTINCT COMPANY) FROM
PRODUCT;
3
Count total number of records in the table Product where the
rate of the product is more than 15
SELECT COUNT(*) FROM PRODUCT WHERE RATE>15;
7

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

SELECT COMPANY, COUNT(product)


FROM PRODUCT GROUP BY
COMPANY;

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

SELECT COMPANY, COUNT(*)FROM


PRODUCT
WHERE RATE>15 GROUP BY COMPANY;

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

SELECT COMPANY, COUNT(*)FROM PRODUCT


GROUP BY COMPANY
HAVING COUNT(*)>2;

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

SELECT COMPANY, COUNT(*)FROM PRODUCT


WHERE RATE>15 GROUP BY COMPANY
HAVING COUNT(*)>2;

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

8 NIRAJ ALIPUR XXXXXXXXXX 19

7 ROHIT BALURGHAT XXXXXXXXXX 18

6 DHANRAJ BARABAJAR XXXXXXXXXX 20

5 SAPTARHI KOLKATA XXXXXXXXXX 19

4 DEEP RAMNAGAR XXXXXXXXXX 18

3 RIYANKA SILIGURI XXXXXXXXXX 20

2 PRATIK BIHAR XXXXXXXXXX 19


30
1 HARSH DELHI XXXXXXXXXX 18
SELECT * FROM Student ORDER BY Age ASC ,
ROLL_NO DESC;
(or)
SELECT * FROM Student ORDER BY Age, ROLL_NO
DESC;
ROLL_NO NAME ADDRESS PHONE Age

7 ROHIT BALURGHAT XXXXXXXXXX 18

4 DEEP RAMNAGAR XXXXXXXXXX 18

1 HARSH DELHI XXXXXXXXXX 18

8 NIRAJ ALIPUR XXXXXXXXXX 19

5 SAPTARHI KOLKATA XXXXXXXXXX 19

2 PRATIK BIHAR XXXXXXXXXX 19

6 DHANRAJ BARABAJAR XXXXXXXXXX 20

3 RIYANKA SILIGURI XXXXXXXXXX 20


31
SELECT TOP Clause
฀ SELECT TOP clause is used to fetch limited number of
rows from a database. This clause is very useful while
dealing with large databases.

SELECT TOP value * column1,column2 FROM


table_name;

To fetch first two records from Student table

SELECT TOP 2 * FROM Student;

32
Cond…
SELECT TOP value PERCENT column1,column2
FROM table_name;

To fetch 50 percent of the total records from Student


table.

SELECT TOP 50 PERCENT * FROM Student;

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;

To fetch Branch using Stream as alias name and Grade as


CGPA from table Student_Details.
SELECT Branch AS Stream, Grade as CGPA FROM
Student_Details;

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

SELECT Ename FROM EMP WHERE NOT (sal


BETWEEN 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

SELECT column1, column2, ...FROM table_name


WHERE column LIKE pattern;

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.

SELECT * FROM Product WHERE ProductName LIKE


'Cha_' OR ProductName LIKE 'Chan_‘;

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

Which of the following statements are TRUE about an SQL query?

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

฀ Combine Multiple Tables


฀ CARTESIAN PRODUCT
฀ JOIN

2
StudentCourse

3
Cond…

฀ Display student name and their


enrolled course details of the students

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…

SELECT Student.Roll_No, NAME,


COURSE_ID FROM Student, StudentCourse
where
Student.Roll_no=StudentCourse.Roll_no;
(or)
SELECT S.Roll_No, NAME, COURSE_ID
FROM Student S, StudentCourse C where
S.Roll_no=C.Roll_no;

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

SELECT S.Roll_No, NAME


FROM Student S, StudentCourse C
where S.Roll_no=C.Roll_no and Course_ID=2;

13
Cond…
Roll_No Name
2 Ramesh
3 Sujit

14
JOIN
฀ INNER JOIN

SELECT * FROM table1 INNER JOIN table2 ON


table1.matching_column = table2.matching_column;

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)

SELECT * FROM (Customer AS Customer(ID,


name) NATURAL JOIN Addresses);

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

Security and authorization subsystem


DBA creates accounts and to specify account
restrictions
DBMS should enforce these restrictions automatically

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

DBMS software automatically performs any


necessary conversions
Impedance mismatch – differences between the
database model and the programming language model
object-oriented database systems

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

data are interrelated

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.

One person is married to only one person.

9
*Degree of relationship
Binary Relationship

Ternary or n-ary 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

A department recruits faculty

Many houses are owned by a person

Authors write books

14
*

Binary and N:1


15
*Participation Constraint
*Total Participation(Existence dependency)
*Partial Participation

16
*Role Name: Recursive
Relationships

17
*Weak Entity Partial key or discriminator
key

Parent entity type or Child entity type or


Dominant entity type Subordinate entity type
18
Payment No Amount Duration
P1 20000 30
P2 30000 25
P3 40000 20
P1 20000 30
P3 40000 20
P2 30000 25
P3 40000 20

Loan No Payment No Amount Duration


1 (Home) P1 20000 30
1 P2 30000 25
1 P3 40000 20
2 (Gold) P1 20000 30
2 P3 40000 20
3 (Car)
3
P2
P3
30000
40000 19
25
20
*
*
* An entity type DEPARTMENT with attributes Name,
Number, Locations, Manager, and
Manager_start_date. Locations is the only
multivalued attribute. And specify that both Name
and Number are (separate) key attributes because
each was specified to be unique.

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

Consider the following ER diagram.

The minimum number of tables needed to


represent M, N, P, R1, R2 is
(A) 2
(B) 3
(C) 4
(D) 5

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

In an Entity-Relationship (ER) model, suppose R is a many-


to-one relationship from entity set E1 to entity set E2. Assume
that E1 and E2 participate totally in R and that the cardinality
of E1 is greater that the cardinality of E2.
Which one of the following is true about R?
(A) Every entity in E1 is associated with exactly one entity in
E2.
(B) Some entity in E1 is associated with more than one entity
in E2.
(C) Every entity in E2 is associated with exactly one entity in
E1.
(D) Every entity in E2 is associated with at most one entity in
E1.

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.

OWNER that is a subclass of the UNION of the


three entity sets of COMPANY, BANK, and
PERSON

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)

O Select the columns Name and Age for all the


rows of data in Student table
∏Name, Age(Student)

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)

O Display the name of the managers


∏Fname,Lname,MName(Employee ⋈ Mgr_Ssn=Ssn (Department))

O Find the name of the projects which are controlled by the


department and also fetch the name of manager
∏Fname,Lname,Mname,PName((Project ⋈ Dnum=Dnumber Department)
⋈ Mgr_Ssn=Ssn 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

list of attributes on aggregate function –


which to group E.g.: Sum(Salaray) 23
Cond…
O Find the average of salary
of the department

O Find the average salary in


each department

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.

The attributes in resulting relation


{ROLL_NO,SPORTS} - {SPORTS} = ROLL_NO

ROLL_NO which are associated with all B’s tuple


{Badminton, Cricket}. ROLL_NO 1 and 4 are
associated to Badminton only. ROLL_NO 2

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.

The difference between compound and the


composite key is that any part of the compound
key can be a foreign key, but the composite key
may or maybe not a part of the foreign key.

*
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.

Fname Lastname Start Time End Time


Anne Smith 09:00 18:00
Jack Francis 08:00 17:00
Anna McLean 11:00 20:00
Shown Willam 14:00 23:00

11
*
* https://www.studytonight.com/dbms/databas
e-key.php
* https://www.guru99.com/dbms-keys.html

*
12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy