0% found this document useful (0 votes)
6 views95 pages

Study Material XII CS 2023-24

The document is a study material for Class XII Computer Science under Kendriya Vidyalaya Sangathan for the session 2023-24. It includes a detailed syllabus covering topics such as computational thinking, programming in Python, computer networks, and database management. The document also features contributions from various educators and an index for easy navigation.
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)
6 views95 pages

Study Material XII CS 2023-24

The document is a study material for Class XII Computer Science under Kendriya Vidyalaya Sangathan for the session 2023-24. It includes a detailed syllabus covering topics such as computational thinking, programming in Python, computer networks, and database management. The document also features contributions from various educators and an index for easy navigation.
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/ 95

KENDRIYA VIDYALAYA SANGATHAN

JABALPUR REGION

STUDY MATERIAL
CLASS XII
COMPUTER SCIENCE (083)

SESSION: 2023-24

1
OUR PATRON

Shri. SOMIT SHRIVASTAV


DEPUTY COMMISSIONER

Smt. SAROJ DABAS Shri HEERA LAL


Assistant Commissioner Assistant Commissioner

KENDRIYA VIDYALAYA SANGATHAN


JABALPUR REGION

2
SUBJECT CO-ORDINATOR
Mr. RITESH KUMAR PATEL
PRINCIPAL KV HATTA

PREPARED BY PGT (Computer Science)

Member Member Member


Team Leader
MR. HARIOM PATNHA Mr. SUNIL KUMAR BHELE KV Mr. Sushil Mishra Mr. Ravindra Kumar Upadhyay
PGT CS, KV NKJ KATNI MALANJKHAND KV Dhana KV Chhindwara

REVIEWED BY

Mrs. SUSHMA CHAUDHA Mr. SANDEEP SAHU


PGT CS KV CMM JABALPUR PGT CS KV NARSINGHPUR

3
Index
S.No. Topic Page No.

1. SYLLABUS 1

2. Computational thinking and programming 3

3. Functions Mind Map 4

4. Revision of Python topics covered in Class XI 5

5. Functions in Python 11

6. Exception Handling 15

7. Python File Handling Mind Map 18

8. Python File Handling 19

9. Data structure mind map 22

10. Data-structures 23

11. Computer Networks 32

12. Database Concepts 56

13. Relational Database 63

14. Structured Query Language 65

4
5
SYLLABUS
Unit I: Computational Thinking and Programming – 2
● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable (global
scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a
file using with clause, writing/appending data to a text file using write() and writelines(), reading
from a text file using read(), readline() and readlines(), seek and tell methods, manipulation of data
in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab,
ab+), close a binary file, import pickle module, dump() and load() method, read, write/create,
search, append and update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using writer(),
writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack using list.

Unit II: Computer Networks


● Evolution of networking: introduction to computer networks, evolution of networking
(ARPANET, NSFNET, INTERNET)
● Data communication terminologies: concept of communication, components of data
communication (sender, receiver, message, communication media, protocols), measuring
capacity of communication media (bandwidth, data transfer rate), IP address, switching
techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-
optic cable), Wireless media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI
card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking
topologies (Bus, Star, Tree)

1
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup
Language (XML), domain names, URL, website, web browser, web servers, web hosting

Unit III: Database Management


● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate
key, primary key, alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data Manipulation
Language, data type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary
key), create database, use database, show databases, drop database, show tables, create table,
describe table, alter table (add and remove an attribute, add and remove primary key), drop
table, insert, delete, select, operators (mathematical, relational and logical), aliasing, distinct
clause, where clause, in, between, order by, meaning of null, is null, is not null, like, update
command, delete command, aggregate functions (max, min, avg, sum, count), group by, having
clause,joins: cartesian product on two tables, equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing insert,
update, delete queries using cursor, display data by using connect(), cursor(), execute(),
commit(), fetchone(), fetchall(), rowcount, creating database connectivity applications, use of
%s format specifier or format() to perform queries

2
UNIT–1
COMPUTATIONAL THINKING AND PROGRAMMING-2

3
4
1. Revision of Python topics covered in Class XI
Q. What are keywords?
Ans. i. Python Keywords are some predefined and reserved words in python that have special
meanings.
ii. Keywords are used to define the syntax of the coding.
iii. The keyword cannot be used as an identifier, function, or variable name.
iv. All the keywords in python are written in lowercase except True and False.
Keyword Description
and A logical operator
as To create an alias
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception
occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be
executed no matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
None Represents a null value
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling

Q. Write rules for writing identifiers in Python.


Ans.
i. The identifier is a combination of character digits and underscore and the character
includes letters in lowercase (a-z), letters in uppercase (A-Z), digits (0-9), and an
underscore (_).
ii. An identifier cannot begin with a digit. If an identifier starts with a digit, it will give a
Syntax error.

5
iii. In Python, keywords are the reserved names that are built-in to Python, so a keyword
cannot be used as an identifier - they have a special meaning and we cannot use them
as identifier names.
iv. Special symbols like !, @, #, $, %, etc. are not allowed in identifiers.
v. Python identifiers cannot only contain digits.
vi. Identifier names are case-sensitive.
Valid Identifiers Invalid Identifiers Reason
Project_Report Project Report Space not allowed
Position3 3position Can’t start with digit
_temperature #temperature Special symbol not allowed
RETURN return Keywords not allowed

Q. What will be the value of cats, dogs, hens in the following code?
a, b, c = 5, 4, 2
cats, dogs, hens = b, c, a
Ans. 4 , 2, 5
Explanation: a, b, c are variables. first value assign to a first variable, second value assign
to a second variable and so on..

Q. What will be the output for the following code if input is “*”?
ch = input("Enter separator")
print("a","b","c","d",sep=ch)
Ans. a*b*c*d
Explanation: The ‘sep’ parameter allows you to specify a string that will be used to separate
the items being printed by the print() function.

Q. What is the difference between immutable and mutable types?


Ans. Objects whose value can change are said to be mutable; objects whose value is
unchangeable once they are created are called immutable. Example: string is immutable
and list is mutable.

Q. Identify and write the arithmetic, relational and logical operators in the following statement
print(10+15 > 5 + 15 and 100%3!=0)
Ans. Arithmetic Operators +, %
Relational Operators >, !=
Logical Operator ‘and’

Q. Write output of the following python code.


if False:
print("Good")
elif False:
print("Very Good")
elif True:
print("Excellent")
else:
print("Outstanding")
Ans. Excellent
Explanation: If the code in the ‘if’ block is False, it will move to the ‘elif’ block. If that is True ,
then the rest of the blocks are ignored. If it is False, Python will move to other ‘elif’ blocks if
there are any present. Finally, if all of the conditions are False, then and only then the code in
the ‘else’ block will run.
6
Q. Write output of the following python code.
start , stop, step = 5, 50, 10
for x in range(start, stop, step):
print(x, end=' ')
Ans. 5 15 25 35 45
Explanation: start value is always the part of the range. The stop value is never part of the
range. The step shows the difference between two consecutive values in the range.
The ‘end’ parameter in the print function is used to add any string at the end of the output of
the print statement in python. By default, the print function ends with a newline. Passing the
whitespace to the end parameter (end=' ') indicates that the end character has to be identified
by whitespace and not a newline.

Q. Write syntax of while loop in python.


Ans. A while loop will run a piece of code while a condition is True. It will keep executing the
desired set of code statements until that condition is no longer True.
The general syntax of a while loop in Python looks like this:
while condition:
execute this code in the loop's body

Q. Find and write the output of the following python code


text = "AQBAUPAW"
for letter in text:
if letter == 'A':
continue
print(letter*4)
Ans. QQQQ
BBBB
UUUU
PPPP
WWWW
Explanation: ‘for’ loop iterates string one character at a time.
iterate over a string means accessing each of its characters of a string one by one.
Relational operator ‘==’ applies to string also. "a" == "a" will give ‘True’
The ‘continue’ statement rejects all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
The * operator also works on strings. It performs repetition. For example, 'Moon'*3 is
'MoonMoonMoon'.

Q. Write output of the following code


print('abcd1234'.islower())
print('1234ABCD'.isupper())
print('45678'.isdigit())
print('pqrs1234'.isalnum())
print('careful'.isalpha())

Ans. True
True
True
True
7
True
Explanation: islower() returns True if all alphabets in string are in lower case
isupper() returns True if all alphabets in string are in upper case
isdigit() returns True if all characters in string are digits
isalnum() returns True if all characters are either alphabet or digit
isalpha() returns True if all characters in string are alphabets

Q. Write output of the following statement


print(3-2**2**3+99/11)
Ans. -244.0
Explanation: 3-4**3+9.0
3-256+9.0
-244.0
In Python, the double-star operator (**) is used for exponentiation, where one number is
raised to the power of another.

Q. What is list in python?


Ans. Lists are used to store multiple items in a single variable. Lists are created using square
brackets:
w = ['car', 'bus', 'truck', 'jeep']
lists are ordered and each item in a list is associated with a number. The number is known
as a list index.
The index of the first element is 0, second element is 1 and so on.
List items car bus truck jeep
Index -> 0 1 2 3

Q. Write output
L1 = [111, 222, 333]
L2 = [500, 600, 700]
L3 = L1 + L2
print(L3)

Ans. [111, 222, 333, 500, 600, 700]


Explanation: ‘+’ operator concatenates two lists.

Q. Write output
List1 = ["One","Two","Three"]
print(List1*3)
Ans. ['One', 'Two', 'Three', 'One', 'Two', 'Three', 'One', 'Two', 'Three']
Explanation: When * appears between a list and an integer, the expression will be evaluated
as a new list that consists of several copies of the original list concatenated together. The
number of copies is set by the integer.

Q. Write list methods and its function


List Methods in Python
S.no Method Description
1 append() Used for appending and adding elements to the end of the List.
2 copy() It returns a shallow copy of a list
3 clear() This method is used for removing all items from the list.
4 count() These methods count the elements
5 extend() Adds each element of the iterable to the end of the List
8
6 index() Returns the lowest index where the element appears.
7 insert() Inserts a given element at a given index in a list.
8 pop() Removes and returns the last value from the List or the given index
value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
11 sort() Sort a List in ascending, descending, or user-defined order
12 min() Calculates the minimum of all the elements of the List
13 max() Calculates the maximum of all the elements of the List

Q. Explain built in methods you can use in dictionary.


Ans.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Q. Create a dictionary where int are keys and str are values.
Ans. d = {1:'Sun',2;'Eyes',3:'angles',4:'sides',5:'brothers'}
Explanation: dictionary is used to store data in the form of a {key: value} pair.
Q. Find and write the output of the following python code.
dev = {1:'brain',2:'hands',3:'ideas'}
dev[4]='stars'
print(dev)
del dev[2]
print(dev)
Ans. {1: 'brain', 2: 'hands', 3: 'ideas', 4: 'stars'}
{1: 'brain', 3: 'ideas', 4: 'stars'}
Explanation: Adding an item to the dictionary is done by using a new index key and
assigning a value to it. The del keyword removes the item with the specified
key name:

Q. What will be the output of the following python program?


k = [ 2, 3, 4, 5 ]
m = ( 4, 5, 6 )
p = {1:2,2:3}
print(len(k) + len(m) + len(p))
Choose the correct option a) 13 b) 11 c) 9 d) 7
Ans. (c) 9

9
Explanation: len() is a built-in function of Python that returns the total number of items in a
list, array, tuple, dictionary, etc. So 4+3+2 gives 9

Q. Write output of the following python statements


a = max( [ 199, 299, 499, 399 ] )
b = min( [499, 199, 299, 399] )
c = sum( [a,b] )
print(a, b, c)
Ans. 499 199 698
Explanation: min() gives smallest element in the list
max() gives largest element in the list
sum() gives total of all elements in the list
therefore a = 499, b = 199, c = 499+199 = 698

Q. Write output of the following python code


para = "First Run Second Rest"
para2 = " "
for i in range(len(para)):
if para[i].isupper():
para2 = para2 + para[i]
elif para[i].isspace():
para2 = para2 + "#"
else:
pass
print(para2)
print(para.split()[1],para.split()[3])

Ans. F#R#S#R
Run Rest
Explanation: The split() function in Python is a built-in string method that is used to split a
string into a list of substrings based on a specified delimiter. The function takes the delimiter
as an argument and returns a list of substrings obtained by splitting the original string
wherever the delimiter is found. if delimiter is not provided then any white space is a
separator.
For example
para = "First Run Second Rest"
L = para.split()
print(L)
['First', 'Run', 'Second', 'Rest']

Choose the correct option


1. Which of the following is a Python tuple?
a) [11, 22, 33] b) (11, 22, 33) c) {11, 22, 33} d) {11:[22.33]}
Answer: b
Explanation: Tuples are represented with round brackets.

2. Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t [ 3 ]) b) t [ 3 ] = 45
c) print(max( t )) d) print(len( t ))
Answer: b
Explanation: Values cannot be modified in the case of tuple, that is, tuple is immutable.
10
3. What will be the output of the following Python code?
d = {"john":40, "peter":45}
d["john"]
a) 40 b) 45 c) “john” d) “peter”
Answer: a
Explanation: Values for key ‘john’ is 40 in dictionary

4. When will the else part of try-except-else be executed?


a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block
Answer: c
Explanation: The else part is executed when no exception occurs.

Q. What will be the output of the following Python code?

x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)

Ans. x is 50
Changed global x to 2
Value of x is 2

2. Functions in Python
Q. What is function in a program? What are its advantages?
Ans. Function is used to perform a specific task. Function is a block of code, it executes when
called in a program. When a program is divided into number of functions, it is easy to manage.
Program becomes more readable. It is easy to understand the program. Function can be
called in any part of the program. Function is reusable.

Q. Explain how to create a user defined function in Python?


Ans. To create a function, we write def keyword followed by the name of a function with arguments
or parameters inside parentheses. There is a colon(:) at the end of the def line to start a block
of code.
Example
def ShowMessage(m):
print(m)

Q. How can we call a function in our program?


Ans. To call a function, we simply write the name of function followed by parentheses with
arguments.
Example:

11
ShowMessage("Hello")

Q. What happened when you call a function?


Ans. The code or statements written inside a function executes when we call a function in our
program. A value can also be returned by a function if there is a return statement inside a
function.

Q. Create a user defined function which returns sum of two numbers passed as arguments.
Ans. def SumTwoNum(a, b):
return a + b

Q. What do you mean by argument in a function?


Ans. An argument is a variable, value or object passed to a function or method as input. For
example in the following function call:
SumTwoNum(25, 80)
25 and 80 are arguments in a function.

Q. What are positional arguments?


Ans. Positional arguments are arguments that need to be included in the proper position or order.
The order in which you pass these arguments matters, because the function or method will
use the arguments in the order that are received.
For example
def GetDiscount(name, fee):
fee = fee - 500
print(name,' your fee ',fee)
Now when you call GetDiscount function you need to pass arguments in the correct order as
expected otherwise it may not work properly.
For example
If you call like
GetDiscount(15000, "Meena")
By changing the position or in case you forgot the order of the position then the values can
be used at the wrong places as we can see in the above example 15000 assigned to name
and “Meena” assigned to fee.
It will show an error TypeError: unsupported operand type(s) for -: 'str' and 'int'

Q. Explain keyword arguments in a function.


Ans. Keyword arguments means you can also send arguments with the key = value syntax. This
way the order of the arguments does not matter. In keyword arguments, arguments are
assigned based on the name of arguments.

for example

def BodyMI(height, weight, age):


print("Height ", height)
print("Weight ", weight)
print("Age is ", age)

#function calling
BodyMI(age = 40, weight = 65, height = 5.6)
#order of argument doesn’t matter

12
Output
Height 5.6
Weight 65
Age is 40

Q. Write down the difference between positional arguments and keyword arguments.
Ans.
Keyword argument Positional argument
Parameter names are used to pass the Arguments are passed in the order of
argument during the function call. parameters. The order defined in the
function declaration
Order of parameter names can be Order of values cannot be changed to avoid
changed to pass the arguments. unexpected output
Syntax Syntax
FunctionName(paramName = value,…) FunctionName(value1, value2, value3…)

Q. What do you mean by default arguments in a function?

Ans. Default values indicate that the function argument will take that value if no argument value is
passed during the function call. The default value is assigned by using the assignment (=)
operator of the form keywordname = value.

When you call a function and pass an argument to the parameter that has a default value,
the function will use that argument instead of the default value.
However, if you don’t pass the argument, the function will use the default value.
example
def NewAdmission(regno,sec='A',category='V'):
print("Admitted")
print("Registration No",regno)
print("Section",sec)
print("Category",category)
print("------------------------------")

NewAdmission(1999) #function call 1


NewAdmission(2000,'B','III') #function call 2

