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

Lecture Notes

The document discusses SQL concepts including the relational data model, DDL, DML, and DCL. It covers creating databases and tables with constraints using SQL, along with foreign keys and cascading operations. The document also discusses altering and dropping database objects using DDL statements.

Uploaded by

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

Lecture Notes

The document discusses SQL concepts including the relational data model, DDL, DML, and DCL. It covers creating databases and tables with constraints using SQL, along with foreign keys and cascading operations. The document also discusses altering and dropping database objects using DDL statements.

Uploaded by

Harsh Taneja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Computer Engineering Dept, NIT Kurukshetra

ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Relational Data Model

 Introduction to SQL Concepts : DDL, DML & DCL

Till now, we have covered the modelling aspect of relational database. In this, the creation
of conceptual schema (as ERD) and then its mapping into logical schema is covered.

So naturally, we are ready with a Logical schema version of the Data requirements. The next
step to create this schema into the system.

From here, we are diving into the various concept of SQL (Structure Query Language). F
or the Creation, Manipulation and overall Management of a relational DB, we will discuss
theses concepts in details.
 Important Term:
 Relational DB Table/relation
 Attribute/Column
 Tuple/Row
 Domain
 Relational Model Constraints (PK, Unique, Not Null, Check, Default, FK).
 Null Values & its three –valued logic

 1st step in this is the creation of relational DB schema in form of relational DB Table,
with appropriate Constraints & DataType & 2nd step is population of data values.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

So now, we begin discussing the various concepts of SQL for achieving both steps on
relational DB.
SQL has three set of expression (for Programmer User):
B objects (DB, Table,
 Data Definition Lang. (DDL): to create & manage the D
views, triggers, packages, procedure, etc).

 Data Manipulation Lang. (DML): to create/upload & manage data values.


 Data Control Lang. (DCL): to manage the user access on DB objects.

Set Set of Expressions (Clause & Functions)

DDL CREATE, ALTER, DROP, TRUNCATE, & RENAME

DML INSERT, UPDATE, & DELETE

DCL GRANT & REVOKE

Clause: SELECT, FROM, WHERE, ORDER BY, HAVING, GROUP BY


Retrieval Queries
Functions: Aggregate, Substring Matching, etc.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Data Definition Language (DDL)


Aim: to create the DB objects {DB, Table, Views, Triggers, Packages, Procedures, etc}.

sql> show databases;

sql>Create database Db1;

sql>Use db1;

sql [db1]> show tables;

O/p: the DB control moves inside the Db1.

sql [db1]> Create table Student;

O/p: Error;

sql [db1]> Create table Student (Fname char(20), Rollno Int (10), DOB date);

O/p: a DB table ‘Student 2’ is created with three attribute

sql [db1]> Desc student;

O/p: a Metadata table, which describe the details about DB Table Student.

sql [db1]> Create table Student2 (Fname char(10) not null, Rollno int (10) primary key);

O/p: a DB table ‘Student 2’ is created with two attributes, where Rollno is PK.

sql [db1]> Create table Students3 (Fname char(10) primary key, Rollno int(10) primary key;

O/p: Error;

sql [db1]> >Create table Students4 (Fname char(10), Rollno int(10), primary key(fname, Rollno));

O/p: a DB table ‘Student 4’ with two attributes & both as part of PK is created.

1
CSPC-25) Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to SQL Concepts : DDL

 Foreign key & On Cascade Constrains.

 Data Definition Language (DDL)


Set Set of Expressions (Clause & Functions)
DDL CREATE, ALTER, DROP, TRUNCATE, & RENAME

Aim: to create the DB objects {DB, Table, Views, Triggers, Packages, Procedures, etc}.

sql> show databases;


sql>Create database Db1;
sql>Use db1;
sql [db1]> show tables;
O/p: the DB control moves inside the Db1.
sql [db1]> Create table Student;
O/p: Error;
sql [db1]> Create table Student (Fname char(20), Rollno Int (10), DOB date);
O/p: a DB table ‘Student 2’ is created with three attribute
sql [db1]> Desc student;
O/p: a Metadata table, which describe the details about DB Table Student.
sql [db1]> Create table Student2 (Fname char(10) not null, Rollno int (10) primary key);
O/p: a DB table ‘Student 2’ is created with two attributes, where Rollno is PK.
sql [db1]> Create table Students3 (Fname char(10) primary key, Rollno int(10) primary key;
O/p: Error;
sql [db1]> >Create table Students4 (Fname char(10), Rollno int(10), primary key(fname, Rollno));
O/p: a DB table ‘Student 4’ with two attributes & both as part of PK is created.

5
CSPC-25) Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Foreign Key Concept

