Unit 3 - Database Management System: Tables/Relations Are Saved in
Unit 3 - Database Management System: Tables/Relations Are Saved in
Unit 3 - Database Management System: Tables/Relations Are Saved in
Cardinality -
The cardinality of a
Degree - The degree of a relation is the number of
relation is the number of tuples/records in a
attributes in its header, or, in relation/ table.
other words, the number of
columns.
79
KEYS
Primary Candidate
Key Key
Alternate Foreign
• All the candidate keys Key Key • A * A field (or
except primary key is collection of
are called alternate or fields) in one
secondary key table that refers to the
PRIMARY KEY in
another table
80
CHARACTER
char, varchar2
NUMERIC
DATE
int, decimal,
date, time,
numeric, float,
datetime SUM()
real
SQL AVG()
DATATYPES
SQL
AGGREGATE
FUNCTIONS
COUNT()
MIN()
MAX()
81
enables you to specify used to return
conditions that filter which SELECT only distinct (different)
group results appear in the values.from a table
results. Used with group
by clause. having DISTINCT
Used to group
rows that have
the same values
sorts the records used to specify
in ascending order
by default. Use
SQL a condition while
fetching the data
DESC for commands from a table.
order by descending order. WHERE
used to compare
a value to similar
values using allows you to
null/ is wildcard
IN specify multiple
null operators. values in a
WHERE clause
used to check
for null values
like between
selects values within a
given range inclusive of
both values.
82
JOINS
E.g. E.g.
select * from Table1, Table2 where select * from Table1 natural join table2;
Table1.col1=Table2.col2;
-------------------o-X-o-------------------
83
warning packet) that it is transmitting for so much time before actually sending the data. The
other device refrains from transmitting data for the specified time limit. This means data
packets will never collide.
Ans 24. There are many methods of checking or detecting simplest ones are:
(i) Single dimensional parity checking
(ii) Two dimensional parity checking
(iii) Checksums
Ans 25. The errors that may occur in the data transmitted over networks, can be one or more of
following types:
(i) Single-bit error. This type of error occurs if only one bit of the transmitted data got changed
from 1 to 0 or from 0 to 1.
(ii) Multiple-bit error. This type of error occurs if two or more nonconsecutive bits in data got
changed from 0 to 1 or from 1 to 0.
(iii) Burst Error. This type of error occurs if two or more consecutive bits in data got changed
from 0 to 1 or from 1 to 0
Ans 26. Parity checking is a method of error detection that can checkk1 or 2 bit errors (but not all dr
these) In parity checks, a parity bit is added to the end of a string of binary code to indicate
whether the number of bits in the string with the value 1 is even or odd.
Ans 27. The sender, which is the checksum generator, follows these steps:
(a) The units are divided into k sections each of n bits, taking 1's complement to get the sum.
(b) All sections are added together
(c) The sum is complemented and become the checksum.
(d) The checksum is sent with the data.
Ans 28. The acknowledgement signal or the ACK signal is a control code, which is sent by the receiving
computer to indicate that the data has been received without error and that the next part of the
transmission may be sent.
Ans 29. Routing is the process of selecting paths to move information across networks When a data
packet reaches a router, the router selects the best route to the destination network from js
routing table and forwards the data packet to the neighbouring router as per the selected best
path. This way each router keeps passing the data packet(s) to its neighbouring router on best
route the destination and finally the data packet reaches its destination.
Q3. Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (viii).
Table:GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
(i) To display the name of all Games with their Gcodes.
(ii) To display details of those games which are having PrizeMoney more than 7000.
(iii) To display the content of the GAMES table in ascending order of ScheduleDate.
(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 2 or 4)
(v) SELECT COUNT(DISTINCT Number) FROM GAMES;
(vi) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(vii) SELECT SUM(PrizeMoney) FROM GAMES;
(viii) SELECT DISTINCT Gcode FROM PLAYER;
Q4. Consider the following tables FACULTY and COURSES. Write SQL commands for the
statements (i) to (iv) and give outputs for SQL queries (v) to (vi).
FACULTY
F_ID Fname Lname Hire_date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
COURSES
C_ID F_ID Cname Fees
C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000
i) To display details of those Faculties whose salary is greater than 12000.
ii) To display the details of courses whose fees is in the range of 15000 to 50000 (both
values included).
118
iii) To display details of those courses which are taught by ‘Sulekha’ in descending order
of courses ?
iv) Select COUNT(DISTINCT F_ID) from COURSES;
v) Select Fname,Cname from FACULTY,COURSE where COURSE.F_ID=FACULTY.F.ID;
Q-5 Write SQL Command for (a) to (e) and output of (f)
TABLE : GRADUATE
S.NO NAME STIPEND SUBJECT AVERAGE DIV
1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP Sc 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II
a. List the names of those students who have obtained DIV I sorted by NAME.
b. Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a
year assuming that the STIPEND is paid every month.
c. To count the number of students who are either PHYSICS or COMPUTER SC graduates.
d. To insert a new row in the GRADUATE table: 11,”KAJOL”, 300, “computer sc”, 75, 1
e. Give the output of following sql statement based on table GRADUATE:
(i) Select MIN(AVERAGE) from GRADUATE where SUBJECT=”PHYSICS”;
(ii) Select SUM(STIPEND) from GRADUATE WHERE div=2;
(iii) Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
(iv) Select COUNT(distinct SUBJECT) from GRADUATE;
Q-6 Consider the following tables Sender and Recipient. Write SQL commands for the
statements (i) to (iv) and give the outputs for SQL queries (v) to (viii).
Sender
SenderID SenderName SenderAddress Sendercity
ND01 R Jain 2, ABC Appls New Delhi
MU02 H Sinha 12 Newtown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K,SDA New Delhi
Recipients
RecID SenderID RecName RecAddress recCity
KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A-Vihar New Delhi
MU19 ND01 H Singh 2A, Andheri East Mumbai
MU32 MU15 P K Swamy B5, C S Terminals Mumbai
ND48 ND50 S Tripathi 13, BI D Mayur Vihar New delhi
a. To display the names of all Senders from Mumbai
b. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every Recipient
c. To display Recipient details in ascending order of RecName
d. To display number of Recipients from each city
e. SELECT DISTINCT SenderCity from Sender;
f. SELECT A.SenderName, B.RecName From Sender A, Recipient B
Where A.SenderID = B.SenderID AND B.RecCity =’Mumbai’;
g. SELECT RecName, RecAddress From Recipient
Where RecCity NOT IN (‘Mumbai’, ‘Kolkata’) ;
119
h. SELECT RecID, RecName FROM Recipent
Where SenderID=’MU02’ or SenderID=’ND50’;
Q-7 Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which
are based on the tables.
Table : VEHICLE
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
Note : PERKM is Freight Charges per kilometer , VTYPE is Vehicle Type
Table : TRAVEL
NO NAME TDATE KM CODE NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
• NO is Traveller Number
• KM is Kilometer travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Travel Date
(i) To display NO, NAME, TDATE from the table TRAVEL in descending order of NO.
(ii) To display the NAME of all the travellers from the table TRAVEL who are travelling by
vehicle with code 101 or 102.
(iii) To display the NO and NAME of those travellers from the table TRAVEL who travelled
between ‘2015-12-31’ and ‘2015-04-01’.
(iv) To display all the details from table TRAVEL for the travellers, who have travelled
distance more than 100 KM in ascending order of NOP.
(v) SELECT COUNT (*), CODE FROM TRAVEL GROUP BY CODE HAVING COUNT(*)>1;
(vi) SELECT DISTINCT CODE FROM TRAVEL;
(vii) SELECT A.CODE,NAME,VTYPE FROM TRAVEL A, VEHICLE B WHERE A.CODE=B.CODE
AND KM<90;
Q9. Observe the following table and answer the parts (i) and(ii) accordingly
Table:Product
Pno Name Qty PurchaseDate
101 Pen 102 12-12-2011
102 Pencil 201 21-02-2013
103 Eraser 90 09-08-2010
109 Sharpener 90 31-08-2012
113 Clips 900 12-12-2011
(i) Write the names of most appropriate columns, which can be considered as candidate
keys.
(ii) What is the degree and cardinality of the above table?
Q-10 Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to(viii), which
are based on the tables.
TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARG 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 O LEVEL 18000 2018-07-25 105
(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.
(iv) To display number of Trainers from each city.
(v) SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’, ‘MUMBAI’);
(vi) SELECT DISTINCT TID FROM COURSE;
(vii) SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID HAVING
COUNT(*)>1;
(viii) SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE< ‘2018-09-15’;
121
QUESTONS : MORE ON SQL
Answer-1 Define the terms:
I. PRIMARY KEY : It is a key/attribute or a set of attributes that can uniquely identify
tuples within the relation.
II. CANDIDATE KEY : All attributes combinations inside a relation that can serve as
primary key are candidate key as they are candidates for being as a primary
key or a part of it.
III. RELATIONAL ALGEBRA : It is the collections of rules and operations on
relations(tables). The various operations are selection, projection, Cartesian
product, union, set difference and intersection, and joining of relations.
IV. DOMAIN : it is the pool or collection of data from which the actual values appearing in
a given column are drawn.
Answer-2
Ans1. Data Definition Language (DDL): This is a category of SQL commands. All the commands
which are used to create, destroy, or restructure databases and tables come under this category.
Examples of DDL commands are - CREATE, DROP, ALTER.
Data Manipulation Language (DML): This is a category of SQL commands. All the commands
which are used to manipulate data within tables come under this category. Examples of DML
commands are - INSERT, UPDATE, DELETE.
Ans 3: Single Row Function work with a single row at a time. A single row function returns a result for
every row of a quired table
Examples of Single row functions are Sqrt( ), Concat( ), Lcase( ), Upper( ), Day( ), etc.
Ans 4. The CHAR data-type stores fixed length strings such that strings having length smaller than the
field size are padded on the right with spaces before being stored.
The VARCHAR on the other hand supports variable length strings and therefore stores strings
smaller than the field size without modification.
Ans 5: WHERE clause is used to select particular rows that satisfy the condition where having clause is
used in connection with the aggregate function GROUP BY clause.
FOR EXAMPLE- select * from student where marks >80;
Select * from student group by stream having marks>90;
Ans 6: i) 100001 ii)No output
Ans 8. COMMIT command permanently saves the changes made during the transacation execution.
ROLLBACK command undoes the changes made during transaction execution.
Ans9: DISTINCT
Ans 10: curdate() returns the current date whereas date() extracts the date part of a date.
Answer-3
(i) SELECT GameName, Gcode FROM GAMES;
(ii) SELECT * FROM GAMES WHERE PrizeMoney>7000;
(iii) SELECT * FROM GAMES ORDER BY ScheduleDate;
(iv) SELECT SUM(PrizeMoney),Number FROM GAMES GROUP BY Number;
(v) 2
(vi) 19-Mar-2004 12-Dec-2003
(vii) 59000
(viii) 101
103
108
122
Answer-4
(i) Select * from faculty where salary > 12000;
(ii) Select * from Courses.where fees between 15000 and 50000;
(iii) Select * from faculty fac, courses cour where fac.f_id = cour.f_id and fac.fname = 'Sulekha'
order by cname desc;
(iv) 4
(vi) Amit Grid Computing
Rakshit Computer Security
Rashmi Visual Basic
Sulekha Human Biology
Answer-5.
a. SELECT NAME from GRADUATE where DIV = ‘I’ order by NAME;
b. SELECT NAME,STIPEND,SUBJECT, STIPEND*12 from GRADUATE;
c. SELECT SUBJECT,COUNT(*) from GRADUATE group by SUBJECT having SUBJECT=’PHYISCS’ or
SUBJECT=’COMPUTER SC’;
d. INSERT INTO GRADUATE values(11,’KAJOL’,300,’COMPUTER SC’,75,1);
e. (i) 63
(ii) 800
(iii) 475
(iv) 4
Answer-6
a. SELECT sendername from Sender where sendercity=’Mumbai’;
b. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress
from Sender S, Recepient R where S.SenderID=R.SenderID ;
c. SELECT * from Recipent ORDER By RecName;
d. SELECT COUNT( *) from Recipient Group By RecCity;
e) SenderCity
Mumbai
New Delhi
f) A.SenderName B.RecName
R Jain H Singh
S Jha P K Swamy
g) RecName RecAddress
S Mahajan 116, A Vihar
S Tripathi 13, BID, Mayur Vihar
h) RecID RecName
ND08 S Mahajan
ND48 STripathi
Answer-7
i. SELECT NO, NAME, TDATE FROM TRAVEL ORDER BY NO DESC;
ii. SELECT NAME FROM TRAVEL WHERE CODE=‘101’ OR CODE=’102’;
OR
SELECT NAME FROM TRAVEL WHERE CODE IN (101,102);
iii. SELECT NO, NAME from TRAVEL
WHERE TDATE >= ‘20150401’ AND TDATE <= ‘20151231’;
OR
SELECT NO, NAME from TRAVEL
WHERE TDATE BETWEEN ‘20150401’ AND ‘20151231’;
iv. SELECT * FROM TRAVEL WHERE KM > 100 ORDER BY NOP;
iv. SELECT * FROM TRAVEL WHERE KM > 100 ORDER BY NOP;
vi. count(*) code
2 101
2 102
vii. DISTINCT CODE
101
123
102
103
104
105
viii. Code Name Vtype
104 Ahmed Khan Car
105 Raveena Suv
Answer-7
i. SELECT M_Compnay, M_Name, M_Price FROM MobileMaster
ORDER BY M_Mf_Date DESC;
ii. SELECT * FROM MobileMaster WHERE M_Name LIKE “S%‟;
iii. SELECT M_Supplier, M_Qty FROM MobileStock WHERE M_Id <> ‘MB003’;
iv. SELECT M_Company FROM MobileMaster WHERE M_Price
v. M_Id SUM(M_Qty)
MB004 450
MB003 400
MB001 300
MB006 200
vi.
MAX(M_Mf_Date) MIN(M_Mf_Date)
2017-11-20 2010-08-21
vii.
M_Id M_Name M_Qty M_Supplier
MB004 Unite3 450 New_Vision
MB001 Galaxy 300 Classic Mobile Store
viii. 5450
Answer-9
i) Candidate Key: Pno, Name
ii) Degree:4 Cardinality:5
Answer-10
(i) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE;
(ii) SELECT TNAME, CITY FROM TRAINER
WHERE HIREDATE BETWEEN ‘2001-12-01’ AND ‘2001-12-31’;
(iii) SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE
WHERE TRAINER.TID=COURSE.TID AND FEES<=10000;
(iv) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
(v) SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’,’MUMBAI’);
(vi) TID TNAME
103 DEEPTI
106 MANIPRABHA
(vii) DISTINCT TID
101
103
102
104
105
(viii) TID Count(*) Min(Fees)
101 2 12000
(ix) Count(*) sum(Fees)
4 65000
124
QUESTION : PYTHON WITH SQL
Q1. What is MySQLdb?
Q2. What is resultset?
Q3. What is database cursor?
Q4. What is database connectivity?
Q5. Which function do use for executing a SQL query?
Q6. Which package must be imported to create a database connectivity application?
Q7. Differentiate between fetchone() and fetchall()
Q8. How we can import MYSQL database in python?
Q9. Write a small python program to insert a record in the table books with attributes
(title, isbn).
Q.10 Write a small python program to retrieve all record from the table books with attributes
(title ,isbn).
A2. Result set refers to a logical set of records that are fetched from the database by executing a
query.
A3. Database cursor is a special control structure that facilitates the row by row processing of records
in the result set
A4. Database connectivity refers to connection and communication between an application and a
database system.
A7. fetchone() − It fetches the next row of a query result set. A result set is an object that is returned
when a cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from
the result set, then it retrieves the remaining rows from the result set.
A8. Use the mysql.connector.connect() method of MySQL Connector Python with required parameters
to connect MySQL. Use the connection object returned by a connect() method to create a cursor
object to perform Database Operations. The cursor.execute() to execute SQL queries from Python.
125
conn =sqlator.connect(host=”localhost”,user=”root”,passwd=””,database=”test”)
cursor=con.cursor()
query=”select * from query”
cursor.execute(query)
data=cursor.fetchall()
for row in data:
print(row)
conn.close()
1. Intellectual property rights are the rights given to persons over the creations of their minds. They
usually give the creator an exclusive right over the use of his/her creation for a certain period of
time12.
2. Plagiarism is the "wrongful appropriation" and "stealing and publication" of another author's
"language, thoughts, ideas, or expressions" and the representation of them as one's own original
work. Plagiarism is considered academic dishonesty and a breach of journalistic ethics.
3. Open-source software is a type of computer software in which source code is released under a
license in which the copyright holder grants users the rights to study, change, and distribute the
software to anyone and for any purpose. Open-source software may be developed in a collaborative
public manner.
4. Privacy law refers to the laws that deal with the regulation, storing, and using of personally
identifiable information of individuals, which can be collected by governments, public or private
organisations, or other individuals.
Privacy laws are considered within the context of an individual's privacy rights or within
reasonable expectation of privacy.
5. The crime that involves and uses computer devices and Internet, is known as cybercrime.
Cybercrime can be committed against an individual or a group; it can also be committed against
government and private organizations. It may be intended to harm someone's reputation, physical
harm, or even mental harm.
6. Voice phishing, or “vishing”, works the same way as a spear phishing attack (by using
personalized information to leverage trust), but uses a different channel: the telephone. The
126