In above program, function call 1 has only one argument so python uses default values
(sec='A',category='V') for other two arguments and in another case of function call 2 ,
values for all three parameters are provided so the program uses that value instead of the
default values.
Therefore the output is
Admitted
Registration No 1999
Section A
Category V
------------------------------
Admitted
Registration No 2000
Section B
Category III
------------------------------

Q. What is the purpose of ‘return’ keyword in python function? Explain.


Ans. The Python return statement is used to return a value from a function. A return statement
includes the return keyword and the value that will be returned after that.

13
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed.

def Grace(marks):
return marks + 5
print(“End”) #this statement will not execute

#calling function
K = Grace(30)

Grace() will return a value which is assigned to the variable ‘K’. value in ‘K’ is 35

Q. What is the difference between global variable and local variable?


Ans. Python Local Variables
Local variables in Python are those which are initialized inside a function and belong only to
that particular function. It cannot be accessed anywhere outside the function.
def function2():
a = 10 #local variable

function2()
print(a)

NameError: name 'a' is not defined

Python Global Variables


Global variables are defined outside any function and accessible throughout the program, i.e., inside
and outside of every function.

def function2():
print("inside function ", p)

p = 100
function2()
print("outside function ",p)

output
inside function 100
outside function 100

The variable ‘p’ is defined as the global variable and is used both inside the function as well as
outside the function.

Difference b/w Local Variable Vs. Global Variables


Comparision Basis Global Variable Local Variable
Definition declared outside the functions declared within the functions
They are created the They are created when the function
execution of the program starts its execution and are lost
Lifetime
begins and are lost when the when the function ends
program is ended

14
Can be access throughout the Can access only inside the function
Scope
code
Once the value changes it is once changed the variable don’t
Value reflected throughout the code affect other functions of the
program

Q. What is the purpose of global keyword in python?


Ans. In Python, the global keyword is used to declare that a variable inside a function is referring
to a global variable defined outside the function rather than creating a new variable with the
same name as the global variable inside the function. This allows the function to modify the
value of the global variable instead of creating a new local variable with the same name. The
global keyword is used to access and modify global variables from within a function.

subject = "optional" #global scope

def mycourse():
subject = subject + " computer"
print(subject)

mycourse()

Error:

An error is obtained as Python treats “subject” as a local variable, and we have not defined any local
variable “subject” inside the function mycourse(). To solve this error, we use the global keyword.

subject = "optional" #global scope

def mycourse():
global subject
subject = subject + " computer"
print("Inside function",subject)

mycourse()
print("Outside function",subject)

output
Inside function optional computer
Outside function optional computer

In Python, the global keyword is used to indicate that a variable declared inside a function should
be treated as a global variable, rather than a local variable. This means that the variable can be
accessed and modified both inside and outside the function.

3. Exception Handling

Q. What is an exception?
Ans. An exception is an error which happens at the time of execution of a program. We know that
exceptions abnormally terminate the execution of a program. An object in Python that
describes an error is called an exception.
Common Examples of Exception
15
 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a nonexistent index of a sequence

Q. How exception is handled in python?


Ans. Exception handling in Python is achieved using the try and except blocks. The try block is
used to enclose the code that may raise an exception, while the except block is used to
handle the exception that may occur. If an exception is raised in the try block, the program
jumps to the except block to handle it, instead of halting the program altogether.

Syntax:

try :
#statements in try block
except :
#executed when error in try block

example
try:
a=5
b='0'
print(a+b)
except TypeError:
print('TypeError Occurred')
except:
print('Some error occurred.')
print ("Out of try except blocks")

Q. Give some examples of built-in exceptions in python.


Ans.
Exception Description Example
NameError Raised when a name doesn't
exist among either local or print(x)
global variables:
TypeError Raised when an operation is
run on an inapplicable data print(1+'1')
type:
ValueError Raised when an operation or
print(int('a'))
function takes in an invalid
value of an argument:
IndexError Raised when an index print('dog'[3])
doesn't exist in an iterable:
ZeroDivisionError Raised at attempt to divide a
print(1/0)
number by zero:
KeyError Raised when the key is animals = {'cow': 1, 'goat': 2}
absent in the dictionary: print(animals['rabbit'])

Q. How try and except works in python? Explain.

16
Ans. The ‘try’ statement is used to run an error-prone piece of code and must always be followed
by the ‘except’ statement. If no exception is raised as a result of the ‘try’ block execution, the
‘except’ block is skipped and the program just runs as expected. In the opposite case, if an
exception is thrown, the execution of the ‘try’ block is immediately stopped, and the program
handles the raised exception by running the alternative code determined in the ‘except’ block.
After that, the Python script continues working and executes the rest of the code.
Example
try:
print(message)
except:
print("Variable not declared")
print("take care")
output
Variable not declared
take care

We can explicitly mention the type of exception that we need to catch and handle right after the
‘except’ command:
try:
print(message)
except NameError:
print("Variable not declared")
print("take care")
Q. What is ‘finally’ in python?
Ans. In Python, the 'finally' keyword is used in the context of exception handling, specifically with
try-except blocks. The 'finally' block contains code that will always be executed, regardless
of whether an exception occurs or not within the “try” block.

try:
x = int(input("Enter number "))
print(2*x)
except ValueError:
print("This is not a number ")
finally:
print("All the best") #Always execute

output
Enter number abc
This is not a number
All the best

17
4. PYTHON FILE HANDLING

18
4. PYTHON FILE HANDLING
Introduction to files:
File: - A file is a collection of related data stored in computer storage for future data retrieval.
Stream: - It refers to a sequence of bytes. File handling refers to reading and writing contents from a file.
Data Files: Data files can be stored in three ways: 1. Text Files 2. Binary Files 3. CSV Files
DIFFERENCE BETWEEN TEXT FILE, BINARY FILE and CSV files
Text Files Binary Files CSV(comma separated values) Files
Stores information in ASCII CSV format is a plain text format where
Stores information in binary format
characters. values separated by commas.
Each line of text is terminated with a
No delimiters are used for a line. No CSV is a format for saving tabular
special character known as EOL
translation occurs in it information into a delimited text file
(End of Line),

Slower than binary files. Binary files are faster Importing CSV files can be much faster

 Relative & absolute paths- The files are kept in directory which is also known as folders. Every running program
has a current directory. Which is generally a default directory, python always see the default directory first.
 The absolute path (full path) of an entity contains the complete information (from the root to the ending) needed
to locate it. it always includes the root directory as a starting point.
The absolute path to the xiics file is: C:\KVS\XII\Science\xiics.txt
 A relative path- It describes the location of a file or folder without starting from the root of the file system. The
relative path of xiics.txt in parent folder is
“..\xiics.txt”
 Code to know current working directory >>> import os
>>> cwd=os.getcwd() # getcwd() can be used to identify the
>>> print(cwd) # current working directory
Text Files- A text file is simply a sequence of ASCII or Unicode characters.
Opening and Closing Files:
 To perform file operation, it must be opened first then after reading, writing, editing operation can be performed.
 Closing a file releases valuable system resource. In case we forgot to close the file,
 Python automatically close the file when program ends or file object is no longer referenced in the program
Syntax: file_objectname= open (filename, mode) file-objectname.close( )
Example: f = open("XIICS") f.close()
The code above is the same as: f = open("XIICS", "rt") Where "r" for read mode, and "t" for text are the default values,
you do not need to specify them.
File modes
Text File Binary File Description
r rb Read - Default value. Opens a file for reading, error if the file does not exist.
w wb Write - Opens a file for writing, creates the file if it does not exist
a ab append - Opens a file for appending, creates the file if it does not exist
r+ rb+ Read and Write-File must exist, otherwise error is raised.
w+ wb+ Read and Write-File is created if does not exist.
a+ ab+ Read and write-Append new data
Writing/appending data to a text file- There are 2 types of functions to write the data to a file.
 write(): - It returns the number of characters being written on single execution of the write() method.
>>>file.write("Hello Python")
12 # No of characters
 writelines (): This method is used to write multiple strings or object to a file. It does not return the number of characters
written in the file.
>>>file.writelines(lines) # lines = ["Hello everyone\n", "Writingmultiline strings\n", "This is third line"]
Example: Open the file "XIICS" and append content to the file:
file= open("XIICS", "a") # if file is open with “w” mode then content will be overwrite
file.write("Welcome to the world of Programmers")
Reading from a text file
The read() method- Read a specified number of bytes of data from a data file. If no argument or a negative number is
specified in read(), the entire file content is read.
>>>file.read(5) 'Hello'
The readline([n]) method- Read one complete line from a file. It can also be used to read a specified number (n) of
bytes of data from a file but maximum up to the newline character (\n).If no argument or a negative number is specified,
it reads a complete line and returns string.
19
>>> myobject.readline(10) 'Hello ever'

The readlines() method- Reads all the lines and returns the lines along with newline as a list of strings.
>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']

SOME IMPORTANT PROGRAMS RELATED TO TEXT FILES

#Count the number of #Count the number of words in a file #Count number of
characters from a file. lines in a text file
FILE=open("D:\\python programs\\XIICS",'r')
FILE=open("XIICS",'r') FILE=open("XIICS",'r')
str=FILE.read()
str=FILE.read() str=FILE.readlines()
L=str.split()
L=str.split() line=0
words=0
Chars=0 for i in str:
for i in L:
for i in L: line=line+1
words+=1
Chars += len(i) print(line)
print(words)
print(Chars) FILE.close()

#Count number of ‘d’ or #Count the number of ‘is’


#To take the details of book from the user
‘D’ in a text file. word in a text file.
and write the record in text file.
F=open("D:\\Pr\XII",'r') file=open("D:\\programs\\Students.txt",'w') FILE=open("CS.txt”,’r’)
n=int (input ("No. of records want to write? :"))
str=F.read() str=FILE.read()
for i in range(n):
count=0 print ("Enter Students’ record:", i+1) L=str.split(); count=0
for i in str: title=input ("Enter the name: ")
for i in L:
price=int (input ("Enter the marks: "))
if i=='d' or i=='D': if i=='is':
record=title+", "+str(price)+'\n'
count=count+1 file.write(record) count=count+1
file.close()
print(count) print(count)

FILE.close()
The seek and tell methods
The tell() method- Returns the current position of the file object in the file. The syntax of using tell() is:
file_object.tell()
The seek() method- Used to jump file object at a particular position in a file. The syntax of seek() is:
file_object.seek(offset [, reference_point])
offset -Number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. It can have any of the following values: 0 (By default)-
beginning of the file 1 - current position of the file 2 - end of file

Binary File- They store data in the binary format (0’s and 1’s). In Binary files there is no delimiter for a line. Pickle
module can be imported to write or read data in a binary file.
The pickle module- It is used for serializing and de-serializing any Python object structure.
 Serialization/pickling is the process of transforming data or an object in memory to a stream of bytes.
 De-serialization/unpickling- where a byte stream is converted back to Python object.
The pickle module provides two methods- dump()for writing onto binary files and load() to read from binary files.

20
Operations on a binary file:

#Write operation #Append operation


import pickle import pickle
data={'Raj':8500,'Ani':5400,'Sahaj':9800} data={'Dj':86,'Kri':95,'Ved':78}
f1=open('emp.dat','wb') f1=open('emp.dat','ab')
pickle.dump(data,f1) pickle.dump(data,f1)
f1.close() f1.close()

#Read operation
#Searching operation
import pickle import pickle
file=open('emp.dat','rb') f1=open('emp.dat','rb')
try: try:
e=pickle.load(file) e=pickle.load(f1)
for x in e: for x in e
if(e[x]>=25000 and [x]<=30000): print(x)
print(x)
except EOFError:
except EOFError:
f1.close()
file.close()

CSV file-CSV (Comma Separated Values) is a file format for data storage which looks like a text
file. The information is organized with one record on each line and each field is separated by comma.
Advantages Disadvantages
 Smaller in size, Easy to generate • No standard way to represent binary data
 Human readable, faster to handle • There is no distinction between text and numeric values

Operations in CSV files -The csv module’s reader and writer objects read and write sequences.
Operations are -
• open / close csv file import csv
file = open ('Filename.csv’, ’mode’)
file.close()
Reading a CSV file import csv
newFile=open('d:\\a.csv','r'):
NFReader = csv.reader(newFile) # Reading is done using reader object
for row in NFReader:
print (row)
newFile.close()
Writing with writerow () and writerows ()
import csv;
Fields = ['Name', 'Dept', 'Salary']
Rows = [['Sunil', 'Prod','29000'],['Manoj', 'Sales', '46000'], ['Vinod', 'Prod','45000'],
['Videh','Sales', '78000'], ['Ranjana', 'IT','35000'], ['Rohit', 'IT', '45000']]
csvfile = open(“Emp.csv”, 'w') # open the CSV file in WRITE mode.
csvwriter = csv.writer(csvfile) # The file object is converted to csv.writer object.
csvwriter.writerow(fields) #write the first row which is nothing but the field names.
csvwriter.writerows(rows) # writerows method to write multiple rows at once.
csvfile.close()

21
5. DATA STRUCTURE MIND MAP

22
Data-structures –The logical or mathematical model of a particular organization of data is called data structure. It is a
way of storing, accessing, manipulating data. Types are-
a) Simple Data Structure b) Compound Data Structure
Stacks
A stack is a linear data structure that provides temporary storage of data in such a way that the element stored last will
be retrieved first. This method is also called LIFO – Last In First Out. It is controlled by two operations: PUSH and POP.
Both the operations take place from Top position

Implementation of Stack – Stack can be implemented in list. The basic operations are-
Creation of Stack – Stack can be created using list with the help of statement
Stack= [ ] # this statement creates an empty stack
Push (Insertion): The append () functions adds the new element at the top of the list. Codes are –
Stack.append(data)
Pop (Deletion): The pop () function removes the last (top) data from the stack. Before removing an element from the
stack it is necessary to check whether the stack is empty (underflow condition) or not. Codes are –
If (Stack= = []):
print (“Stack is Empty, Underflow Condition”)
else:
print(Stack.pop()) # remove and print top most element of the stack
Peep (Traversal): Traversal (accessing) means visiting each item of the stack. Codes are –
for i in range(len(stack)-1, -1, -1):
print (stack[i])
Implementation of Stack: Codes for various operations
def PUSH (): #code to push an item
item = int(input(“\t\t\tEnter an item to push: “))
Stack.append(item)
print(“\t\t\t ITEM”, item,” PUSHESD IN THE STACK”)

def POP (): #code to pop from stack


if (Stack == []):
print (“\t\t\t UNDERFLOW CONDITION – NO ITEM TO POP”)
else:
item = Stack.pop()
print (“\t\t\t ITEM “, item,” POPPED FROM THE STACK”)

def PEEP (): #code to display stack


if (Stack== []):
print (“\t\t\Tempty STACK”)
else:
print (“\t\t\t”,)
for i in range(len(stack)-1,-1,-1):
print(Stack[i], ‘’, end=””)

STANDARD FILE STREAMS: – Standard input Stream sys.stdin


– Standard output Stream sys.stdout
– Standard error Stream sys.stderr

QUESTIONS & ANSWERS


1 Marks Questions –MCQ/Fill in the blanks
1. A CSV file is also known as a ….
(i) Flat File (ii) 3D File (iii) String File (iv) Random File

2. Which of the following mode is used when dealing with non-text files like image or exe files?
(i) Text mode (ii) Binary mode (iii) xls mode (iv) csv mode

3. Which of the following is not a valid mode to open a file?


(i) ab (ii) rw (iii) r+ (iv) w+

4. Which statement is used to change the file position to an offset value from the start?
(i) fp.seek(offset, 0) (ii) fp.seek(offset, 1)
(iii) fp.seek(offset, 2) (iv) None of the above

5. The difference between r+ and w+ modes is expressed as?


(i) No difference

23
(ii) r+ mode opens the file if it exists, while w+ mode also opens the file, but it deletes all the
content present in the file.
(iii) In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the
end for r+
(iv) Depends on the operating system

6. What does CSV stand for?


(i) Cursor Separated Variables (ii) Comma Separated Values
(iii) Cursor Separated Values (iv) Cursor Separated Version

7. Which module is used for working with CSV files in Python?


(i) random (ii) statistics (iii) csv (iv) math

8. Which of the following modes is used for both writing and reading from a binary file?
(i) wb+ (ii) w (iii) wb (iv) w+

9. Which statement is used to retrieve the current position within the file?
(i) fp.seek() (ii) fp.tell() (iii) fp.loc (iv) fp.pos

10. What happens if no arguments are passed to the seek() method?


(i) file position is set to the start of file (ii) file position is set to the end of file
(iii) file position remains unchanged (iv) results in an error

11. Which of the following modes will refer to binary data?


(i) r (ii) w (iii) + (iv) b