sql [db1]> Create table Students6 (Fname char (10), Rollno int (10), Dno int (2),

Primary key (Rollno),

Foreign key (dno) references Dept (deptno) ) ;

O/p: Error

sql [db1]> Create table dept (deptname char (5), deptno int (3) Primary key) ;

sql [db1]> Create table Students7 (Fname char (10), Rollno int (10), Dno int (2),

Primary key (Rollno),

Foreign key (dno) references Dept (deptno));

O/p: both DB tables will be created using appropriate constraints.


= = = = = = = = = = = = = = = = == = = == = = = = = == = =
 Concept of ‘On Cascade’ while Creation of the DB table

Example > create table students8 (fname char (10), rollno int (10) primary key, dno int (2),

foreign key (dno) references dept (deptno) on delete cascade on update cascade);

 On delete [cascade | Set null | Set Default ]


 On update [cascade | Set null | Set Default ]

sql [db1]> create table students8 (fname char (10), rollno int (10) primary key, dno int (2),
foreign key (dno) references dept (deptno) on delete set null, on update cascade);

sql [db1]> create table students8 (fname char (10), rollno int (10) primary key, dno int (2),
foreign key (dno) references dept (deptno) on delete set default, on update cascade);

sql [db1]> create table students8 (fname char (10), rollno int (10) primary key, dno int (2),
foreign key (dno) references dept (deptno) on delete set default, on update set null);

5
CSPC-25) Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

O/p: ??

Reflection Question:

5
CSPC-25) Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Topic: DDL (Alter)

Aim: to modify the definition of the existing Objects (Table: on Attribute & Constraints)
e.g. Add/rename/remove attribute & Add/Remove the Constraint on the Attribute.

= = = = = = = Add/rename/remove attribute = = = = = = = = = =

Sql [db1]> Alter table student add lname char (20) not null;

O/p: Simply added an attribute (lname) in existing student table.

Sql [db1]> Alter table student rename;

O/p: ?

Sql [db1]> Alter table student rename column rollno roll_no;

Sql [db1]> Alter table student change column rollno roll_no;

O/p: Rename the attribute in DB table

Sql [db1]> Alter table student drop column dob;

O/p: Removed an attribute from DB table

= = = = = = = = Add/removing Constraints on existing attribute = = =

Sql [db1]> Alter table student11 add address_notnull constraints not null (address);

O/p: added the not null constraint as address_notnull on attribute ‘address’ .

Sql [db1]> Alter table student11 drop address_notnull;

O/p: remove the constraint address_notnull on attribute ‘address’.

5
CSPC-25) Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Topic: DDL ( Drop, Truncate, Rename)

Aim: to remove the definition of the existing Objects (Table: on Attribute & Constraints)

Sql [db1]> drop table student11;

O/p: The DB table student 11 is removed.

Sql [db1]> desc student 11;

O/p: The object does not exist, as definition is removed.

Sql [db1]> truncate table student10;

O/p: This will only remove the Data values/item in the DB table student10.

Sql [db1]> rename table student10;

O/p: ?

5
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to SQL Concepts: Retrieval Queries

 Fundamental Clause & other concepts.

After the creation of DB relation & insertion of the DB records, next important task is the
retrieval of the DB records.

In the relational DB, to retrieve the DB records following Clauses are used:
sql> SELECT ..... FROM ..... WHERE .....ORDER BY..... GROUP BY ....HAVING ;

From the above, SELECT & FROM are the mandatory clause in the retrieval query.

 SELECT clause is to list the attribute required in the results.


 FROM clause is to list the Relations/Tables required for retrieval.
 WHERE clause is to list all the condition on the tuples
 ORDER BY to mention the arranged list
 GROUP BY to create the sub group of results
 HAVING to apply the additional Condition on GROUP BY result.

 Order of Execution of clauses:

FROM, WHERE, ORDER BY, GROUP BY, HAVING, SELECT;

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

ABC

A B C D

sql> Select A as Fname from ABC;

O/P: Retrieves all records of the Table (emp), as * is used to extract all the Attributes & Tuples.

sql> Select Fname as First Name from Employee;

sql> Select distinct (Salary) from Employee;

 Aggregate Function

(Count, Min, Max, Sum, Average, STD Dev, etc): Mathematical Operators.