12. Every record in a CSV file is stored in reader object in the form of a list using which method?
(i) writer() (ii) append() (iii) reader() (iv) list()
13. In text files, each line of text is terminated, with a special character known as ___________.
(i) EOL ii) EOF iii) EEF iv) All of the above
14. A _________ file is just a file that contains information in the same format in which the information is held in
memory.
(i). Text file (ii) Binary file (iii) Word file (iv) None of the above
15. _________ binary file mode is used to append data in the file using file handling.
(i) ‘ab’ (ii) ‘w’ (iii) ‘a’ (iv) None of the above
16. The input and output devices are implemented as file, also called __________.
(i) Standard streams (ii) Standard Binary (iii) Standard Text (iv) None of the above
17. ________ are the standard streams in file handling.
(i) stdin (standard input) (ii)stdout (standard output)
(iii) stderr (standard error) (iv) All of the above
18. A text file can be opened in ________ file modes.
(i) ‘r’ and ‘w’ (ii) ‘a’ and ‘r+’ (iii) ‘w+’ and ‘a+’ (iv) All of the above
19. .................... method is used for random access of data in a CSV file. Seek()
20. .................... method of pickle module is used to write an object into binary file. Dump()
21. .................... method of pickle module is used to read data from a binary file. Load()
22. .................... statement is given for importing csv module into your program. Import csv
23. To read all the file contents in form of a list, ..................... method is used. Readlines()
24. To write all the file contents, ....................., method may be used. Writelines()
25. To force Python to write the contents of file buffer on to storage file,.... method may be used. Flush()

1 Marks Questions – Descriptive[one line/one word]


Q.1 What is a data file in python?
Ans: A bunch of bytes / data stores on some storage device referred by the filename.

Q.2. What is the difference between “w” and “a” mode?


Ans: “w” mode opens file in write mode but “a” mode opens file in append mode.

Q.3. What does stdin, stdout represent?


Ans: stdin represent standard input device and stdout represent standard output device which are represented as files.

Q.4. What is CSV File?


Ans: A CSV file is a human readable text file where each line has a number of fields, separated by commas or some
other delimiter.

Q.5. Write the full form of CSV


24
Ans: Comma Separated Values

Q.6. In which of the following file modes the existing data of the file will not be lost?
Rb, ab, w, w+b, a+b, wb, wb+, w+, r+
Ans. In file modes rb, ab, a+b and r+, data will not be lost. In file modes w, w+b, wb, wb+ and w+, data will be lost.

Q.7. Ravi intends to position the file pointer to the beginning of a text file. Write Python statement for the same
assuming “F” is the Fileobject.
Ans. F.seek(0)

Q.8. Which method can be used to determine the name of the current working directory?
Ans. Getcwd()

Q.9. Which function is used to write data onto a file.


Ans. Write() and writelines()

Q.10 Which sign is used to denote directory and parent directory in python
Ans Single dot and double dot

3 Marks Questions

Q.1. Write a python code to find the size of the file in bytes, number of lines and number of words.
Ans. # reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size)
f.seek(0)
L=f.readlines( )
word=str.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words’,len(word))
f.close( )

Q.2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])

Q.3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible
by 5 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise display
appropriate error message.
Ans: Code
def PUSH(Arr):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print(“Empty Stack”)
else:
print(s)
Q.4. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of numbers. The function returns
the value deleted from the stack.
Ans: Code
def popStack(st) :
# If stack is empty
if len(st)==0:
print(“Underflow”)
else:
return st.pop()

Q.5. Write a function in Python that counts the number of “Me” or “My” words present in a text file “STORY.TXT”.
Ans: Code
def displayMeMy():

25
num=0
f=open(“story.txt”,”rt”)
N=f.read()
M=N.split()
for x in M:
if x==”Me” or x== “My”:
num=num+1
f.close()
print(“Count of Me/My in file:”,num)

Q.6. Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count
and display the occurance of alphabets A and M (including small cases a and m too).
Ans: Code
def count_A_M():
f=open(“story.txt”,”r”)
A,M=0,0
r=f.read()
for x in r:
if x==”A” or x==”a” :
A=A+1
elif x==”M” or x==”m”:
M=M+1
f.close()
print(“A or a: “,A)
print(“M or m: “,M)

Q.7. Write a function in python to count the number lines in a text file ‘Country.txt’ which is starting with an alphabet
‘W’ or ‘H’.
Ans. Code
def count_W_H():
f = open (“Country.txt”, “r”)
W,H = 0,0
r = f.readlines()

for x in r:
if x[0] == “W” or x[0] == “w”:
W=W+1
elif x[0] == “H” or x[0] == “h”:
H=H+1
f.close()
print (“W or w :”, W,“\nH or h :”, H)

Q.8. Write a user defined function to display the total number of words present in the file.
Ans. Def countwords():
s = open(“Quotes.txt”,”r”)
f = s.read()
z = f.split ()
count = 0
for I in z:
count = count + 1
print (“Total number of words:”, count)
Q.9. Write a function AddCustomer(Customer) in Python to add a new Customer information NAME into the List of
Cstack and display the information.
Ans.
Def AddCustomer(Customer):
Cstake.append(Customer)
If len(Cstack)==0:
print (“Empty Stack”)
else:
print (Cstack)

Q.10. Write a function DeleteCustomer() to delete a Customer information from a list of Cstack. The function delete
the name of customer from the stack.

26
Ans.
Def DeleteCustomer():
if (Cstack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,Cstack.pop())
Q.11. Write a function in Python that counts the number of “He” or “She” words present in a text file “STORY.TXT”.
Ans. Def displayMeMy():
num=0
f=open(“story.txt”,”rt”)
N=f.read()
M=N.split()
for x in M:
if x==”He” or x== “She”:
print(x)
num=num+1
f.close()
print(“Count of He/She in file:”,num)

Q.12. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible
by 7 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise display
appropriate error message.
Ans.
Def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%7==0:
s.append(Arr[x])
if len(s)==0:
print(“Empty Stack”)
else:
print(s)

Q.13. Write a python program to create and read the city.txt file in one go and print the contents on the output screen.
Ans. # Creating file with open() function
f=open(“city.txt”,”w”)
f.write(“My city is very clean city.”)
f.close()

# Reading contents from city.txt file


f=open(“city.txt”,”r”)
data = f.read()
print(data)
f.close()

Q.15. Write a function count_lines() to count and display the total number of lines from the file. Consider above file –
kvs.txt.
Ans. Def count_lines():
f = open(“kvs.txt”)
cnt =0
for lines in f:
cnt+=1
print(“no. of lines:”,cnt)
f.close()

Q.16. Write a function display_oddLines() to display odd number lines from the text file diary.txt.
Ans. Def display_oddLines():
f = open(“diary.txt”)
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()

27
Q.17. Write the file mode that will be used for opening the following files. Also, write the Python statements to open
the following files:
a) a text file “example.txt” in both read and write mode
b) a binary file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
Ans.
a) file = open( “example.txt”, “w+” )
b)file = open(“bfile.dat” , “wb” )
c) file = open ( “try.txt” , “a+” )

Q.18. What is the difference between the following set of statements (a) and (b):
a) P = open(“practice.txt”,”r”)
P.read(10)

b) with open(“practice.txt”, “r”) as P:


x = P.read()

Ans. File object P will read 10 characters in part “a” but won’t print anything; in part “b,” however, it will read every
character in the 28ractice file and save it in the variable “x.”

Q.19. Write the use and syntax for the following methods:
a) open() b) read() c) seek() d) dump()
Ans. File_object=open(file_name, mode)
x=file_object.read()
f.seek(offset, from_what)
pickle.dump(data_object, file_object)

Q.20. 1. Differentiate between:


a) text file and binary file b) readline() and readlines() c) write() and writelines()

Ans –
a) Data files primarily come in two flavours: text files and binary files. Any text editor can open a text file
since it is made up of characters that are human readable. Binary files, on the other hand, contain non-
human readable characters and symbols and need special software to retrieve its information.
b) When called, the readline() function in Python returns a line from the file. The readlines() method will
return every line in a file as a list with each item representing a line in the file.
c) A string is passed as an argument to the write() method, which writes it to a text file. To write several
strings to a file, use the writelines() method. To use the writelines() method, we must supply an iterable
object (such as a list, tuple, etc.) that contains strings.

5 Marks Questions
1. Aditya Vishwakarma of class 12 is writing a program to create a CSV file “user.csv” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to successfully
execute the given task.

Import _____________ # Line 1


def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(‘ user.csv’,’________’) # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()

#csv file reading code


def readCsvFile(): # to read data from CSV file
with open(‘ user.csv’,’r’) as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Chandra”,”sst@tgt”)
addCsvFile(“Sachin”,”har@narmade”)
addCsvFile(“Pankaj”,”frnd@distance”)
readCsvFile() #Line 5

28
(a) Name the module he should import in Line 1. 1
(b) In which mode, Devesh should open the file to add data into the file 1
€ Fill in the blank in Line 3 to read the data from a csv file. 1
(d) Fill in the blank in Line 4 to close the file. 1
€ Write the output he will obtain while executing Line 5. 1
(a) Line 1 : csv
(b) Line 2 : a
€ Line 3 : reader
(d) Line 4 : close()
€ Line 5 : Chandrasst@tgt
Sachinhar@narmade
Pankajfrnd@distance

2. Given a binary file “EMP.dat” has structure (EmpID, EmpName, EmpPay). Write a function in Python countsal()
in Python that would read contents of the file “EMP.dat” and count and display the details of those employee
whose salary is greater than 35000.

Ans. Import pickle def countsal():


f = open (“EMP.dat”, “rb”)
n=0
try:
while True:
rec = pickle.load(f)
if rec[2] > 35000:
print(rec[0], rec[1], rec[2], sep=”\t”)
n=n+1
except:
f.close()
print(‘the number of employee’,n)
3. A binary file “Stu.dat” has structure (rollno, name, marks).
(i) Write a function in Python add_record() to input data for a record and add to Stu.dat.
(ii) Write a function in python Search_record() to search a record from binary file “Stu.dat” on the basis of
roll number.
def Search_record():
Ans. f = open(“Stu.dat”, “rb”)
import pickle
def add_record(): stu_rec = pickle.load(f);
fobj = found = 0
open(“Stu.dat”,”ab”) rno = int(input(“Enter the roll
4. Anamika Vishwakarma of class 12 is writing a program to create
number a CSV file “empdata.csv” with empid, name
to search:”))
rollno
and mobile no and search empid and display the record. try: She has written the following code. As a programmer,
help him to successfully execute the given task. for R in stu_rec:
Import _____ #Line1
fields=[‘empid’,’name’,’mobile_no’]
rows=[[‘101’,’Rohit’,’8982345659’],[‘102’,’Shaurya’,’8974564589’],
[‘103’,’Deep’,’8753695421’],[‘104’,’Prerna’,’9889984567’],
[‘105’,’Lakshya’,’7698459876’]]
filename=”empdata.csv”
with open(filename,’w’,newline=’’) as f:
csv_w=csv.writer(f,delimiter=’,’)
csv_w.___________ #Line2
csv_w.___________ #Line3

with open(filename,’r’) as f:
csv_r=______________(f,delimiter=’,’) #Line4
ans=’y’
while ans==’y’:
found=False
emplid=(input(“Enter employee id to search=”))
for row in csv_r:
if len(row)!=0:
if _____==emplid: #Line5
print(“Name : “,row[1])
print(“Mobile No : “,row[2])
found=True

29
break
if not found:
print(“Employee id not found”)
ans=input(“Do you want to search more? (y)”)

(a) Name the module he should import in Line 1. 1


(b) Write a code to write the fields (column heading) once from fields list in Line2. 1
€ Write a code to write the rows all at once from rows list in Line3. 1
(d) Fill in the blank in Line4 to read the data from a csv file. 1
€ Fill in the blank to match the employee id entered by the user with the empid of record from a file in
Line5.
Ans: a) csv b) writerow(fields) c) writerows(rows) d) csv.reader e) row[0]

5. Kavy is making a software on “Countries & their Capitals” in which various records are to be stored/retrieved in
CAPITAL.CSV data file. It consists some records(Country & Capital). He has written the following code in
python. As a programmer, you have to help him to successfully execute the program.
Import ___________ # Statement-1
def AddNewRec(Country,Capital): # Fn. To add a new record in CSV
file f=open(“CAPITAL.CSV”,_________) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f.__________ # Statement-3

def ShowRec(): # Fn. To display all records from CSV


with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv.___________(NF) # Statement-4
for rec in NewReader:
print(rec[0],rec[1])

AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”)
ShowRec() # Statement-5

(a) Name the module to be imported in Statement-1.


(b)Write the file mode to be passed to add new record in Statement-2.
€ Fill in the blank in Statement-3 to close the file.
(d)Fill in the blank in Statement-4 to read the data from a csv file.
€ Write the output which will come after executing Statement-5

Ans. (a) csv (b) “a” (c) close() (d) reader € INDIA NEW DELHI CHINA BEIJING

6. Vanshika of class 12 is writing a program to create a CSV file “emp.csv”. She has written the following code to
read the content of file emp.csv and display the employee record whose name begins from “S‟ also show no.
Of employee with first letter “S‟ out of total record. As a programmer, help her to successfully execute the given
task. Consider the following CSV file (emp.csv):
1, Sumit, 6500
2, Arjun, 3500
3, Sandip, 7500
4, Ahmed, 9500
import ________ # Line 1
def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile,delimiter=’,’) # Line 3
count_rec=0 count_s=0
for row in myreader:
if row[1][0].lower()==’s’:
print(row[0],’,’,row[1],’,’,row[2])
count_s+=1
count_rec+=1
print(“Number of ‘S’ names are “,count_s,”/”,count_rec)
a) Name the module he should import in Line 1

30
b) In which mode, Vanshika should open the file to print data
c) Fill in the blank in Line 2 to open the file
d) Fill in the blank in Line 3 to read the data from a csv file
e) Write the output he will obtain while executing the above program
Ans. A) csv b) read mode c) emp.csv d) reader
e) 1, Sumit, 6500
3, Sandip, 7500
Number of “S” names are 1/3

7. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function countrec()
in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose
percentage is above 90. Also return number of students scoring above 90%
Ans. Import pickle
def CountRec():
fobj=open(“STUDENT.DAT”,”rb”)
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2] > 90:
print(rec[0],rec[1],rec[2],sep=”\t”)
num = num + 1
except:
fobj.close()
return num

8. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count
and return number of books by the given Author are stored in the binary file “Book.dat”

Ans.

import pickle def CountRec(Author):


fobj=open("Book.dat","rb")
def createFile():
num = 0
fobj=open("Book.dat","ab") try:
BookNo=int(input("Book Number : ")) while True:
rec=pickle.load(fobj)
Book_name=input("Name :")
if Author==rec[2]:
Author = input("Author:" ) num = num + 1
Price = int(input("Price : ")) except:
rec=[BookNo,Book_Name,Author,Price] fobj.close()
return num
pickle.dump(rec,fobj)
fobj.close()

31
6. Computer Networks

S.N. TOPICS
1 Computer Networks
Unit II: Computer Networks ● Evolution of networking: introduction to computer networks,
evolution of networking (ARPANET, NSFNET, INTERNET) ● Data communication
terminologies: concept of communication, components of data communication
(sender,receiver, message, communication media, protocols), measuring capacity of
communication media (bandwidth, data transfer rate), IP address, switching techniques
(Circuit switching, Packet switching) ● Transmission media: Wired communication media
(Twisted pair cable, Co-axial cable, Fiber-optic cable), Wireless media (Radio waves,
Micro waves, Infrared waves) ● Network devices (Modem, Ethernet card, RJ45,
Repeater, Hub, Switch, Router, Gateway, WIFI card) ● Network topologies and Network
types: types of networks (PAN, LAN, MAN, WAN), networking topologies (Bus, Star,
Tree) ● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET,
VoIP ● Introduction to web services: WWW, Hyper Text Markup Language (HTML),
Extensible Markup Language (XML), domain names, URL, website, web browser, web
servers, web hosting
2 Database concepts
Unit III: Database Management ● Database concepts: introduction to database
concepts and its need ● Relational data model: relation, attribute, tuple, domain,
degree, cardinality, keys (candidate key, primary key, alternate key, foreign key)

Introduction
Computer Network is a collection of autonomous computers interconnected by a single technology.

32
A Computer network is a network of computers which share information and resources from each
other.
A group of computers which are connected to each other and follow similar usage protocols for the
purpose of sharing information and having communications provided by the networking nodes is
called a Computer Network.
Two computers are said to be interconnected if they are able to exchange information.
A computer network is a system that connects independent computers in order to share information
and resources.
A network may be small where it may include just one system or maybe as large as what one may
want. The nodes may further be classified into various types. These include:

 Personal Computers
 Servers
 Networking Hardware
 General Hosts