sql> Select Count (*) from Employee;

O/P: Total number of tuple/ total employees.

sql> Select Count (Salary) from Employee;

sql> Select Max (salary), Min (salary), average (salary) from Employee;

 Substring Matching

(%, _ ): % refers to variable length text string, _ place .

sql> Select * from Employee where address = ‘%india%;

sql> Select * from Employee where dob = ’_ _ , _ _, 198_;

sql> Select * from Employee where fname like ’_J%;

sql> Select * from Employee where fname like ’_ _ _J;

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to SQL Concepts: Retrieval Queries

 Concepts of Cartesian Product, Join Operator, and other Binary Operator

We have discussed:
 Basic Clauses (Select, From, Where, Order by, Group By, Having).
 Aggregate Function ( Count, Min, Max, Sum, Average, etc)
 Substring Matching (&, _ ) & like function.
Next, we will discuss,
 Cartesian Product: Select *
from Person, Customer;

Cardinality :( No. of tuple/Rows = no. of tuple in (relation 1) * no. of tuple in (relation 1)


No. of Attributes = (Attribute in relation1 + Attribute in relation2)
 Select * from Person, Customer;

Person Customer
Name Age Food Name Add
Rajesh 22 Paratha Rajinder db1
Vipul 24 Sambhar Jitender db2
Kulwinder db3
Dharminder db4
Hemant db5
Rajesh db6

Relation ( person X Customer)


Name Age Food Name Add
Rajesh 22 Paratha Rajinder db1
Rajesh 22 Paratha Jitender db2
Rajesh 22 Paratha Kulwinder db3
Rajesh 22 Paratha Dharminder db4
Rajesh 22 Paratha Hemant db5
Rajesh 22 Paratha Rajesh db6
Vipul 24 Sambhar Rajinder db1
Vipul 24 Sambhar Jitender db2
Vipul 24 Sambhar Kulwinder db3
Vipul 24 Sambhar Dharminder db4
Vipul 24 Sambhar Hemant db5
Vipul 24 Sambhar Rajesh db6

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Join :: Inner (matching tuples), Outer (non-matching tuples of a relations) & Semi

Inner Join (Natural, Equi, & Theta)

Natural Join: Select * from Project Natural join Dept;


(1). Compare all common attributes from participating Relations (As in following
Relations, Project name & Project ID are the common attributes)
(2). Final table will retain both Instances of all common attributes (Join attribute).

Project
Project Name Projects ID Fund Start_date Dept Name Dept ID Project ID
p1 111 1k 1/1/2012 d1 co 111
p2 121 12k 1/2/2010 d2 me 111
p3 131 13k 2/2/2012 d3 ch 121
p4 141 2k 3/5/2011 d4 ec 141
p5 151 12k 1/1/2010 d6 ee 141
p6 161 12 2/2/2010
p7 171 13k 2/2/2012
Resultant Relation
Project Name Project ID Fund Start_date Dept Name Dept ID Project ID
p1 111 1k 1/1/2012 d1 co 111
p1 111 1k 1/1/2012 d2 me 111
p2 121 12k 1/2/2010 d3 ch 121
p4 141 2k 3/5/2011 d4 ec 141
p4 141 2k 3/5/2011 d6 ee 141

Equi Join
(1) Comparison on common attributes on Equality (=) condition only.
(2) Final Relation will retain only single of common attribute (Join Attribute)

Person Menu
Ag
Name e Food Food Day
Rajesh 22 Paratha Roll Monday
Vipul 24 Sambhar idly Tuesday
Wednesda
Pawan 21 Pizza Pizza y
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Fried rice Friday
Akhil 25 Sandwich Poha Saturday
Hemant 40 Fried rice
Ajay 29 Roll
Relation (Person Menu)
Name Age Person.Food Day
Ajay 29 Roll Monday
Dravid 39 idly Tuesday
Pawan 21 Pizza Wednesday
Kashish 22 Dosa Thursday

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Hemant 40 Fried rice Friday


Theta Join

(1). Comparison on common attributes on Non-Equality (<,>,>=,<=) condition only.


(2). Final Relation will retain both Instances of common attribute.
(Like Both Project Name & Project ID will appears once, In Resultant Relation)

Outer Join

Left Outer Join


(1) Comparison on common attributes on Equality/Matching conditions only.
(2) Final Relation will retain both Instances of common attribute.
(Like both instances of attributes of Menu will appear, In Resultant Relation)
(3). Final relation will retain all tuples/rows from Left relation & matching tuples from
right relation.
No of tuple/Rows = total no of tuples/rows in Left relation
No of Attributes = (Attribute in left relation+ Attribute in Right relation)

Person Menu
Name Age Food Food Day
Rajesh 22 Paratha Roll Monday
Vipul 24 Sāmbhar idly Tuesday
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Fried rice Friday
Akhil 25 Sandwich Poha Saturday
Hemant 40 Fried rice
Ajay 29 Roll

Relation (Person left outer join Menu)


Name Age Person.Food Menu.Food Day
Rajesh 22 Paratha Null Null
Vipul 24 Sāmbhar Null Null
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Idly Tuesday
Akhil 25 Sandwich Null Null
Hemant 40 Fried rice Fried rice Friday
Ajay 29 Roll Roll Monday

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Right Outer Join

(1) Comparison on common attributes on Equality/Matching condition only.


(2) Final Relation will retain both Instances of common attribute.
(Like both instances of attributes of Menu will appear, In Resultant Relation)
(3). Final relation will retain all tuples/rows from Right relation & matching tuples
from Left relation.
No of tuple/Rows = total no of tuples/rows in Right relation
No of Attributes= (Attribute in left relation+ Attribute in Right relation)

Person Menu
Name Age Food Food Day
Rajesh 22 Paratha Roll Monday
Vipul 24 Sambhar idly Tuesday
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Fried rice Friday
Akhil 25 Sandwich Poha Saturday
Hemant 40 Fried rice
Ajay 29 Roll

Relation (Person right outer join Menu)


Name Age Person.Food Menu.Food Day
Ajay 29 Roll Roll Monday
Dravid 39 idly idly Tuesday
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Hemant 40 Fried rice Fried rice Friday
Null Null Null Poha Saturday

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Full Outer Join

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(1). Comparison on common attributes on Equality/Matching condition only.


(2). Final Relation will retain both Instances of common attribute.
(Like both instances of attributes of Menu will appear, In Resultant Relation)
(3). Final relation will retain all tuples/rows from both relations.
No of tuple/Rows = total no of tuples/rows in Right relation
No of Attributes= (Attribute in left relation+ Attribute in Right relation)

Person Menu
Name Age Food Food Day
Rajesh 22 Paratha Roll Monday
Vipul 24 Sambhar idly Tuesday
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Fried rice Friday
Akhil 25 Sandwich Poha Saturday
Hemant 40 Fried rice
Ajay 29 Roll

Relation (Person full outer join Menu)


Name Age Person.Food Menu.Food Day
Rajesh 22 Paratha Null Null
Vipul 24 Sambhar Null Null
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 Idly idly Tuesday
Akhil 25 Sandwich Null Null
Hemant 40 Fried rice Fried rice Friday
Ajay 29 Roll Roll Monday
Null Null Null Poha Saturday

2.3. Semi Join

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(1).A semi join is half Join.


(as the rows of one of the table that match with at least one row of another table. )
(2) Comparison on common attributes on Equality/Matching condition only.
(3) Final Relation will retain one Instances of common attribute.
(Like once instances of attribute Menu will appear, In Resultant Relation)
(4). Final relation will retain only matching tuples/rows on common attribute.
No of tuple/Rows = total no of matching tuples/rows
No of Attributes= (Attribute in Left relation)

Person Menu
Name Age Food Food Day
Rajesh 22 Paratha Roll Monday
Vipul 24 Sambhar idly Tuesday
Pawan 21 Pizza Pizza Wednesday
Kashish 22 Dosa Dosa Thursday
Dravid 39 idly Fried rice Friday
Akhil 25 Sandwich Poha Saturday
Hemant 40 Fried rice
Ajay 29 Roll
Relation (Person semi join
Menu)
Name Age Person.Food
Pawan 21 Pizza
Kashish 22 Dosa
Dravid 39 idly
Hemant 40 Fried rice
Ajay 29 Roll

Concept of Union Compatibility


12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

3. Union – (U)

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(1) All participating relations must be Union compatible with each other.
(2) Tuples/ Rows will be combined from all participating Tables/relations.
(3) Duplicate Tuples will be eliminated from Resultant relation.
(Tuple {Hemant, 40, Fried Rice} appear both in Person & Customer, thus eliminated).
no of tuple= [no of tuples (relation1) + no of tuples(relation2)] -(matching/duplicate
tuples)
no of Attributes= no of attributes in any participating Relation/Tables
Person Customer
Ag Ag
Name e Food Name e Food
Rajesh 22 Paratha Rajinder 56 Paratha
Vipul 24 Sambhar Jitender 60 Sambhar
Pawan 21 Pizza Kulwinder 55 Pizza
Kashish 22 Dosa Dharminder 76 Dosa
Dravid 39 idly Hemant 40 Fried rice
Akhil 25 Sandwich Rajesh 23 Paratha
Hemant 40 Fried rice
Ajay 29 Roll

Relation (Person U Customer)


Name Age Food
Rajesh 22 Paratha
Vipul 24 Sambhar
Pawan 21 Pizza
Kashish 22 Dosa
Dravid 39 idly
Akhil 25 Sandwich
Hemant 40 Fried rice
Ajay 29 Roll
Rajinder 56 Paratha
Jitender 60 Sambhar
Kulwinder 55 Pizza
Dharminder 76 Dosa
Rajesh 23 Paratha

4. Intersection
(1) All participating relations must be Union compatible with each other.
(2) Only matching Tuple/Rows from all participating tables/relations will be retain.

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(as following Person & Customer both have {Hemant, 40, Fried Rice} tuple}, this tuple
will be selected for Resultant relation).
no of tuple/Rows= (no of matching/common tuples/rows)
no of Attributes= no of attributes in any participating Relation/Tables