Networking can be classified into three types:

1. Types of Computer Networks


2. Topology
3. Interpreters

Advantage of Computer Network:


 Central Storage of Data
 Sharing of Information
 Sharing of Resources (Hardware & Software)
 Reliability
 Communication
 Reduced Cost

Disadvantage of Computer Network:


 Computer networks require a specific setup
 Lack of Security
 Cost of network hardware and software

Evolution of Networking
ARPANET
In the 1960s a research project was commissioned by Advanced Research Projects Agency
Network (ARPANET) in the U.S. Department of Defence to connect the academic and research
institutions located at different places for scientific collaborations. The first message was
communicated between the University of California, Los Angeles (UCLA) and Stanford Research
Institute (SRI). Slowly but gradually, more and more organisations joined the ARPANET, and many
independent smaller networks were formed.
NSFNET
NSFNET program was launched by National Science Foundation in 1986 to bring connectivity to
more people. It was popularly used to promote advanced research and education networking in the
United States.
Internet (INTERconnection NETwork)
33
The Internet is a network of the interlinked computer networking worldwide, which is accessible to
the general public. Internet is a huge network of several different interlinked networks relating to the
business, government, academic and even smaller domestic networks. Therefore, Internet is known
as the network of all the other networks.
These networks enable the Internet to be used for various important functions, which include the
several means of communications like the file transfer, the online chat and even the sharing of the
documents and websites on the WWW or the World Wide Web.

Data Communication
Communication is an act of sending or receiving data. Thus, data communication refers to the
exchange of data between two or more networked or connected devices.

Components of Data Communication:


 Message – It is information to be communicated
 Sender – The device which send the message
 Receiver – The device which receive the message
 Transmission media – It is physical path by which message travel from sender to receiver
 Protocol – It is set of rules that governs data communication. Actually, it is agreement
between the sender and receiver regarding various communication parameter.

Network Terminology
 Node- The device connected to a network.
 Client – The device that requests for a service
 Server – The Device that renders the services
 Client-Server - In this model, the data are stored on powerful computers called Server that
can be accessed by a much simpler computer called Client that are connected by a
network.
 Network Interface Card or Unit (Network Adapter or LAN card) - It is hardware that allows
a computer (or device) to connect to network.
 MAC (Media Access Control) address – Each NIC is assigned a unique 12-digit hexadecimal
number, known a MAC address, is used as network address in communication. The format for
the MAC address is MM : MM : MM : SS : SS : SS Manufacturer ID Card Id
 IP Address: Every device on network has unique identifier called IP address. It
consists of 4 bytes (IPv4) decimal number (between 0 to 255) separated by ‘.’
(Period).
 Channel – It is communication path through which data is actually transmitted.
 Communication Media- It allows data or signal to be communicated across the devices. It is
means of communication.
 Data – Information stored within the computer system in form of ‘0’ and ‘1’
 Signal- It is electric or electromagnetic encoding of data to be transmitted. It can be
categorized into following two types:
1.Analog Signal – that has infinitely many levels of intensity over a period of time.
2. Digital Signal – that can have only a limited number of defined values.
 Bit rate – It defines the amount of data transferred. It is defined as number of bits per
second (bps). [Bps – Bytes per Second]
 Baud – The number of changes in signal per second.

34
 Bandwidth – It is difference between the highest and the lowest frequencies contained in
the signal.

IP Address vs MAC Address


IP Address MAC Address
It is of 4 bytes It is of 6 bytes
Represented by decimal number Represented by hexadecimal number
It is logical address It is physical address
Its value can vary for the same machine It is fixed address
It can be assigned only when a device It is assigned by manufacturer of the card
is connected to network irrespective of connectivity
Command to know the IP address is Command to know the IP address is
Ipconfig ipconfig/all

Switching Technique
A switched network consists of a series of interlinked nodes called switches capable of creating
temporary connections between two or more liked devices.
There are three basic switching technique
 Circuit Switching: In circuit switching a dedicated path is established before sending data from
sender to receiver and entire communication is carried out the same path.
 Packet Switching – In packet switching in a message is broken into a number of parts called
packet which are sent independently from sender to receiver and reassembled at the destination.
 Message Switching: Message switching is a connectionless network switching technique where
the entire message is routed from the source node to the destination node, one hop at a time. It
was a precursor of packet switching.
Circuit Switching vs Packet Switching
Circuit Switching Packet Switching
A dedicated path is established No dedicated path is established
Entire message follows the same path Each packet travels independently to each
other

Network Devices
Modem
 It stands for modulator and demodulator  It a computer hardware device that converts data from
a digital format into a format suitable for an analog.
 A modem transmits data by modulating one or more carrier wave signals to encode digital
information, while the receiver demodulates the signal to recreate the original digital information.
Repeater
 Repeaters are network devices that amplify or regenerate an incoming signal before
retransmitting it.
 It operates at physical layer of the OSI model.
 The repeater allows to transfer the data through large area distance
Hub
 It is a multiport device that allows multiple computers to communicate with each other over a
network.

35
 It is a non-intelligent network device that sends message to all ports( i.e. Broadcast)
Types of Hubs
Active Hub
 It strengthens the signal and may boost noise too.
 It is relatively costlier than passive hub.
Passive Hub –
 It repeat/copy signals.
 It is relatively cheaper than active hub.
Switch
 Network Switch or switch is also a network multiport device that allow multiple computers to
connect together.
 Network switch inspects the packet, determine source and destination address and route the
packet accordingly.
 It operates at Data Link Layer (layer 2) of OSI model.
Bridge
 It connects multiple network segments having same protocol
 It works at Data Link Layer (Layer 2).
 Bridge does not simply broadcast traffic from one network.
 Bridges use bridge table to send frames across network segments.  It also improves the overall
network performance.
Router
 A router is a device that connects two or more packet-switched networks or sub networks.
 It serves two primary functions:
 Managing traffic between these networks by forwarding data packets to their intended
IP addresses, and
 Allowing multiple devices to use the same Internet connection.
 It connects LANs (local area networks) and WANs (wide area networks).
 It operates on layer 3 or 4 in OSI model
Gateway
 It is simply a device or hardware that acts as a "gate" between the networks.
 It connects two networks with different transmission protocols together.
 It converts information, data or other communications from one protocol or format to another.
 It operates on layer 5 of OSI model
RJ45
 It stands for Registered Jack.
 It is common interface to connect Twisted Pair Cable.
 It is used for Ethernet and Token Ring Network.
Ethernet Card
 It also known as NIC card.
 It enables a computer to access an Ethernet network (LAN)
 It has MAC id which gives it unique identity in the network.

Wi-Fi card
 It is also known wireless network adaptor.
 It is a wireless network technology that allows devices to communicate over wireless signals.
 It uses radio waves for the communication
36
Difference between Router and Switch
.A network switch forwards data packets between groups of devices in the same network, whereas
a router forwards data between different networks.
Difference between a Router and a Modem
A router forms networks and manages the flow of data within and between those networks, while a
modem connects those networks to the Internet.
Difference between a Router and Gateway
A gateway is a concept while a router is a device that implements a gateway.

Router Gateway
It ensure that data packets are switched to To connect two networks of different
the right address with the best route. protocols as a translator
It routes the data packets via similar networks It connects two dissimilar networks
It supports dynamic Routing. It does support dynamic Routing.

Type of Network
PAN
 It stands for Personal Area Network.
 It is a computer network formed around a person.
 It generally consists of a computer, mobile, or personal digital assistant.
 Appliances use for PAN: cordless mice, keyboards, and Bluetooth systems.
 PAN includes mobile devices, tablet, and laptop.
LAN
 It is a group of computer and peripheral devices which are connected in a limited area such
as room, building & campus.
 Higher Data Speed.
 LANs are in a narrower geographic scope (up to 1 Km).
 It is a private network.

MAN
 A Metropolitan Area Network or MAN is consisting of a computer network that span across a
city.
 It mostly covers towns and cities in a maximum 50 km range.
 The dual bus in MAN network provides support to transmit data in both directions
concurrently.
WAN
 It connects device across globe.
 It uses public network
 Internet
 BSNL

Network Media

37
Guided or Wired
 Telephone (T1) cable
 Twisted pair cable
 STP (Shielded Twisted Pair)
 UTP (Unshielded Twisted Pair)
 Co-axial cable
 Optical Fiber/Fibre

Unguided or Wireless
 Infrared
 Radio Wave
 Microwave
 Bluetooth
 Satellite

Twisted Pair Cable


 A twisted pair cable comprises of two separate insulated copper wires, which are twisted
together and run in parallel.
 A STP (Shielded Twisted Pair) cable has a fine wire mesh surrounding the wires to
protect the transmission
 UTP (Unshielded Twisted Pair) cable does not has a fine wire mess.
 It is also known as Cat# cable where # denote number. e.g., Cat6
 Connector: RJ 45
Co-axial Cable
 Coaxial cabling has a single copper conductor at its center, and a plastic layer that provides
insulation between the center conductor and a braided metal shield.
 Connector: BNC (Bayonet Neill-Concelman)
Optical Fibre
38
 An optical fiber is a flexible, transparent fiber made by drawing glass or plastic to a diameter
slightly thicker than that of a human hair.
 It uses light for data transmission using total internal reflection.
Unguided Media or Wireless Media
 No Physical media is used
 Less Secure
 Relatively low speed
 Can be used for longer distance
 Best suited for difficult terrain
 There is no need to acquire land rights
Radio Wave
 Frequency – 3KHz – 1GHz
 Omni-Directional
 Penetrate obstacle
 Antenna of sender and receiver should not be aligned
Infrared
 300GHz to 400THz
 Line of sight- antenna of sender and receiver must be aligned
 Short distance communication
 It cannot penetrate obstacle -best suited for indoor
 Secure
 Support high data rate
 TV Remote

Microwave
 1GHz to 300 GHz
 Line of sight- antenna of sender and receiver must be aligned
 Cannot penetrate obstacles
 Rain or other disturbance cause issue with Microwave
 Types of microwave propagation
 Terrestrial Microwave propagation
 Satellite Microwave propagation
Bluetooth
 It also uses radio waves
 2.4 GHz
 Range 10mtr
 Short distance

Topology
Physical and Logical arrangement of nodes in the network is called Network Topology.
Types of Topologies
 Bus
 Ring
 Star Bus Topology
 Tree
39
 Mess
 Hybrid

Bus Topology
 In Bus Topology all the nodes are connected to single cable or backbone
 Both the end has terminators.

Ring Topology
 In Ring Topology all the nodes are connected to
each-other to form a loop.
 Each workstation is connected to two other components on either side
 It communicates with these two adjacent neighbors.
 Data is sent and received using Token.

Star Topology
 In Star Topology all the nodes are connected to a central device called Hub/Switch.
 All communication is controlled by the central Device (Hub/Switch)

Tree Topology

40
 In Tree Topology, the devices are arranged in a tree fashion similar to the branches of a
tree.
 It has multilayer architecture.

Protocol
 It is set of rules or standard that governs communication.

Types of Protocol (Broadly can be kept in two suites of Protocols vis. TCP/IP or OSI)
 FTP
 HTTP/HTTPS
 IMAP
 POP3
 SMTP
 PPP
 TELNET
 VoIP

TCP/IP – Transmission Control Protocol/ Internet Protocol


 It is a protocol suite consist of two protocols Transmission Control Protocol and Internet
Protocol.
 TCP ensures reliable transmission or delivery of packets on the network.

HTTP (Hyper Text Transfer Protocol)


 It is is an application-layer protocol for transmitting hypermedia documents, such as HTML.
HTTPS (Secure Hyper Text Transfer Protocol)
 It is an extension of HTTP protocol for transmitting hypermedia documents, such as HTML
securely over a network.
 It encrypts data to be sent using TLS (Transport Layer Security)/SSL (Secure Sockets
Layer).

FTP (File Transmission Protocol)


 It is used for the transfer of computer files among hosts over TCP/IP (internet). Telnet
(TErminaL NETWork)
 It is an application protocol that allows a user to communicate with a remote device.

SMTP (Simple Main Transfer Protocol)


 It is used to send mail from mail client to mail server over internet.

POP3 (Post Office Protocol)


 It provides mechanism for retrieving emails from a remote server for a mail recipient.
 POP3 downloads the email from a server to a single computer, then deletes the email from
the server.
IMAP (Internet Message Access Protocol)
41
 It is also used to retrieve mail from mail server to client over internet (TCP/IP).
 It allows access to mail from different device.

VoIP (Voice over IP)


 It is also known as Internet Telephony or Internet calling.
 It allows to make voice calls using a broadband Internet connection instead of a regular (or
analog) phone line.

Introduction to web services WWW:


 The World Wide Web, commonly known as the Web, is an information system where
documents and other web resources are identified by Uniform Resource Locators, which
may be interlinked by hyperlinks, and are accessible over the Internet.
 The Web is not the same as the Internet: The Web is one of many applications built on top
of the Internet.
 Tim Berners-Lee proposed the architecture World Wide Web in 1989.

Application of Internet Web 2.0:


 The term web 2.0 is used to refer to a new generation of websites that are supposed to let
people to publish and share information online.
 It aims to encourage the sharing of information and views, creativity that can be consume
by the other users e.g.: YouTube

Web 3.0
 It refers to the 3rd Generation of web where user will interact by using artificial intelligence
and with 3-D portals.
 Web 3.0 supports semantic web which improves web technologies to create, connect and
share content through the intelligent search and the analysis based on the meaning of the
words, instead of on the keywords and numbers.
Hyper Text Markup Language (HTML):
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page

Various Tags are


 <html>represents the root of an HTML document
 <head> element is a container for metadata (data about data) and is placed between the
<html>tag and the<body> tag.
 <title>represents the root of an HTML document
 <body> defines the document's body.
 </br> Line Break tags
 <h1><h2>…</h6> - Heading Tags - tags are used to define HTML headings.
 <font> defines font face, font size, and color of text etc.

Extensible Markup Language (XML)


 XML stands for eXtensible Markup Language.
 XML was designed to store and transport data.
 XML was designed to be both human- and machine-readable.
 XML is a markup language much like HTML
 XML was designed to be self-descriptive

The Difference between XML and HTML

42
HTML XML
It designed to display the data It is designed to carry data
Its tags are predefined Its tags user defined
It is not case sensitive It is case sensitive
It is static It is dynamic
It is Markup Language It is framework to define Markup language
Closing tags are not necessary in HTML Closing tags are necessary in XML

Domain names
 A domain name is a website's address on the Internet.
 Domain names are used in URLs to identify to which server belong a specific webpage.
 The domain name consists of a hierarchical sequence of names (labels) separated by periods
(dots) and ending with an extension.
URL
Uniform Resource Locator (URL) is a text string that specifies where a resource (such as a web
page, image, or video) can be found on the Internet.
Website
Website is a group of web pages, containing text, images and all types of multi-media files.
Web browser-
A web browser, or simply "browser," is an application used to access and view websites. Common
web browsers include Microsoft Internet Explorer, Google Chrome, Mozilla Firefox, and Apple
Safari.
Web servers:
A web server is a computer that stores web server software and a website's component files (e.g.
HTML documents, images, CSS style sheets, and JavaScript files).
Web hosting:
Web hosting is an online service that enables you to publish your website or web application on the
internet. When you sign up for a hosting service, you basically rent some space on a server on which
you can store all the files and data necessary for your website to work properly.

Types of Web Hosting


 Shared Hosting - Web server shared among customers
 Reseller Hosting – Become yourself as web host to sell others
 Virtual Private Server – One server as multiple server for multiple websites
 Dedicated Server- Entire web server is dedicated to same website

Examples of domain names and their mapped IP addresses


Domain names me IP addresses s
ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32
mhrd.gov.in 164.100.163.45
43
wikipedia.org 198.35.26.96

DNS Server
Instead of remembering IP addresses, we assign a domain name to each IP. But, to access a web
resource, a browser needs to find out the IP address corresponding to the domain name entered.
Conversion of the domain name of each web server to its corresponding IP address is called domain
name resolution. It is done through a server called DNS server. Thus, when we enter a URL on a
web browser, the HTTP protocol approaches a computer server called DNS server to obtain the IP
address corresponding to that domain name. After getting the IP address, the HTTP protocol
retrieves the information and loads it in our browser.

ABBREVIATIONS

1 NIU Network Interface Unit