Person Customer
Ag
Name Age Food Name e Food
Rajesh 22 Paratha Rajinder 56 Paratha
Vipul 24 Sambhar Jitender 60 Sambhar
Pawan 21 Pizza Kulwinder 55 Pizza
Kashish 22 Dosa Dharminder 76 Dosa
Dravid 39 idly Hemant 40 Fried rice
Akhil 25 Sandwich Rajesh 23 Paratha
Hemant 40 Fried rice
Ajay 29 Roll
Relation (Person U Customer)
Name Age Food

Hemant 40 Fried rice

5. Set Difference ( - )
12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(1) All participating relations must be Union compatible with each other.
(2) Resultant relation consists of the tuples/rows that are in relation1 not in relation2.

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

(For Relation-Relation2)
(3) Matching Tuple/Rows from all participating Tables/relations will be removed.

Person Customer
Name Age Food Name Age Food
Rajesh 22 Paratha Rajinder 56 Paratha
Vipul 24 Sambhar Jitender 60 Sambhar
Pawan 21 Pizza Kulwinder 55 Pizza
Kashish 22 Dosa Dharminder 76 Dosa
Dravid 39 idly Hemant 40 Fried rice
Akhil 25 Sandwich Rajesh 22 Paratha
Hemant 40 Fried rice
Ajay 29 Roll
Relation (Person - Customer)
Name Age Food
Vipul 24 Sambhar
Pawan 21 Pizza
Kashish 22 Dosa
Dravid 39 idly
Akhil 25 Sandwich
Ajay 29 Roll