2 MAC Media Access Control
3 TCP/IP Transmission Control Protocol/Internet Protocol
4 PAN Personal Area Network
5 LAN Local Area Network
6 MAN Metropolitan Area Network
7 WAN Wide Area Network
8 UTP Unshielded Twisted Pair
9 STP Shielded Twisted Pair
10 Mbps Mega bits per sec
11 EMI Electro Magnetic Interference
12 RJ Registered Jack
13 Wi-Fi Wireless Fidelity
14 VPN Virtual Private Network
15 IAAS Infrastructure As A Service
16 PAAS Platform As A Service
17 SAAS Software As A Service
18 DAAS Desktop As A Service
19 IOT Internet Of Things
20 NIC Network Interface Card
21 CSMA/CD Carrier Sense Multiple Access/Collision Detection
22 CSMA/CA Carrier Sense Multiple Access/Collision Avoidance
23 DNS Domain Name System
24 DHCP Dynamic Host Configuration Protocol
25 ISP Internet Service Provider
26 URL Uniform Resource Locator
27 HTTP Hyper Text Transfer Protocol
28 FTP File Transfer Protocol
29 FDMA Frequency Division Multiple Access
30 TDMA Time division Multiple Access
31 CDMA Code Division Multiple Access
32 SIM Subscriber Identity Module
33 EDGE Enhanced Data rates for GSM Evolution
34 UMTS Universal Mobile Telecommunications System
35 LTE Long Term Evolution
36 GPRS General Packet Radio Service
37 ICMP Internet Control Message Protocol
38 OSI Open Systems Interconnection
39 SMTP Simple Mail Transfer Protocol
40 VoIP Voice Over Internet Protocol
41 SIP Session Initiation Protocol
42 QoS Quality of Service
43 POP Post Office Protocol
44 IMAP Internet Mail Access Protocol
45 SCP Secure Copy Protocol
46 SSH Secure Shell
47 IEEE Institute of Electrical & Electronic Engineering
44
48 NFC Near-Field Communication
49 NFS Network File System
50 NTP Network Time Protocol
51 SLIP Serial Line Internet Protocol
52 PPP Point to Point Protocol
53 UDP User Datagram Protocol
54 SNMP Simple Network Management Protocol

1 MARKS QUESTION
1 Fill in the blank: ______is a communication methodology designed to deliver both voice and
multimedia communications over Internet protocol.
(a) VoIP (b) SMTP (c) PPP (d)HTTP
Ans (a) VoIP
2 What is the Use of Bridge?
(a) To Connect two LAN (b) To Connect two LAN Segment
(a) To Connect Internet (d) Amplify Signal

Ans (b) To Connect two LAN Segment


3 With the use of computer network, we can share
(a) Data (b) Resources
(c) Both of the above (d) None of the above
Ans (c) Both of the above
4 Which of the following is used in computer network
(a) Router (b) Switch (c) Bridge (d) All of the Above

Ans (d) All of the Above


5 Computer Network is
A. Collection of hardware components and computers
B. Interconnected by communication channels
C. Sharing of resources and information
D. All of the Above

Ans D. All of the Above


6 What is a Firewall in Computer Network?
A. The physical boundary of Network
B. An operating System of Computer Network
C. A system designed to prevent unauthorized access
D. A web browsing Software
Ans C. A system designed to prevent unauthorized access
7 DNS is the abbreviation of
A. Dynamic Name System B. Dynamic Network System
C. Domain Name System D. Domain Network Service
Ans C. Domain Name System
8 What is the meaning of Bandwidth in Network?
A. Transmission capacity of a communication channels
B. Connected Computers in the Network
C. Class of IP used in Network
D. None of Above
Ans A. Transmission capacity of a communication channels

45
9 Each IP packet must contain
A. Only Source address B. Only Destination address
C. Source and Destination address D. Source or Destination address
Ans C. Source and Destination address
10 _______ provides a connection-oriented reliable service for sending messages
A. TCP B. IP C. UDP D. All of the above
Ans A. TCP
11 Which of the following is not a feature of networking?
(a) Resource sharing (b) Uninterrupted Power Supply (UPS)
(c) Reduced cost (d) Reliability
Ans (b) Uninterrupted Power Supply (UPS)
12 Which of these is not a communication channel?
a) Satellite b) Microwave c) Radio wave d) Wi-Fi
Ans d) Wi-Fi

14 Which of the following is the smallest network?


a) WAN b) MAN c) PAN d) LAN
ans c) PAN

15 Which transmission media is capable of having a much higher bandwidth (data capacity)?
a) Coaxial b) Twisted pair cable c) Untwisted cable d) Fiber optic
Ans d) Fiber optic
16 Which type of transmission media is the least expensive to manufacture?
a) Coaxial b) Twisted pair cable c) CAT cable d) Fiber optic
Ans b) Twisted pair cable

17 A device that forwards data packet from one network to another is called a
a) Bridge b) Router c) Hub d) Gateway
Ans b) Router

18 Which of the following is the fastest media of data transfer?


a) Co-axial Cable b) Untwisted Wire c) Telephone Lines d) Fiber Optic
Ans d) Fiber Optic

19 Switch is a
a) Broadcast device b) Unicast device c) Multicast device d) None of the above
Ans b) Unicast device

20 In computer, converting a digital signal in to an analog signal is called


a) modulation b) demodulation c) conversion d) transformation
Ans a) modulation

21 What is the address size of IPv6?


a) 32 bit b) 64 bit c) 128 bit d) 256 bit
Ans c) 128 bit

22 Which of these is not an example of unguided media?


a) Optical Fibre Cable b) Radio wave c) Bluetooth d) Satellite
Ans a) Optical Fibre Cable

23 Which of the following is not the Networking Devices?

46
a) Gateways b) Linux c) Routers d) Firewalls
Ans b) Linux

24 The location of a resource on the internet is given by its?


a) Protocol b) URL c) E-mail address d) ICQ
Ans b) URL

25 Which one of the following is not a network topology?


a) Star b)Ring c)Bus d)Peer to Peer
Ans d)Peer to Peer
26 Expand the following terms: POP3 , URL
Ans POP3- Post Office Protocol 3
URL- Uniform Resource Locator
27 Expand the following : HTTPS, TDMA
Ans HTTPS- Hypertext Transfer Protocol Secure
TDMA : Time-division multiple access
28 Name any 2 most popularly search engines
Ans Google and Bing
29 Name any 2 common web browser
Ans Google Chrome and Mozilla Firefox
30 What is telnet
Ans TELNET is used to access a remote computer / network.

2 MARKS QUESTION
1 Differentiate e between XML and HTML.
Ans HTML( Hyper text mark Up language) XML (Extensible Markup Language)
We use pre-defined tags we can define our own tags and use
them
Static web development language – only Dynamic web development language
focuses on how data looks
It use for only displaying data, cannot as it is used for transporting and storing
transport data data
Not case sensitive Case sensitive
2 How is http different from https?

Ans https (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to
encrypt data being transmitted over the Internet. Therefore, https helps in secure browsing while
http does not.
3 Write two points of difference between Circuit Switching and Packet Switching.
Ans Circuit Switching Packet Switching
Circuit switching is the method of switching Packet switching is the method of switching
which is used for establishing a dedicated where no dedicated path is established from
communication path between the sender the source to the destination.
and the receiver
Data is processed and transmitted at the Data is processed and transmitted, not only
source only. at the source but at each switching station
It is more reliable. It is less reliable.
4 How is http different from https?
Ans https (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to
encrypt data being transmitted over the Internet. Therefore, https helps in secure browsing while
http does not.
5 Differentiate e between LAN and WAN.

47
Ans Difference between LAN and WAN
LAN is private. WAN can be private or public.
The full form of LAN is Local Area The full form of WAN is Wide Area Network.
Network.
The speed of LAN is higher. The speed of WAN is slower.
The configuration and maintenance is easy The configuration and maintenance is harder
in LAN. than LAN.
LAN covers smaller areas like school, WAN covers a large area like a country.
hospital, etc.
Coaxial or UTP cable is the transmission PSTN or satellite link is a transmission
medium used by LAN. medium used by WAN.
6 Explain Any two Wired Media
Ans a. Twisted Pair Cable
A twisted pair cable comprises of two separate insulated copper wires, which are twisted together
and run in parallel.
b. Fibre Optics
Fibre optic cables are mainly used to transmit information over long distances with minimum loss.
The information through optical fibres is transmitted in the form of light pulses. The core of the optical
fibres is made of glass or plastic.
7 Define Any Two Topologies
Ans a. Star
Star topology is a network topology in which each network component is physically connected to a
central node such as a router, hub or switch. In a star topology, the central hub acts like a server
and the connecting nodes act like clients
b. Bus
A bus topology is a type of local area network configuration in which computers or terminals (also
known as nodes) are connected to a single cable (as known as the backbone)

8 What is ARPANET? What is NSFNET?

Ans ARPANET (Advanced Research Project Agency Network) is a project sponsored by US Department
of Defense.
NSFNET, developed by the National Science Foundation, was a high-capacity network and strictly
used for academic and engineering research.

9 Define web browser and web server.


Ans Web Browser: - A web browser is a software which is used for displaying the content on web page(s).
It is used by the client to view websites. Examples of web browser: - Google Chrome, Firefox, Internet
Explorer, Safari, Opera, etc.
Web Server: - A web server is a software which entertains the request(s) made by a web browser. A
web server has different ports to handle different requests from web browser, like generally FTP
request is handled at Port 110 and HTTP request is handled at Port 80. Example of web server is
Apache

10 What is Cloud Computing? Name three types also


Ans Cloud computing is the on-demand availability of computer system resources, especially data
storage and computing power, without direct active management by the user. Large clouds often
have functions distributed over multiple locations, each of which is a data centre.
Types of Cloud
a. Private clouds
b. Public clouds
c. Hybrid clouds

48
5 MARKS QUESTION
1 MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres in
various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus, they are
planning to have 3 different blocks for App development, Web designing and Movie editing. Each block has
number of computers, which are required to be connected in a network for communication, data and resource
sharing. As a network consultant of this company, you have to suggest the best network related solutions for
them for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between various

blocks/locations and other given parameters.

KASHIPUR
APP CAMPUS
DEVELOPM MOVIE
ENT EDITING
MUSSOORIE
CAMPUS
WEB
DESIGNING

Distance
between various blocks/locations:
Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 km
Number of computers
Block Number of Computers
App development 75
Web designing 50
Movie editing 80

I Suggest the most appropriate block/location to house the SERVER in the Kashipur campus
(out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
Ans Movie editing block is the most appropriate to house the server as it has the maximum number of computers.
II Suggest a device/software to be installed in the Kashipur Campus to take care of data security.
Ans Firewall
III Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect various
blocks within the Kashipur Campus
Ans Ethernet Cable
Layout:

KASHIPUR
APP CAMPUS
DEVELOP MOVIE
MENT EDITING

WEB
DESIGNING

IV Suggest the placement of the following devices with appropriate reasons:


a Switch / Hub
b Repeater
Ans Switch/hub will be placed in all blocks to have connectivity within the block.
Repeater is not required between the blocks as the distances are less than 100 mts.

49
V Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur Campus and
Mussoorie Campus.
Ans Protocol: VoIP

2 JNV School at Hyderabad have their offices according to the following diagram. Go through the details
and answer the questions that follows.
JNV,

MESS7

NOIDA
SCHOOL40

5 ADMIN10

Hyderabad

Distance between various wings are given below:


Wings Distance ( in Metre)
MESS to SCHOOL 60
MESS to DORMETORY 110
MESS to GATE 65
MESS to ADMIN 130
SCHOOL to DORMETORY 40
SCHOOL to GATE 50
SCHOOL to ADMIN 68
DORMETORY to GATE 115
DORMETORY to ADMIN 100
GATE to ADMIN 65
I Draw the cable layout to efficiently connect various wings JNV, Hyderabad and also write the topology.

Star Topology

MESS7

SCHOOL40

5 ADMIN10

II Suggest a device/software and its placement that would provide data security for the entire network of the
School.
Ans Firewall
III (a) Which device will you suggest to be placed/installed in each of these wings to efficiently connect all
the computers within these wings.
(b) Suggest the placement of a repeater in the network with justification.
Ans (a)- Switch
(b) Repeater will be placed between MESS and DORMETORY, MESS and ADMIN, DORMETORY and
GATE , DORMETORY and ADMIN because distance in these building is more than 100 meters
IV Suggest a device and the protocol that shall be needed to provide wireless Internet access to all
smartphone/laptop users in the campus of JNV, Hyderabad.
50
Ans WiFi Router
V Which of the following will you suggest to establish the online face to face communication between the
people in the ADMIN office of Hyderabad campus and Noida head office?
a) Cable TV b) Email c) Video conferencing d) Text chat
Ans c) Video conferencing

3 Prime Computer services Ltd. is an international educational organization. It is planning to set up its India
campus at Mumbai with its head office in Delhi. The Mumbai office campus has four main buildings-ADMIN,
ACCOUNTS, EXAMINATION and RESULT.
You as a network expert have to suggest the best network related solutions for their problems raised in (i) to
(v), keeping in mind the distances between the buildings and other given parameters

MUMBAI CAMPUS

DELHI HEAD OFFICE EXAMINATION ACCOUNTS

ADMIN
RESULT

Shortest distances between various buildings:


ADMIN TO ACCOUNTS 55 m
ADMIN TO EXAMINATION 90 m
ADMIN TO RESULT 50 m
ACCOUNTS TO EXAMINATION 55 m
ACCOUNTS TO RESULT 50 m
EXAMINATION TO RESULT 45 m
DELHI Head Office to MUMBAI 2150 m

Number of computers installed at various buildings are as follows:


ADMIN 110
ACCOUNTS 75
EXAMINATION 40
RESULT 12
DELHI HEAD OFFICE 20
I Suggest and draw cable layout to efficiently connect various buildings within the MUMBAI campus for a wired
connectivity.

Ans BUS Topology

MUMBAI CAMPUS

EXAMINATION ACCOUNTS

ADMIN RESULT

II Suggest the most appropriate location of the server inside the MUMBAI campus (out of the four buildings) to
get the best connectivity for maximum number of computers. Justify your answer.

51
Ans Admin block, as it has maximum number of computers.

III Which networking device will you suggest to be procured by the company to interconnect all the computers of
various buildings of MUMBAI campus?

Ans Switch
IV Company is planning to get its website designed which will allow students to see their results after registering
themselves on its server. Out of the static or dynamic, which type of website will you suggest?

Ans Dynamic
V Which fast and very effective wireless transmission medium should preferably be used to connect the head
office at DELHI with the campus in MUMBAI?
Ans Microwave

52
4 MyPace University is setting up its academic blocks at Naya Raipur and is planning to
set up a network. The University has 3 academic blocks and one Human Resource
Center as shown in the diagram below:

Center to Center distances between various blocks/center is as follows:


Law Block to business Block 40m
Law block to Technology Block 80m
Law Block to HR center 105m
Business Block to technology Block 30m
Business Block to HR Center 35m
Technology block to HR center 15m
Number of computers in each of the blocks/Center is as follows:
Law Block 15
Technology 40
Block
HR center 115
Business Block 25

I Suggest the most suitable place (i.e., Block/Center) to install the server of this
University with a suitable reason.
Ans HR Center, as it has maximum number of computers.
II Suggest an ideal layout for connecting these blocks/centers for a wired connectivity.

III Which device will you suggest to be placed/installed in each of these blocks/centers to
efficiently connect all the computers within these blocks/centers.
Ans Switch
IV Suggest the placement of a Repeater in the network with justification.
Ans Between Law Block to HR center, because distance is more than 100 meters
V The university is planning to connect its admission office in Delhi, which is more than
1250km from university. Which type of network out of LAN, MAN, or WAN will be
formed? Justify our answer.
Ans WAN, because distance is more than 1250 km
53
5 Meticulous EduServe is an educational organization. It is planning to setup its India campus at
Chennai with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN,
ENGINEERING, BUSINESS and MEDIA

Block to Block distances (in Mtrs.)


From To Distance
ADMIN ENGINEERING 55 m
ADMIN BUSINESS 90 m
ADMIN MEDIA 50 m
ENGINEERING BUSINESS 55 m
ENGINEERING MEDIA 50 m
BUSINESS MEDIA 45 m
DELHI HEAD OFFICE CHENNAI CAMPUS 2175 km

Number of computers in each of the blocks/Center is as follows:


ADMIN 110
ENGINEERING 75
BUSINESS 40
MEDIA 12
DELHI HEAD 20
a Suggest and draw the cable layout to efficiently connect various blocks of buildings within the
CHENNAI campus for connecting the digital devices.
Ans BUS topology

ADMIN ENGINEERING

MEDIA BUSINESS

b Which network device will be used to connect computers in each block to form a local area
network?
Ans Switch
c Which block, in Chennai Campus should be made the server? Justify your answer.

54
Ans Admin block, as it has maximum number of computers.
d The company is planning to link its head office situated in New Delhi with the offices in hilly
areas. Suggest a way to connect it economically.
Ans Microwave
e Is there a requirement of a repeater in the given cable layout? Why/ Why not?
Ans No, a repeater is not required in the given cable layout as the length of transmission
medium between any two blocks does not exceed 70 m.

55
6. Database concepts
Unit III: Database Management ● Database concepts: introduction to database concepts
and its need ● Relational data model: relation, attribute, tuple, domain, degree, cardinality,
keys (candidate key, primary key, alternate key, foreign key)

Database Management System


 May be defined as a collection of interrelated data stored together to serve multiple
application
 It is computer based record keeping system.
 It not only allows to store but also allows us modification of data as per requirements
DBMS:
 A DBMS refers to Database Management System
 It is software that is responsible for storing, manipulating, maintaining and utilizing database.
 A database along with a DBMS is referred to as a database system.
 There are various DBMS software available in the market. e.g. Oracle, MS SQL Server,
MySQL, Sybase, PostgreSQL, SQLite
Purpose of DBMS:
 Reduce Data redundancy
 Control Data Inconsistency
 Sharing of data
 Ensure data integrity
 Enforce standard
Relational Database Model:
 In relational database model data is organized into table (i.e. rows and columns).
 These tables are also known as relations.
 A row in a table represents relationship among a set of values.
 A column represents the field/attributes related to relation under which information will be
stored.
 For example if we want to store details of students then : Roll, Name, Class, Section, etc.
will be the column/attributes and the collection of all the column information will become a
Row/Record

Limitations of a File System


 Difficulty in Access
 Data Redundancy
 Data Inconsistency
 Data Isolation
 Data Dependence
 Controlled Data Sharing

Key Concepts in DBMS


Database Schema
 Database Schema is the design of a database.
Data Constraint
 Sometimes we put certain restrictions or limitations on the type of data that can be inserted
in one or more columns of a table. This is done by specifying one or more constraints on that
column(s) while creating the tables.
Meta-data or Data Dictionary
 The database schema along with various constraints on the data is stored by DBMS in a
database catalog or dictionary, called meta-data

Database Instance

56
 When we define database structure or schema, state of database is empty i.e. no data entry
is there. Afterloading data, the state or snapshot of the database at any given time is the
database instance.
Query
 A query is a request to a database for obtaining information in a desired way.

Data Manipulation
 Modification of database consists of three operations viz. Insertion, Deletion or Update.
Database Engine
 Database engine is the underlying component or set of programs used by a DBMS to create
database and handle various queries for data retrieval and manipulation.

Relational Data Model


 Different types of DBMS are available and their classification is done based on the
underlying data model. A data model describes the structure of the database, including how
data are defined and represented, relationships among data, and the constraints. The most
commonly used data model is Relational Data Model. Other types of data models include
object-oriented data model, entity-relationship data model, document model and
hierarchical data model.
 Data is organized in two-dimensional tables called relations. The tables or relations are
related to each other.

Characteristics of relational database are:-


 Data is arranged into rows and columns,
 Each relation is represented as a table.
 Every row in a table represents a single entity.
 At any given row or column position, there is one and only one value.

Various Terms Used in Relational Model: -


A relational database is a type of database that stores and provides access to data points that are
related to one another. Basic Terminologies related to a Relational Database:-
 Entity: An entity is something that exists and an object which can be distinctly identified. For
example, student entity, employee entity,
 Attribute: The term attribute is also used to represent a column.
 Tuple: Each row in a table is known as tuple.
 Cardinality of Relation: It is the number of records or tuples in a relation.
 Degree of Relation: Number of columns or attributes is known as degree of a relation.
 Domain of Relation: It defines the kind of data represented by the attribute.
 Body of the Relation: It consists of an unordered set of 0 or more tuples.

57
Component of a table/relation:
 Data Item: smallest unit of named data. It represent one type of information and often
referred to as a field or column information
 Record : collection of data items which represent a complete unit of information
 Table: collection of all Rows and Columns.

Properties of a Relation:
 Each relation has a unique name by which it is identified in the database.
 Relation does not contain duplicate tuples.
 The tuples of a relation have no specific order.
 All attributes in a relation are atomic, i.e., each cell of a relation contains exactly one value.

Properties of a row:
o No two tuples are identical to each other in all their entries.
o All tuples of the relation have the same format and the same number of entries.
o The order of the tuple is irrelevant. They are identified by their content, not by their position.

Properties of an Attribute:

o Every attribute of a relation must have a name.


o Null values are permitted for the attributes.
o Default values can be specified for an attribute automatically inserted if no other value is
specified for an attribute.
o Attributes that uniquely identify each tuple of a relation are the primary key.

NULL Values

The NULL value of the table specifies that the field has been left blank during record creation. It is
different from the value filled with zero or a field that contains space.

Data Integrity

There are the following categories of data integrity exist with each RDBMS:

Entity integrity: It specifies that there should be no duplicate rows in a table.

Domain integrity: It enforces valid entries for a given column by restricting the type, the format, or
the range of values.

Referential integrity specifies that rows cannot be deleted, which are used by other records.

User-defined integrity: It enforces some specific business rules defined by users. These rules are
different from the entity, domain, or referential integrity.

Concept of Keys
 In relation each record must be unique i.e. no two identical records are allowed in the
Database.
 A key attribute identifies the record and must have unique values. There are various types
of Keys:
Primary key:

58
 A set of one or more attribute that can identify a record uniquely in the relation is called
Primary Key.
 There can be only one primary key in a table
 Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL) i.e.
we can’t leave it blank.
Candidate Key
 In a table there can be more than one attribute which uniquely identifies a tuples in a
relation. These columns are known as candidate key as they are the candidate for primary
key.
 Among these database analyst select only one attribute as a primary key.
Alternate Key
 In case of multiple candidate keys, one of them will be selected as Primary Key and rest of
the column will serve as Alternate Key.
 A Candidate Key which is not a primary key is an Alternate Key.

59
Foreign key
 Used to create relationship between two tables.
 It is a non-key attribute whose value is derived from the Primary key of another table.
 Primary Key column table from where values will be derived is known as Primary Table or
Master Table or Parent Table and Foreign key column table will be Foreign Table or Detail
Table or Child table.

REFERENTIAL INTEGRITY:
 Used to ensure relationships between records in related tables are valid and user don’t
accidentally delete or change the related data.
 Referential integrity can be applied when:
 The master table’s column is a Primary Key or has a unique index
 The related fields have the same data type
 Both tables must belong to same database.
 When referential integrity is enforced using Foreign Key you must observe the following
rules:
 You cannot enter a value in Child Table which is not available in Master
Table’s Primary key column. However you can enter NULL values in foreign
key
 You cannot delete a record from Master Table if matching record exists in
related table.
 You cannot modify or change the Primary Key value in Master table if its
matching record is present in related table.

1 MARKS QUESTION

1 Key to represent relationship between tables is called


(A) Primary key (B) Secondary Key
(C) Foreign Key (D) None of these
Ans (C) Foreign Key
2 _______ produces the relation that has attributes of R1 and R2
(A) Cartesian product (B) Difference (C) Intersection (D) Product
Ans A) Cartesian product
3 It is better to use files than a DBMS when there are
(A) Stringent real-time requirements.
(B) Multiple users wish to access the data.
(C) Complex relationships among data.
(D) All of the above.
Ans B) Multiple users wish to access the data.
60
4 The RDBMS terminology for a row is
(A) tuple. (B) relation. (C) attribute. (D) degree.
Ans (A) tuple
5 What is the full form of DBMS?
a) Data of Binary Management System
b) Database Management System
c) Database Management Service
d) Data Backup Management System

Ans b) Database Management System

6 What is a database?
a) Organized collection of information that cannot be accessed, updated, and managed
b) Collection of data or information without organizing
c) Organized collection of data or information that can be accessed, updated, and
managed
d) Organized collection of data that cannot be updated

Ans c) Organized collection of data or information that can be accessed, updated, and
managed

7 The number of attributes in a relation determines the………… of a relation.


a) Degree b) Tuple c) Attributes d) Cardinality
Ans a) Degree

8 A…………………. is a non-key attribute whose value is derived from the primary key of
another table.
(a) Primary Key (b) Alternate Key
(c) Candidate Key (d) Foreign Key
Ans (d) Foreign Key
9 A pool of Values from where a column draws its value is called.
(a) Table (b) Attribute c) Domain (d) Data Set
Ans c) Domain

10 Which Data Model uses Tables:


(a) Hierarchical (b) Conceptual (c) Relational (c) Network
Ans (c) Relational

11 In a table in MYSQL database, an attribute A of datatype varchar(20) has the value


“Keshav”. The attribute B of datatype char(20) has value “Meenakshi”. How many
characters are occupied by attribute A and attribute B?
a. 20,6 b. 6,20 c. 9,6 d. 6,9
Ans b. 6,20

12 In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table,
Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the
Cartesian product of Alpha and Beta?
a. 5,3 b. 8,15 c. 3,5 d. 15,8
Ans b. 8,15

13 Which of the following statements is FALSE about keys in a relational database?


a.Any candidate key is eligible to become a primary key
b.A primary key uniquely identifies the tuples in a relation.
c.A candidate key that is not a primary key is a foreign key.

61
d.A foreign key is an attribute whose value is derived from the primary key of another
relation.
Ans c.A candidate key that is not a primary key is a foreign key.

14 The other name for a table is


(a) database (b) relation (c) domain (d) degree
Ans (b) relation

15 Special value that is stored when actual data value is unknown for an attribute. (NCERT)
(a) None (b) NULL (c) NaN (d) None of these
Ans (b) NULL

2 MARKS QUESTION
1 Explain the use of ‘Foreign Key’ in a Relational Database Management System.
Ans A foreign key is used to set or represent a relationship between two relations ( or tables) in
a database. Its value is derived from the primary key attribute of another relation

2 What is difference between degree and cardinality


Ans Degree in SQL refers to the number of attributes or columns in a relation or table. It
represents the horizontal size of the table. For example, if a table has three attributes, it has
a degree of three. Cardinality in SQL refers to the number of tuples or rows in a relation or
table
3 Any 2 advantages of DBMS
Ans 1. Data Integrity · 2. Data Security · 3. Better data integration
4 Difference between primary key and foreign key
Ans Primary keys and foreign keys are important concepts in database design as they help to
establish relationships between tables and help ensure data integrity. A primary key
uniquely identifies a row in a table, while a foreign key is used to link two tables together by
referencing the primary key of the related table.
5 Difference between primary key and Candidate key

S.
Ans Primary Key Candidate Key
No.

Primary key is a unique and non−null Candidate key is also a unique key
1. key which identify a record uniquely in to identify a record uniquely in a
table. table.

Primary key column value cannot be Candidate key column can have
2.
NULL. NULL value.

Primary key is most important part of Candidate key signifies as which


3.
any relation or table. key can be used as Primary Key.

Candidate key may or may not be a


4. Primary Key is a candidate key.
primary key.

A table can have multiple candidate


5. A table can have only one primary key.
keys.
6 Define Data Redundancy and Data Integrity
62
Ans Data Redundancy – Data redundancy refers to the practice of keeping data in two or
more places within a database or data storage system.

Data Integrity - Data integrity is the overall completeness, accuracy and consistency of
data over its entire lifecycle.
7 Define Integrity Constraints in DBMS
Ans In database management systems (DBMS) there is a certain set of rules which are used to
maintain the quality and consistency of data in the database. Every time there is an insertion,
deletion, or updating of data in the database it is the responsibility of these integrity
constraints to maintain the integrity of data and thus help to prevent accidental damage to
the database.
8 What are the characteristics of primary key
Ans The data in a specific column is always unique.
 A database table can only have one primary key.
 It uniquely identifies a record in a relational database table.
 The value of a primary key can't be deleted from the tree structure or the parent table.
 It doesn't permit null values.

UNIT-3
RELATIONAL DATABASES
Key Points of the Chapters:
Database:-Collection of interrelated data . It is basically a computer-based record keeping system
that serve multiple applications.
Relational data model:-It is a type of DBMS in which data is organized into tables, these tables are
called relations.
Relation :- Relation is a table that means data is organized into rows and columns.
Domain:-It is a pool of values from which the actual values present in a given column are drawn.
Tuple:-A row in a relation is called a tuple that is horizontal part of a relation and represents a record
of relation
Attribute:- A column in a relation is called an attribute. It is also termed as field or data item.
Degree:- Number of attributes in a relation is called degree of a relation.
Cardinality:-Number of tuples in a relation is called cardinality of a relation.
View:- It is a virtual table that does not really exist in its own but is instead derived from one or more
underlying base table.
Field:- Set of characters that represents specific data element.
Record:-Collection of fields is called a record. A record can have fields of different data types.
Table:-Collection of rows and columns that contains useful data/information is called a table. A table
generally refers to the passive entity which is kept in secondary storage device.

63
Primary Key:-Primary key is set of one or more attributes that can uniquely identifies the
records/tuples in a relation. This key can never be duplicated and NULL.
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are alternate keys
for a relation.
Foreign Key: A non-key attribute, whose values are derived from the primary key of some other
table is known as foreign key in its current table.
Employee table
Emp_id Emp_name salary PAN No Dept_no NPS_no
23008 Ramesh 50000 NALK8907P 10 32FG67
24009 kavita 35000 LMSA9845K 14 87KH86
23908 sana 45000 KMSN6789O 11 78PO98
Department table
Dept_no Dept_name Head
10 Marketing Mrs. Sumitra
11 Sales Mr. Raja raman
12 Purchasing Mr. K P Singh
13 Manufacturing Mr. JyotiRanjan
14 Store Miss Suman

eg:- candidate key in Employee table:- Emp_id, PAN No and NPS_no


Any one of candidate can be selected as primary key. If Emp_id is selected as Primary key then
PAN No and NPS_no is alternate key. Dept_no in Employee table can have only values that are
present in Dept_no column of Department table (it is a primary key in Department table) so it is a
foreign key in Employee table.

 DDL(Data Definition language): The DDL provides commands for the creation and deletion
and alteration of tables. DDL commands are: CREATE , ALTER , DROP
 DML(Data Manipulation language): The DML provides commands to enter, update, delete
data and perform complex queries on these tables.
DML commands are: SELECT, INSERT, DELETE, UPDATE
 TCL(Transaction Control Language) :TCL include commands to control the transactions
in a data base system. The TCL commands are: COMMIT, ROLLBACK , SAVE POINT
Relational Algebra:
CARTESIAN PRODUCT (X)

Let R and S be relations of degree n1 and n2 respectively. Then the Cartesian Product of R and
S, is of degree n1+n2 and Cardinality as n1*n2. It is denoted by R X S
Relation R Relation S

Roll Name Marks


age Class
12 Pallavi 94
17 XII
14 Mousumi 89
14 IX

Relation R X S

Roll Name Marks Age Class


64
12 Pallavi 94 17 XII
12 Pallavi 94 14 IX
14 Mousumi 89 17 XII
14 Mousumi 89 14 IX

Structured Query Language


(Short Notes)

SQL is a non procedural language that is used for accessing, handling and manipulating in the
databases(relations).
Data types of SQL

Just like any other programming language, the facility of defining data of various types is available
in SQL also. Following are the most common data types of SQL.

1) int, float , decimal(n,m) – used to store numeric data


2) CHAR, VARCHAR – Used to store fixed and variable length character string.
3) DATE – Used to store date related data/information in YYYY-MM-DD format.
SQL Commands

a. CREATE TABLE Command: Create table command is used to create a table in SQL. It is a
DDL type of command. The general syntax of creating a table is

The syntax for creating a table is


create table <tablenaame> (
<column 1><data type>[<size>] [not null] [unique] [<column constraint>],
.........
<column n><data type>[<size>] [not null] [unique] [<column constraint>],
[<table constraint(s)>]
);
For each column, a name and a data type must be specified and the column name must be unique
and valid identifier within the table definition. Column definitions are separated by comma.
Uppercase and lowercase letters make no difference in column names, the only place where upper-
case and lower-case letters matter are strings comparisons. A not null Constraint means that the
column cannot have null value, that is a value needs to be supplied for that column. The keyword
unique specifies that no two tuples can have the same attribute value for this column.
Operators in SQL:
The following are the commonly used operators in SQL

1. Arithmetic Operators +, -, *, /
2. Relational Operators =, <, >, <=, >=, <>(not equal to)
3. Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
Relational Operators are used when two values are to be compared and
Logical operators are used to combine more than one search conditions in the WHERE Clause in
SQL.
Constraints:
65
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints
come in play whenever we try to insert, delete or update a record in a relation.

1. NOT NULL- ensures that we cannot leave a column as null.


2. UNIQUE – ensures that the values under that column are always unique
3. PRIMARY KEY- ensures that a column cannot have duplicate or null values
4. CHECK – limits the values that can be inserted into a column of a table.
5. DEFAULT- used to specify default value to a column of a table.
Examples: CREATE TABLE student (
Roll_no number(3) primary key,
Name varchar(25) not null,
Class varchar(10),
Marks number(3) check(marks>0),
City varchar(25) );