12
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to SQL Concepts: Retrieval Queries

 Concepts: Table Aliasing, Sub/Nested Query, Correlated Query & Group by Clause

We have discussed:
 Basic Clauses (Select, From, Where, Order by, Group By, Having).
 Aggregate Function ( Count, Min, Max, Sum, Average, etc)
 Substring Matching (&, _ ) & like function.
 Cartesian Product Operator
 DB Table Join Operator (Inner, Outer, & Semi): Inner (natural, equi, theta), Outer (left, right, full)
 Set Operators (Union, Intersection, & Set difference), Compatibility
Next, we will discuss,
How to use Join condition
DB table Aliasing

For example: E Dept


mp
Fname Salary Dno Dname Dno Dept_address

Sql> Select Fname, Salary, Dname


From Emp, Dept // equi-join// // From Emp Natural Join Dept//
Where Dno=Dno; // condition of join//
O/p: Error (ambiguity of Attributes)

Sql> Select Dno, Dname From Emp, Dept


Where Dno=Dno; // condition of join//
O/p: Error (ambiguity of Attributes)
Sql> Select e.Fname, e.Salary, d.Dname From Emp e, Dept d // table aliasing //
Where e.Dno=d.Dno; // condition of join//

Sql> Select e.fname, e.lname From employee e, employee f Where e.ssn= f.super_ssn And e.sex = f.sex;
Query: ????

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Sub Query, Nested Query & Co-related Query

Query: Retrieve the employee name & SSN, whose salary is higher than the minimum salary of the company.

Sql> Select Fname, SSN From Employee Where Salary > Min (Salary);
O/p: Error // inappropriate use of Aggregate function//

Sql> Select Fname, SSN


From Employee
Where Salary >
(Select Min (Salary) // Nested/ Inner/ sub-query//
From Employee);

Sql> Select Pname, Plocation


From Project
Where Pno = (Select Pno // subquery will retrieve Pno 1 & 2 //
From WORKS_ON
Where Essn=‘123456789’);
O/P: Retrieve the Pname & Plocaton of only for Pno 1, not for Pno 2.

 Comparison operator IN, suitable in case for Sub-Query/ Nested Query/ Co-related Query.

Sql> Select Distinct Essn


From WORKS_ON
Where Pno IN (Select Pno
From WORKS_ON
Where Essn=‘123456789’);
Query: ????

Sql> Select Distinct Essn From Works_On Where Pno IN (1, 2, 3);
Query: ????

Sql> Select Distinct Pnumber


From Project
Where Pnumber IN (Select Pnumber
From PROJECT, DEPARTMENT, EMPLOYEE
Where Dnum=Dnumber AND Mgr_ssn=Ssn AND Lname=‘Smith’);

Query: Name of the Projects number (Pno) that involve an employee whose last name is ‘Smith, as a manager
of the dept that controls the project.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Query: Name of the Projects number (pno) that involve an employee whose last name is ‘Smith, either as a
worker or as a manager of the department that controls the project.

Sql> (Select distinct (pnumber) From project, department, employee

Where dnum=dnumber AND mgr_ssn=ssn AND lname='Smith')

UNION

(Select distinct (pnumber) From project, works_on, employee

Where pnumber=pno AND essn=ssn AND lname= 'Smith');

 Co-related Query
Query: List the the names of employees whose salary is greater than the salary of all the employees in dno 5.

Sql> Select Lname, Fname From employee

Where Salary > (Select Salary

From employee

Where Dno=5);

O/p: ??????

Sql> Select Lname, Fname From employee e

Where (Select Salary

From employee f

Where e.salary> f.salary And Dno=5);

Sql> Select Lname, Fname From employee

Where Salary > All (Select Salary

From employee

Where Dno=5);

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Group by Clause

Query: Number of male & female employee in the Organization/ company? // Gender //

Query: Number of students placed in each company. // Company name//

Query: Number of employees working on each project. // project no//

Query: Number of employees working on each dept. // dno//

Query: Number of employees supervised by each manager. // super_ssn//

Query: Number of male & female employees working in each dept. // little difficult//

Sql> Select *

From Employee

Group by Gender;

// the sub tables/ tuples group will created based on distinct values in ‘Gender’ domain//

O/p: ???

Sql> Select Count (*)

From Employee

Group by Gender;

O/p: ???

Sql> Select Gender, Count (*) as No_of_Employees // result can be renamed, using As //

From Employee

Group by Gender;

Gender No_of_Employees
Female 5
Male 3

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

C
oncepts to be discussed:
 Introduction to Logical Data Model/schema

 Mapping Conceptual Data Modelling Conceptual Data Model

In today’s discussion, we will introduce the Logical Data Model of the database.

A conceptual data model is good to represent the High-level modelling of the Data
requirements, while Logical data model is a System-level representation of these
requirements.

The logical schema represents the entities & other elements in a way that will be created in
the system.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Mapping Conceptual Data Modelling to Logical Data Modelling

Thumb Rule:
 Create a Relational Table,
 For each Entity with located attributes.
 For each Multi-value attribute (with PK of base Entity & multi-value attribute).
 For each instance of M:N relationship ( PKs of both Entities).
 Create Foreign key (FK) attribute in Relational Table,
 For each 1:1 (in either side of Entity, referencing PK of either side entity).
 For each 1:M/M:1 (in the M side entity, referencing PK of 1 side entity).
 For each M:N ( the PK of each entities, referring to the base entity).
For Example:

Conceptual Data Model Logical Data Model

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Course: Database System (CSPC-25) Instructor: Dr. Vikram Singh

Lecture no: 05 Date: 27.08. 2020


Mode (via): Self_note

Concepts to be discussed:
 Data Model, Types: Relational, Hierarchical, Network, Object-oriented , XML, etc
 Introduction to Relational Data Model, Property of Uniqueness, & Role of Constraints

Till now we have discussed about various elementary concepts related to Database.

Today, we will elaborate a new concepts or term ‘Data Model’, which is a set of rules or
properties to implement the ‘Schema’.