Data Modifications in SQL

After a table has been created using the create table command, tuples can be inserted into the table,
or tuples can be deleted or modified.
INSERT Statement
The simplest way to insert a tuple into a table is to use the insert statement
insert into <tablename> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);
INSERT INTO student VALUES(101,'Rohan','XI',400,'Jammu');
INSERT INTO student VALUES(val1,val2, ………),(val1,val2,…….),(val1,val2,…….);

Roll_no Name Class Marks City


101 Rohan XI 400 Jammu
102 Aneeta Chopra XII 390 Udhampur
103 Pawan Kumar IX 298 Amritsar
104 Rohan IX 376 Jammu
105 Sanjay VII 240 Gurdaspur
113 Anju Mahajan VIII 432 Pathankot
Queries:

To retrieve information from a database we can query the databases. SQL SELECT statement is
used to select rows and columns from a database/relation.
SELECT Command

This command can perform selection as well as projection.


Selection: This capability of SQL can return you the tuples form a relation with all the attributes.
Projection: This is the capability of SQL to return only specific attributes in the relation.
* SELECT * FROM student; - command will display all the tuples in the relation student
* SELECT * FROM student WHERE Roll_no<=102;
66
The above command display only those records whose Roll_no less than or equal to 102.
Select command can also display specific attributes from a relation.
* SELECT name, class FROM student;
The above command displays only name and class attributes from student table.
* SELECT count(*) AS “Total Number of Records” FROM student;
Display the total number of records with title as “Total Number of Records” i.e an alias
We can also use arithmetic operators in select statement, like
* SELECT Roll_no, name, marks+20 FROM student;
* SELECT name, (marks/500)*100 FROM student WHERE Roll_no> 103;
Selecting Columns

The columns to be selected from a table are specified after the keyword select. This operation is
also called projection. For example, the query select LOC, DEPTNO from DEPT; lists only the
number and the location for each tuple from the relation DEPT. If all columns should be selected,
the asterisk symbol “*” can be used to denote all attributes. The query
Select * from EMP;

retrieves all tuples with all columns from the table EMP. Instead of an attribute name, the select
clause may also contain arithmetic expressions involving arithmetic operators etc.
Eliminating Duplicate/Redundant data
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g. SELECT DISTINCT name FROM student;
The above command returns non-repeating values for name column
Selecting a specific Rows (Where)
it will select only those rows which fulfill the specific criteria.
SELECT <column name>[, <column name>]
FROM <table name>
WHERE <condition>
Eg:- SELECT empno, name From Emp WHERE sal>50000
Relational Operators
compare two values =,>,<,>=,<=,<>
Eg:- SELECT * FROM emp WHERE Dept=20
Logical operator

i) OR :-if one of both condition is true it will select row and show
ii) AND:- if both condition is true then only it will select row and show it
iii) NOT:- show details of those who does not fulfil the criteria
Conditions based on a range
SQL provides a BETWEEN operator that defines a range of values that the column value must fall
for the condition to become true.

67
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWENN 100 AND 103;

The above command displays Roll_no and name of those students whose Roll_no lies in the range
100 to 103 (both 100 and 103 are included in the range).
Conditions based on a list

To specify a list of values, IN operator is used. This operator selects values that match any value in
the given list.
e.g. SELECT * FROM student WHERE city IN (‘Jammu’,’Amritsar’,’Gurdaspur’);

The above command displays all those records whose city is either Jammu or Amritsar or
Gurdaspur.
Conditions based on Pattern
SQL provides two wild card characters that are used while comparing the strings with LIKE operator.
a. percent(%) Matches any string
b. Underscore(_) Matches any one character
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “%3”;

displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “1_3”;

displays those records whose Roll_no starts with 1 and second letter may be any letter but ends
with digit 3.
ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted order).

The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
e.g. SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending order.

GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple
records and group the results by one or more columns.
The syntax for the GROUP BY clause is:

68
SELECT column1, column2, ...column_n, aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column_n;

Aggregate functions (Group Functions or multi row functions)-


SUM() : returns the sum of values of the given column,
MAX() : returns the maximum value of the given column.
MIN() : returns the minimum value of the given column.
AVG() : returns the average value of the given column.
COUNT(*): returns the number of records present in the table
COUNT(<COLUMN NAME>): returns the number of values present in the given column.
SELECT name, COUNT(*) as "Number of employees"FROM studentGROUP BY city;
HAVING Clause

The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:

SELECT column1, column2, ...column_n, aggregate_function (expression)


FROM tables
WHERE predicates
GROUP BY column1
HAVING condition1 ... condition_n;
e.g SELECT SUM(marks) as "Total marks"
FROM student
GROUP BY department
HAVING SUM(sales) > 1000;

Note: select statement can contain only those attributes which are already present in the
group by clause.
JOINS :
Join is a query which fetches the data from multiple tables. There are 4 types of joins.
1.Equi Join :-Which will fetch data from multiple tables when a common attribute is
available among the tables.
E.X 1:-Select ename, deptno, loc from EMP, DEPT where EMP.deptno=DEPT.deptno;
2.Non-Equi Join:- Which will fetch data from multiple tables when no common
attribute is available among the tables.
Select ename, deptno, sal,grade from EMP, SALGRADE where EMP.sal between
SALGRADE .losal and SALGRADE .hisal ;
69
SQL Functions:

SQL provide large collection of inbuilt functions also called library functions that can be used directly
in SQL statements.

1. Mathematical functions
 Sum(): to find sum total value of a given attribute.
Select SUM(sal) "total" from emp;

 Max() : Returns the maximum value of the expression


Select MAX(sal) "Maximum" from emp;

 Min(): Returns the Minimum value of the expression


Select MIN(hiredate) "Minimum" from emp;

 Avg() : returns average value of a group of records for one attribute


Select avg(sal) "Average" from emp;

 Count() : Returns the number of rows in the query


Select count(*) "Count" from emp;
2. String functions
• upper(<string>) takes a string and converts any letters in it to uppercase, e.g., DNAME
= upper(DNAME) (The name of a department must consist only of upper case letters.)
• lower(<string>) converts any letter to lowercase,
•mid(<string>,n [,m]) clips out a m character piece of <string>, starting at position n.
• length(<string>) returns the length of the string.
• substr(<string>, n [, m]) clips out a m character piece of <string>, starting at position n.
Delete
All or selected tuples can be deleted from a table using the delete command:
delete from <tablename> [where <condition>];

If the where clause is omitted, all tuples are deleted from the table. An alternative command for
deleting all tuples from a table is the truncate table <table> command. However, in this case, the
deletions cannot be undone.
Example:
Delete all projects (tuples) that have been finished before the actual date (system date):
delete from PROJECT where PEND <sysdate;
Note:-sysdate is a function in SQL that returns the system date.
Updates
For modifying attribute values of (some) tuples in a table, we use the update statement:
update<table> set <column i> = <expression i>, . . . , <column j> = <expression j>
70
[where<condition>];
typically, however, only a (small) portion of the table requires an update.
Examples:

• The employee JONES is transfered to the department 20 as a manager and his salary is
increased by 1000:
update EMP set JOB = ’MANAGER’, DEPTNO = 20, SAL = SAL +1000
where ENAME = ’JONES’;
• All employees working in the departments 10 and 30 get a 15% salary increase.
update EMP set SAL = SAL* 1.15 where DEPTNO in (10,30);
In such a case we have a <query> instead of an <expression>.
ALTER TABLE Command

In SQL if we ever need to change the structure of the database then ALTER TABLE command is
used. By using this command, we can add a column in the existing table, delete a column from a
table or modify columns in a table.
Adding a column

ALTER TABLE table_name


ADD column_name datatype;
e.g ALTER TABLE student ADD(Address varchar(30));
The above command add a column Address to the table atudent.
Adding a Primary Key
ALTER TABLE table_name
ADD Primary key (< column_name>);
e.g ALTER TABLE student ADD primary key (admno );
Removing a column

ALTER TABLE table_name


DROP COLUMN column_name;

e.g ALTER TABLE Student


DROP COLUMN Address;
The column Address will be removed from the table student.
Modifying a column
ALTER TABLE table_name
MODIFY col_name datatype(size) [constraint];
e.g. ALTER TABLE Student modify name varchar(30);
the above command will increase the size of the column name of student table.

71
DROP TABLE Command
Sometimes you may need to drop a table which is not in use. DROP TABLE command is used to
Delete / drop a table permanently.
The general syntax of this command is:-
DROP TABLE <table_name>;
e.g DROP TABLE student;
This command will remove the table student from the database.
____________________________________________________________________
Questions & Answers
1 Mark Questions (MCQ)
1, ______________command is used to change table structure in SQL.
(A) update (B) change (C) alter (D) modify
2. Which of the following commands will remove the entire database from MYSQL?
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
3._________ is a non-key attribute, whose values are derived from the primary key of some
other table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
4.The SELECT statement when combined with clause, returns records without repetition.
(A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULL
5. Which function is used to display the total number of records from a table in a database?
(A) total() (B) total(*) (C) return(*) (D) count(*)
6.Which of the following is not part of a DDL query?
(A) DROP (B) MODIFY (C) DISTINCT (D) ADD
7.Which statement in MySql will display all the tables in a database?
(A) SELECT * FROM TABLES; (B) USE TABLES;
(C) DESCRIBE TABLES; (D) SHOW TABLES;
8.Which of the following is a valid sql statement?

(A) ALTER TABLE student SET rollno INT(5);


(B) UPDATE TABLE student MODIFY age = age + 10;
(C) DROP FROM TABLE student;
(D) DELETE FROM student;

72
9. Which command is used to remove a column from a table in SQL.
(a) update (b)remove (c) alter (d)delete
10. Which of the following ignores the NULL values in SQL?
(a) Count(*) (b) count() (c) total(*) (d) None of these

11. Which of the following commands will be used to select a particular database named “Student”
from MYSQL Database?

(A) SELECT Student;


(B) DESCRIBE Student;
(C) USE Student;
(D) CONNECT Student;
12. An attribute in a relation is a foreign key if it is the key in any other relation.

(A) Candidate Key


(B) Foreign Key
(C) Primary Key
(D) Unique Key
13. Which statement in SQL allows to change the definition of a table is
(a) Alter (b) Update. (c) Create (d) select
14. Which of the following is a DML command?
(a) CREATE (b) ALTER (c) INSERT (d) DROP
15. Which function is used to count the non-null number of records from a table in a database?
(A) sum(*) (B) count(*) (C) count(column_name) (D)return(*)
16. Which one of the following is a TCL command?
(A) INSERT (B) COMMIT (C) SELECT (D) DROP
17. ________command is used to change the size of a column in an existing table EMP.
a) update b) remove c) alter d)drop
18. Which of the following commands will delete rows from a table ?
a) DELETE b) DROP c) REMOVE d) ALTER
19. An alternate key is a_____________ , which is not the primary key of the table.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key
20. A relation can have only one_______key and one or more than one_____keys.

(A) PRIMARY, CANDIDATE (C) CANDIDATE,ALTERNATE


(B) CANDIDATE, PRIMARY (D) ALTERNATE, CANDIDATE
21. Which is known as range operator in MySQL?

73
(a) IN (b) BETWEEN (c) IS (d) DISTINCT

22. The SELECT statement when combined with _______clause, returns records in sorted
order.
(a) SORT (b) ARRANGE (c) ORDER BY (d) SEQUENCE
22. Which of the following constraint is used to prevent a duplicate value in a record?
(a) Empty (b) check (c) primary key (d) not null
23. ________keyword is used to obtain unique values in a SELECT query
(A) UNIQUE B) DISTINCT C) SET D) HAVING
Answers:

Que. Ans Que. Ans Que. Ans


1 C 9 C 17 C
2 B 10 B 18 A
3 C 11 C 19 C
4 A 12 C 20 A
5 D 13 A 21 B
6 C 14 C 22 C
7 D 15 C 23 B
8 D 16 B

___________________________________________________________________
2 Marks Questions
1. Differentiate between CHAR() and VARCHAR().
Ans.

CHAR VARCHAR
CHAR datatype is used to store VARCHAR datatype is used to store character
character strings of fixed length strings of variable length

In CHAR, If the length of the string In VARCHAR, If the length of the string is less than the
is less than set or fixed-length then it set or fixed-length then it will store as it is without
is padded with extra memory space. padded with extra memory spaces.

CHAR stands for “Character” VARCHAR stands for “Variable Character”

Storage size of CHAR datatypes is The storage size of the VARCHAR datatype is equal to
equal to n bytes i.e. set length the actual length of the entered string in bytes.

We should use the CHAR datatype We should use the VARCHAR datatype when we
when we expect the data values in a expect the data values in a column are of variable
column are of the same length. length.

74
CHAR takes 1 byte for each VARCHAR takes 1 byte for each character and
character some extra bytes for holding length information

Better performance than VARCHAR Performance is not good as compared to CHAR

2. Differentiate between WHERE and HAVING with appropriate examples.

Ans. The difference between WHERE and HAVING clause is that WHERE condition
is applicable on individual rows whereas HAVING condition are applicable on
groups as formed by GROUP BY clause.
3. Differentiate between COUNT(column name) AND COUNT(*) with appropriate examples.

Ans. COUNT(*) will count all the rows in the table, including NULL values. On the other hand,
COUNT(column name) will count all the rows in the specified column while excluding NULL
values.

4. What do you understand by the terms Degree, cardinality of a Relation? Explain with an
example.
Degree: No. of columns(attribute) of a table
Cardinality: No.of rows( Tuples) of a table
Ex: EMP Table

Employee Id Name Sales JobId


E1 Sumit Sinha 110000 102
E2 Vijay SinghTomar 130000 101
E3 Ajay Rajpal 140000 103
Degree of EMP table is 4 and cardinality is 3.

5. What do you understand by the terms PRIMARY KEY and UNIQUE KEY of a relation in
relational database?

Ans. PRIMARY KEY: The PRIMARY KEY uniquely identifies each record in a table. Primary
keys contain UNIQUE values, and cannot contain NULL values. A table can have only ONE
primary key in the table, this primary key can consist of single or multiple columns (fields).

UNIQUE KEY: It Uniquely determines a row which isn’t primary key. It can accept NULL
values. More than one Unique key can be defined in one table.
6. What are constraints in SQL? Give two examples.

Ans. SQL constraints are used to specify rules o for the data in a table. Constraints are used
to limit the type of data that can go into a table. This ensures the accuracy and reliability
of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
Examples
NOT NULL, UNIQUE, PRIMARY KEY, CHECK etc.
75
7. What are aggregate functions in MySql? Give their names along with their use.

Ans. Aggregate functions are also known as group functions. It works on more than one row in a
table. Various aggregate functions in MySql are- sum(), min(), max(),avg() and count().
8. List various DDL and DML commands available in MySql
Ans. DDL commands- CREATE, ALTER, DROP
DML commands- INSERT, UPDATE, DELETE, SELECT
9. Differentiate between DDL and DML? with one Example each.

Ans. DDL- Data definition language. Consists of commands used to modify the metadata of a
table.
For Example- create table, alter table, drop table
DML-Data manipulation language Consist of commands used to modify the data of a table.
For Example- insert, delete, update
10. Write two points of difference between ALTER and UPDATE command in SQL.

ALTER UPDATE
It is a DDL command. It is a DML command.
ALTER Command is used toadd, UPDATE Command is used toupdate
delete, modify the attributes of the existing records in a database.
relations
(tables) in the database.
ALTER Command by default initializes UPDATE Command setsspecified
values of all the tupleas NULL. values in the command to the tuples.
This command make changes This command makes changes
with table structure. with data inside the table.
Ans.

11. Mention two differences between a PRIMARY KEY and a UNIQUE KEY.
Ans.

PRIMARY KEY UNIQUE KEY


There can be only one primary key in a There can be more than one unique
table keys in a table
The primary key cannot have null values Unique can have null values

12. What is the difference between a Candidate Key and an Alternate Key

CANDIDATE KEY ALTERNATE KEY


All the attributes in a relation that have All the leftover candidate keys after
the potential to become a selecting the primary key
Primary key

76
13. 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.
Ans: Pno
(ii) What is the degree and cardinality of the above table?
Ans: Degree : 4 , Cardinality : 5
14 How is equi-join different from natural-join? Give example.
Ans: Equi-join : It is a sql join where we use the equal sign as the comparison operator while
specifying the join condition. In this, the common column from both the tables will
appear twice in the output.
Natural join : It is similar to Equi-join but only one of the identical columns exist in the
output. Example :
select * from student, course where course.cid = student.cid; (Equi-join) select *
from student natural join course where course.cid = student.cid; (Natural join)
15 Differentiate between an Attribute and a Tuple in a Relational Database
with suitable example.
Ans: Attributes / Field: Columns of the table (Relation) is called as attributes.
Tuple: Rows of the table (relation) is called as a tuple (record).