I hope you can recall the term ‘Schema’:


The way data at a certain level is represented is referred as ‘Schema’. A Schema simply
controls the whole representation of data at certain place/level.
 ‘Schema’ is a c onceptual term, while ‘Data Model’. It simply means that whatever is
defined under/by a schema will be implemented by Data Model in actual. See the
figure 1.
 In brief, we can say Data Model is the implementation of Schema.

Figure 1. Schema diagram Figure 2. Database State

As we have pointed and discussed that, there are primarily three types of Data (Structured,
Semi-structured and Un-structured). Each type data have different properties, and these
properties make it difficult to be managed by a same data-model.

So, based on the nature & properties of Data, we can select a proper data model.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Course: Database System (CSPC-25) Instructor: Dr. Vikram Singh

# Type of Data-model

 Relational Data Model


 Hierarchical Data Model
 Network Data Model
 Object –oriented Data Model
 XML, etc.

Our focus is on Relational Data Model

So, if we adapt Relational Data model for our data, the data will be organized & stored in
structured way. Here,
 The relational data model will represent the data into Tabular views and there will
be relationship among the each data values with other.
 The relational data model ensures that each row/tuple will uniquely create. This is
also referred as property of Uniqueness.
 The property of Uniqueness is implemented using set of Constraints (Primary key,
NOT Null, Unique, Check, Default).

Any DB system, which is created using relational data model, is referred as Relational
DB(RDB). An DBMS designed to handle thus RDB is called Relational DBMS (RDBMS).

Figure 3: A traditional DBMS vs Relational DBMS (RDBMS)

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 What are the constraints, Type of Constraints
 Process to design a Database: Conceptual model-Logical design - Physical design

Now, it is clear that to create/design a structured database, we will adapt relational Data
model & relational DBMS (RDBMS).

The property of Uniqueness is the most important to be ensured or implemented. A relational


database system uses the Constraints to implement the Uniqueness properties.