16 Write the full forms of TCL, DML and DDL.


Ans: TCL – Transaction Control Language
DDL – Data Definition Language
DML- Data Manipulation Language.

______________________________________________________________________

03 Marks Questions
1. Observe the following table and answer the question:
TABLE: VISITOR
VisitorID VisitorName ContactNumber
V001 ANAND 9898989898
V002 AMIT 9797979797
V003 SHYAM 9696969696
V004 MOHAN 9595959595
1. Which command will be used to see the Structure of a table Visitor ?
2. What is the degree and cardinality of the table?
77
3. Insert the following data into the attributes VisitorID, VisitorName and ContactNumber
respectively in the given table VISITOR.
VisitorID = “V004”, VisitorName= “VISHESH” and ContactNumber=9907607474
Ans: 1. DESCRIBE VISITOR;
2. Degree= 3, Cardinality=4
3. insert into VISITOR values(“V004”, “VISHESH”,9907607474)
2. Write query for the following:

2. Find average salary in the table.


Ans. SELECT AVG(SAL)FROM EMPLOYEE;

3. Display number of employees designation wise .


Ans. SELECT Designation ,COUNT(Designation)FROM Employee GROUP BY Designation;

4. Display number of records along-with sum of salaries for each Individual Designation
Where Number of records are more than 1.

Ans: SELECT Designation,COUNT(Designation),SUM(sal) FROM Employee GROUP BY


Designation HAVING COUNT(Designation)>1;

3. Write the output of the sql Queries that follows:


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

1. Select SUM(STIPEND) from GRADUATE WHERE div=2;


2. Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
3. Select COUNT(distinct SUBJECT) from GRADUATE;
Answer-
1. 63
78
2. 800
3. 4

5. Write the output of the sql Queries that follows:


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. SELECT DISTINCT SenderCity from Sender;
b. SELECT A.SenderName, B.RecName From Sender A, Recipient B
Where A.SenderID = B.SenderID AND B.RecCity =’Mumbai’;
c. SELECT RecName, RecAddress From Recipient
Where RecCity NOT IN (‘Mumbai’, ‘Kolkata’) ;
Answer: a. SenderCity
Mumbai
New Delhi
b. A.SenderName B.RecName
R Jain H Singh
S Jha P K Swamy
c. RecName RecAddress
S Mahajan 116, A Vihar
S Tripathi 13, BID, Mayur Vihar

6. Write the output of the sql Queries that follows:


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
TDAT
NO NAME E 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
79
• KM is Kilometer travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Travel Date
(i) SELECT COUNT (*), CODE FROM TRAVEL GROUP BY CODE HAVING COUNT(*)>1;
(ii) SELECT DISTINCT CODE FROM TRAVEL;
(iii) SELECT A.CODE,NAME,VTYPE FROM TRAVEL A, VEHICLE B WHERE
A.CODE=B.CODE AND KM<90;

Ans: i. count(*) code

2 102
ii. DISTINCT CODE
101
103
102
104
105
iii. Code Name Vtype
104 Ahmed Khan Car
105 Raveena Suv

6. Write the output of the sql Queries that follows:


MobileMaster
M_Id M_Company M_Name M_Price M_Mf_Date
MB001 Samsung Galaxy 4500 2013-02-12
MB003 Nokia N1100 2250 2011-04-15
MB004 Micromax Unite3 4500 2016-10-17
MB005 Sony XperiaM 7500 2017-11-20
MB006 Oppo SelfieEx 8500 2010-08-21
MobileStock
S_Id M_Id M_Qty M_Supplier
S001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile Store
S004 MB006 150 A-one Mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Centre

(i) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;


(ii) SELECT MAX(M_Mf_Date), MIN(M_Mf_Date) FROM MobileMaster;
(iii) SELECT AVG(M_Price) FROM MobileMaster;

Ans: i. M_Id SUM(M_Qty)


MB004 450
MB003 400
MB001 300
MB006 200

ii.
MAX(M_Mf_Date) MIN(M_Mf_Date)
2017-11-20 2010-08-21
iii. 5450
80
_______________________________________________________________________
04 Marks Questions
1. Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) .
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)
Answer
(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;

2. Consider the following tables FACULTY and COURSES. Write SQL commands for the
statements (i) to (iv) .
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).
iii) To display details of those courses which are taught by ‘Sulekha’ in descending order
of courses ?
81
iv) Select COUNT(DISTINCT F_ID) from COURSES;
Answer
(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

3. Write SQL Command for (a) to (d)


TABLE : GRADUATE
S.N NAME STIPEND SUBJECT AVERAGE DIV
O
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
Answer-
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);

4 Consider the following tables Sender and Recipient. Write SQL commands for the
statements (i) to (iv).
Sender
SenderID SenderNam SenderAddress Sendercity
e
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
i. To display the names of all Senders from Mumbai

82
ii. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every
Recipient
iii. To display Recipient details in ascending order of RecName
iv. To display number of Recipients from each city
Answer-
i.SELECT sendername from Sender where sendercity=’Mumbai’;
ii.Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress
from Sender S, Recepient R
where S.SenderID=R.SenderID ;
iii.SELECT * from Recipent ORDER By RecName;
iv.SELECT RecCity, COUNT( *) from Recipient Group By RecCity;

5 Write SQL queries for (i) to (iv) 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
TDAT
NO NAME E 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.
Answer-
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 >= ‘2015-04-01’ AND TDATE <= ‘2015-12-31’;
OR
SELECT NO, NAME from TRAVEL WHERE TDATE BETWEEN ‘2015-04-01’ AND
‘2015-12-31’;
iv. SELECT * FROM TRAVEL WHERE KM > 100 ORDER BY NOP;

83
6 Consider the following relations MobileMaster & MobileStock:-
MobileMaster
M_Id M_Company M_Name M_Price M_Mf_Date
MB001 Samsung Galaxy 4500 2013-02-12
MB003 Nokia N1100 2250 2011-04-15
MB004 Micromax Unite3 4500 2016-10-17
MB005 Sony XperiaM 7500 2017-11-20
MB006 Oppo SelfieEx 8500 2010-08-21
MobileStock
S_Id M_Id M_Qty M_Supplier
S001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile Store
S004 MB006 150 A-one Mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Centre
Write the SQL query for questions from (i) to (iv)
i. Display the Mobile company, Mobile name & price in descending order of their
manufacturing date.
ii. List the details of mobile whose name starts with „S‟.
iii. Display the Mobile supplier & quantity of all mobiles except „MB003‟.
iv. To display the name of mobile company having price between 3000 & 5000.
Answer-
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 BETWEEN 3000
AND 5000;

7 Write SQL queries for (i) to (iv) 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.

84
(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.
Answer-
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;

8 A departmental store MyStore is considering to maintain their inventory using SQL


to store the data. As a database administer,
Name of the database – mystore
Name of the table - STORE
The attributes of STORE are as follows:
ItemNo - numeric
ItemName – character of size 20
Scode - numeric
Quantity – numeric
Table :
STORE
ItemNo ItemName Scode Quantit
y
2005 Sharpener Classic 23 60
2003 Ball Pen 0.25 22 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 21 250
2001 Eraser Small 22 220
2004 Eraser Big 22 110
2009 Ball Pen 0.5 21 180

a) Identify the attribute best suitable to be declared as a primary key,


b) Write the degree and cardinality of the table STORE.
c) Insert the following data into the attributes ItemNo, ItemName and SCode respectively
in the given table STORE. ItemNo = 2010, ItemName = “Note Book” and Scode = 25
d) Abhay wants to change the Quantity of ItemNo 2003 by 70, Write a query for this.
e) Which command will be used to count the total rows of table.
Ans: a) ItemNo
b) Degree = 4 Cardinality = 7
c) INSERT INTO store (ItemNo,ItemName,Scode) VALUES(2010, “Note Book”,25);
d) Update STORE set Quantity =70 Where ItemNo=2003
e) count(*)
9 Write the outputs of the SQL queries (i) to (iii) based on the relations
Stationary and Consumer given below:
Table: Stationary
S_ID StationaryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer

85
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02

i. SELECT count(DISTINCT Address) FROM Consumer;


ii. SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary
GROUP BY Company;
iii. SELECT Consumer.ConsumerName, Stationary.StationaryName,
Stationary.Price FROM Stationary, Consumer
WHERE Consumer.S_ID = Stationary.S_ID;
Ans: (i) 2
(ii) Company Max(Price) Min(Price) Count(*)
ABC 15 10 2
XYZ 7 6 2
CAM 5 5 1

(iii) Good Learner Pencil 5


Write Well Gel Pen 15
Topper Dot Pen 10
Write & Draw Pencil 6
10 Consider a database LOANS and Write SQL queries for (i) to (iii)
Table: LOANS

ACNo CUST_NAME Amount Installments Int_Rate Start_Date Interest


1 R.K. Gupta 300000 36 12.00 19-07-2009 1200
2 S.P. Sharma 500000 48 10.00 22-03-2008 1800
3 K.P. Jain 300000 36 NULL 08-03-2007 1600
4 M.P. Yadav 800000 60 10.00 06-12-2008 2250
5 S.P. Sinha 200000 36 12.50 03-01-2010 4500
6 P. Sharma 700000 60 12.50 05-06-2008 3500
7 K.S. Dhall 500000 48 NULL 05-03-2008 3800

(i) Display the sum of all Loan Amounts whose Interest rate is greater than 10.
(ii) Display the Maximum Interest from Loans table
(iii) Display the count of all loan holders whose names are ending with „Sharma‟
Ans: (i) Select sum(Loan_Amount) from LOANS where Interest >10;
(ii) Select max(Interest) from LOANS;
(iii) Select count(*) from LOANS where Cust_Name Like “%Sharma‟;

11 Consider the tables given below.


Table : STOCK
Itcode Itname Dcode Qty UnitPrc StkDate
444 Drawing Copy 101 10 21 31-June-2009
445 Sharpener Camlin 102 25 13 21-Apr-2010
450 Eraser Natraj 101 40 6 11-Dec-2010
452 Gel Pen Montex 103 80 10 03-Jan-2010
86
457 Geometry Box 101 65 65 15-Nov-2009
467 Parker Premium 102 40 109 27-Oct-2009
469 Office File 103 27 34 13-Sep-2010

Table : DEALERS
Dcode Dname Location
101 Vikash Stationers Lanka Varanasi
102 Bharat Drawing Emporium Luxa Varanasi
103 Banaras Books Corporation Bansphatak Varanasi

To display all the information about items containing the word “pen” in the field
(i)
Itname in the table STOCK.
(ii) List all the itname sold by Vikash Stationers.
(iii) List all the Itname and StkDate in ascending order of StkDate.
(iv) List all the Itname, Qty and Dname for all the items for the items quantity more than 40.
(v) List all the details of the items for which UnitPrc is more than 10 and <= 50.
Ans: (i) SELECT * FROM STOCK WHERE Itname LIKE “%pen%”;
(ii) SELECT DISTINCT(Itname) FROM STOCK,
DEALERS WHERE STOCK.Dcode= DEALERS.Dcode and dname=’
Vikash Stationers’;
(iii) SELECT Itname, StkDate FROM STOCK ORDER BY StkDate;
(iv) SELECT Itname, Qty, Dname FROM STOCK,
DEALERS WHERE STOCK.Dcode= DEALERS.Dcode and qty>40;
(v) SELECT * FROM STOCK WHERE UnitPrc BETWEEN 10 AND 50;

12 Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”.
Write SQL commands for the statements (i) to (iv).
Table: BOOKS
BID BNAME AUNAME PRICE TYPE QTY
COMP11 LET US C YASHWANT 350 COMPUTER 15
GEOG33 INDIA MAP RANJEET P 150 GEOGRAPHY 20
HIST66 HISTORY R BALA 210 HISTORY 25
COMP12 MY FIRST C VINOD DUA 330 COMPUTER 18
LITR88 MY DREAMS ARVIND AD 470 NOBEL 24

Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15

(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been
issued.
Ans: (i) select BNAME,AUNAME,PRICE from BOOKS where TYPE=’COMPUTER’;
(ii) Update BOOKS set PRICE = PRICE+50 where TYPE=’HISTORY’;
87
(iii) Select * from BOOKS order by PRICE asc;
(iv) Select BID,BNAME, QTY_ISSUED from BOOKS,ISSUED where
BOOK.BID=ISSUED.BID;

13 Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation
of the table, she has entered data of 8 items in the table.
Table : STOCK
stockid dopurchase name make Price
101 2020-07-06 CPU ACER 12000
102 2020-09-01 CPU ACER 12750
103 2020-09-01 MONITOR ACER 7500
104 2016-08-03 PROJECTOR GLOBUS 37250
105 2016-05-26 VISUALIZER GLOBUS 17500
106 2020-07-23 WIFI RECEIVER ZEBION 450
107 2015-02-18 PRINTER LEXMARK 38000
108 2020-07-23 HEADPHONE BOAT 750
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If three columns are added and 5 rows are deleted from the table stock, what will be
the new degree and cardinality of the above table?
(iii) Write the statements to:
(a) Insert the following record into the table
Stockid - 201, dateofpurchase – 18-OCT-2022, name – neckphone
Make – BoAT, price - 500
(b) Decrease the price of stock by 5% whose were purchased in year2020
(iii) Write the statements to:
(a) Delete the record of stock which were purchased before year 2015.
(b) Add a column STATUS in the table with datatype as char with 1 characters
Ans: i. stockid
ii. degree = 8, cardinality = 3
iii. (a) insert into stock values(201,’2022-10-18’,’neckphone’,’boat’,500);
(c) update stock set price=price*0.95 where year(dopurchase)=2020;

OR
(a) delete from stock where year(dopurchase) < 2015;
(b) alter table stock add column STATUS char(1);

14 Based on the given set of tables write answers to the following questions.
Table: flights
flightid model company
10 747 Boeing
12 320 Airbus
15 767 Boeing
88
Table: Booking
ticketno passenger source destination quantity price Flightid
10001 ARUN BAN DEL 2 7000 10
10002 ORAM BAN KOL 3 7500 12
10003 SUMITA DEL MUM 1 6000 15
10004 ALI MUM KOL 2 5600 12
10005 GAGAN MUM DEL 4 5000 10

a) Write a query to display the passenger, source, model and price for all bookings whose
destination is KOL.
b) Identify the column acting as foreign key and the table name where it
is present in the given example
Ans: a) SELECT passenger, source, model, price FROM booking, flights
WHERE bookings.flightid = flights.flightid AND destination='KOL';
b Flightid in the bookings table is the foreign key.

15 Write the outputs of the SQL queries (i) to (iii) based on the given relations :
Table: Stationary

S_ID StationaryName Company Price


DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15

Table: Consumer
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02

1. SELECT count (DISTINCT Address) FROM Consumer;


2. SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary GROUP
BY Company;
3. SELECT Consumer.ConsumerName, Stationary.StationaryName, Stationary.Price FROM
Stationary, Consumer WHERE Consumer.S_ID = Stationary.S_ID;
Ans: 1. count(DISTINCT Address)
Delhi
Mumbai
2 Company MAX(Price) MIN(Price) COUNT(*)
ABC 15 10 2
XYZ 7 6 2
CAM 5 5 1
3 Consumer.ConsumerName Stationary.StationaryName Stationary.Price
Topper Dot Pen 10

Write & Draw Pencil 6

Good Learner Pencil 5

Write Well Gel Pen 15


89
16. Write SQL Commands for the following queries based on the
relations PRODUCT and CLIENT given below.
Table: Product
P_ID ProductName Manufacturer Price ExpiryDate
TP01 Talcum Powder LAK 40 2011-06-26
FW05 Face Wash ABC 45 2010-12-01
BS01 Bath Soap ABC 55 2010-09-10
SH06 Shampoo XYZ 120 2012-04-09
FW12 Face Wash XYZ 95 2010-08-15
Table: Client
C_ID ClientName City P_ID
1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL
1. To display the ClientName and City of all Mumbai- and Delhi-based clients in Client table.
2. Increase the price of all the products in Product table by 10%.
3. To display the ProductName, Manufacturer, ExpiryDate of all the products that
expired on or before ‘2010-12-31’.

4. To display C_ID, ClientName, City of all the clients and their corresponding
ProductName sold.
Ans: 1. Select ClientName, city from Client where city in(‘Delhi’,’Mumbai’);
2. update Product set Price = Price + Price*0.1;
3. select ProductName, Manufacturer, ExpiryDate from Product
where ExpiryDate<=’2010-12-31’;
4. Select C_ID, ClientName, City ,ProductName from Client, Product
Where Product.P_ID=Client.P_ID;

90

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