Relational Database system constraints are following types:

)i( Primarily Key : values in the attribute will be Unique & Not Null
)i i( Not Null : values in the attribute will be Not Null
)i i i( Unique: values in the attribute will be Unique
)vi( Check : values in the attribute will be restricted to the mentioned values (Male, Female in gender)
)v( Default: values in the attribute will be set as some defined default value
Foreign key: values in the attribute will be restricted to a domain of attributed placed in Master-table
)iv(

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Next, the overall process of Database design will discuss.

You can refer the figure 1, to see the each step.

Figure 1. Process flow of steps involved in Database Design

 How to plan the database (name of the tables, attributes & relationships among the table)
 Example: A database is being constructed to keep track of the teams and games of
a sports league. A team has a number of p layers, not all of whom participate in
each game. It is desired to keep track of the players participating in each game for e
ach team, t he positions they played in that game, and the result of the game.
Design the database for this application, stating any assumptions you make.
Choose your favourite sport (e.g., soccer, baseball, football).

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to Conceptual Modelling of Data Requirements
 Basic elements of Entity-relationship diagram (ERD): Entity, Attributes, Relationship

Now, we will discuss the first step of database design, Conceptual Data Modelling. The
objective of this step is to create the 1st impression of data related requirements and to
provide a detailed idea about all the possible data related details.

Entity-Relationship Diagram
(ERD)

Figure 1. Process flow of steps involved in Database Design

 How to plan the database (name of the tables, attributes & relationships among the table)
 Example: A database is being constructed to keep track of the teams and games of a sports league.
A team has a number of players, not all of whom participate in each game. It is desired to keep t
rack of the players participating in each game for each team, the positions they played in that game,
and the result of the game. Design the database for this application, stating any assumptions you
make. Choose your favourite sport (e.g., soccer, baseball, football).

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Next, we will discuss the fundamental elements of ERD.

 Entity
 Any real-world objects (person, event, etc.)
 Type: Strong Entity, Weak Entity
 Drawn by : Strong & Weak Entity
 Attribute
 Properties of real-world objects ( though which you can identify the entity)
 Type: Single valued, Multi-valued, & Derived
 Drawn by : Single value , Multi-valued , Derived value
 Relationship
 Participation of objects of both entities.
 Type: 1:1, 1:M, M:1, & M:N
 Drawn by :

#Example of 1:1 relationship # Example of 1:M or M:1 relationship

#Example of M:N relationship #Example of Recursive relationship

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 How to identify the elements of ERD: Entities, Attributes & Relationship(Name & ratio)
 How to draw an ERD for given Scenario or real-world requirement

Today’s lecture, we will demonstrate that how you can identify the various elements for
conceptual data modelling and further model into an ERD, of a given scenario and
requirements.

Q: Why conceptual model or visual modelling is a better approach to be adapted in DB


Design?

For Example (Scenario/ data requirements-01):

The COMPANY database keeps track of a company’s employees, departments, and p


rojects. Suppose that after the requirements collection and analysis phase, the d
atabase designers provide the following description of the miniworld—the part of the
company that will be represented in the database.
 The company is organized into departments. Each department has a unique
name, a unique number, and a particular employee who manages the
department. We keep track of the start date when that employee began
managing the department. A department may have several locations.
 A department controls a number of projects, each of which has a unique name,
a unique number, and a single location.
 We store each employee’s name, Social Security number, address, salary, sex
(gender), and birth date. An employee is assigned to one department, but may
work on several projects, which are not necessarily controlled by the same
department. We keep track of the current number of hours per week that an
employee works on each project. We also keep track of the direct supervisor of e
ach employee (who is another employee).
 We want to keep track of the dependents of each employee for insurance
purposes. We keep each dependent’s r first name, sex, birth date, and
elationship to the employee.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

For example (Scenario/Requirement_01):

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

“A database is being constructed to keep track of the teams and games


of a sports league. A team has a number of players, not all of whom
game. It is desired to keep track of the players
participate in each

participating in each game for each team, the positions they (players) p
layed in that game, and the result of the game”.

(1) Design the database for this application, stating any assumptions you make. Choose
your favourite sport (e.g., soccer, baseball, football).
(2) Examine the following three ERD and find out which is best suited for the given
requirement?

ERD-01

ERD-02

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

ERD-03

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Role of Structural Constraints on ER diagram

 Participation : Total & Partial and Min & Max

In continuation with previous lecture (Lect-08), today we will adding few another details into
ER diagram.

We have taken COMPANY database

Following ER has details like Entities, Attribute, Relationship and Relationship Ratio
(cardinality ratio). One thing is interesting that, we have added Participation constraints (
Total participation , indicate with double lined and Partial participation with simple line). For
example:

Department
entity is Partially
participation,
while Project
entity is Totally
participating in
Relationship
Controls

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Similarly, we could described the relationship ratio (cardinality ration) with more precision
using another structural constraints, named as ‘Min, Max’ constraints

We could see the description of Min.,Max constraints on the following ERD (is same
Participation of EMP entity Participation of Department
requirements of COMPANY DB). object’s in relationship (1, 1). entity object’s in relationship,
Means: A Employee can (4, N). Means: A department
work_for minimum 01 & can have minimum 04 &
maximum 01 maximum N employees.

For Example (Scenari/ Requirment-3)

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Consider the ER diagram shown below for part of a BANK database. Each bank
can have multiple branches, and each branch can have multiple accounts and loans.
(a).List the names of all relationship types, and specify the (min, max) constraint
on each participation of an entity type in a relationship type. Justify your choices.
(b). Suppose t hat every customer must have at least one account but is restricted t
o at most two loans at a time, and that a bank branch cannot have more than 1
,000 loans. How does this show up on the (min, max) constraints?

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

Concepts to be discussed:
 Introduction to Enhanced ERD (EERD)

 Concept : Specialization & Generalization

In today’s discussion, we will cover the important extension of ER diagram. The concepts of
Specialization and Generalization on ER diagram.

With these two features are important, we can create:


 More accurate database schemas that reflect the d ata properties and c onstraints more
precisely.
 This was particularly important for newer applications of database technology, such
as databases for engineering design and manufacturing (CAD/CAM),
telecommunications, complex software systems, and Geographic Information Systems
(GIS), among many other applications semantic data models.

We can take the definition of each, as


Specialization: ‘a process of creating the sub-classes’
Generalization: ‘a process of creating the super-class’

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Specialization
The objective is to derived the sub-class/s (based on an attribute/condition) of an entity.

Constraints: Completeness constraint:


Dis-jointness (d) & Total & Partial
Overlapping (o)

 An Overlapping (o) Specialization

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

For Example:

Shared Sub-class

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 Generalization
oves upwards the attributes of
Objective is to derive the super-class. Here the inheritance m
participant’s entities.

1
Computer Engineering Dept, NIT Kurukshetra
ACY: 2020-21 (Odd Sem.)

 An Example: EER diagram for University Database Schema

You might also like