Study Material Based on the Latest CBSE Syllabus
and NCERT Textbooks
Together with®
omputer Science
with Python Language
Authors
Naveen Gupta Shailender Gupta
MPhil, MCA, M.Com, DNIT M.Sc Computer Science
‘Winner of National ICT Award, 2019 Microsoft Certified Professional
PGT Computer Science Java Certified Programmer
Teacher Mentor and Trainer
Adobe Creative Educator
Microsoft Certified Educator
Microsoft Technical Associate
(Python)
CLASS
12
TERM -2
RACHNA
SAGARSYLLABU
tional Thinking and Programming ~ 2
Unit 1: Computat
Stack, operations on stack (push & pop). implementation of stack using list
+ Data Structure:
Unit tl; 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 communica-
tion 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, Ethemet card, R145, 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/P, 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 Ill: 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 Lan-
guage, 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
(6)Interface of python with an SQL database: connecting SQL with Python, performing insert, up-
date, delete queries using cursor, display data by using fetchone(), fetchall(), rowcount, creating,
database connectivity applications
Term-2 |
S Marks Jerm-!
No Fotal 30) (15 Marks) | (15 Marks) |
Lab Test: Z 6 2
1. Python program _ ___}
2. 3 SQL Queries based on one/two table(s), 2 output le i 4
|___questions based on SQL queries
| Report file:
| Term — 1 : Minimum 15 Python programs based on Term - 1
"Syllabus
Term - 2:
| Minimum 3 Python programs based on Term-2 Sylla- 7 7 5
bus
|+ SQL Queries ~ Minimum 5 sets using one table / two
tables.
+ Minimum 2 programs based on Python - SQL
| connect fs a as Pes
| Project (using concepts learnt in Classes 11 and 12)
Term ~ | : Synopsis of the project to be submitted by the
students (documentation only, may not submit the code
3 | during Term - 1) 8 3 3
6.
t
Term - 2 : Final coding + Viva voce
| (Student will be allowed to modify their Term 1 docu-
_| ment and submit the final executable code.)
4 | Viva voce 3
Suggested Practical List
erm-2
Python Programming
Write a python program to implement a stack using list.
Database Management
Write a python program to implement a stack using list
Create a student table and insert data. Implement the following SQL commands on the student
table:
* ALTER table to add new attributes / modify data type / drop attribute
* UPDATE table to modify data
(2)+ ORDER By to display data in ascending descending order
+ DELETE to remove tuple(s)
+ GROUP BY and find the min, max. sum, count and average
+ Joining of two tables.
* Similar exercise may be framed for other cases.
+ Integrate SQL with Python by importing suitable module
Suggested Reading Material
+ NCERT Textbook for COMPUTER SCIENCE (Class XII)
+ Support Materials on the CBSE website
8. Project
+ The aim of the class project is to create something that is tangible and useful using Python file
handling/ Python-SQL connectivity. This should be done in groups of two to three students and
should be started by students at least 6 months before the submission deadline. The aim here is
to find a real world problem that is worthwhile to solve.
+ Students are encouraged to visit local businesses and ask them about the problems that they are
facing. For example, if a business is finding it hard to create invoices for filing GST claims, then
students can do a project that takes the raw data (list of transactions), groups the transactions by
category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students
can be extremely creative here. They can use a wide variety of Python libraries to create user
friendly applications such as games, software for their school, software for their disabled fellow
students, and mobile applications, of course to do some of these projects, some additional learning
is required; this should be encouraged. Students should know how to teach themselves.
The students should be sensitised to avoid plagiarism and violations of copyright issues while
working on projects. Teachers should take necessary measures for this.CONTENTS
Part-I
[Important Terms and Definitions, Solved Question Bank, Practice Question Bank]
5. Data Structure-Stack - 15
7. Database Management — SQL - 61
8 MYSQL with Python Interface .. - 14
9. Computer Networks (CN) ....... - 97
Part - II
[Sample Practical Paper]
« Sample Practical Paper........ - 108
Part - UI
[Practice Papers]
* Practice Papers 1 to 3 (Solved)...... 110 - 128Qs IMPORTANT TERMS & DEFINITIONS
Q > SOLVED
* Question Bank Including
* Very Short Answer/Objective Type Questions [1 Mark]
¢ Short Answer Type Questions [2/3 Marks]
¢ Long Answer Type Questions [4 Marks]
* Competency/Case-based Questions
Q_ PRACTICE QUESTIONS
* Question Bank Including
* Very Short Answer Type Questions [1 Mark]
¢ Short Answer Type Questions [2/3 Marks]
¢ Long Answer Type Questions [4 Marks]
* Competency/Case-based Questions
Q ANSWERS TO PRACTICE QUESTIONS| |
|
| DATA STRUCTURE-STACK _
na sreeme
LEARNING OUTCOMES
After this chapter students will be able to:
+ describe the data structure along with its operations.
= understand the stack.
(SP SE SIE TS
DATA STRUCTURE USING LIST, STACKS AND QUEUES
1. Data Structure. It is a way to store a collection of arbitrary data. The data structure can be
implemented via the list, dictionary, tuple, set etc.
2. Classification of Data Structure.
2 Sse
Structure
an
Static or Fixed Dynamic
‘Structure, Structure
Non-Linear
Ds*
~~
y ’
Tree Graph
Linear DS
Linked
Sequential Lists*
Arrays Stacks Queues12 Pagecher ewith® Computer Science (Python) 12
3. Ope nson Data Structu Some of in reverse order of their arrival. The stack is
the operations that are performed on data called Last In First Out (LIFO) arrangement.
structure are as follows: Hi a Ezz
Insertion (Addition of new elements in
the list.) East
lets
Deletion (Removal of an element from Insertion eal Deletion
tee ra
Traversal (Visiting elements of a list.) Orr
Searching (Finding an element in the rrr
list.)
4. Stack. Stack means arranging one object
over another and these objects are removed
§. Operations on Stack.
Push : Insertion of a new element (from the beginning) in stack.
[Push] [4] Pushy
[Push(2)
3} Top
2 }e Top 2
[He-top 1 1
Pop : Deletion of an element(from the beginning) in stack.
5
L>LPop P42} + Pop }>L2 [Pop OJ
1
6. Conditions associated with Stack/Queue:
© Overflow condi
full or range is overfilled with values,
: It is a situation where we are not able to add new element due to memory
© Underflow condition: It is a situation where there is no element left and we still wish to
remove an element or display the list,
7. Applications of Stack. Stack can be used to reverse a word or reverse a line and it can also used
in function call routines.SOLVED QUESTION BANK
Very Short Answer Type Questions [1 Mark]
Define data structure.
\ns. It is a way to store a collection of related
data together. The data structure can be
implemented via the list, dictionary, tuple,
set ete.
2. What is LIFO?
Last In First Out.
5. What is traversal?
Accessing each element is known as traversal.
4. Name some applications of Stack.
Application of Stack are:
(a) Reverse of a String or Line.
(b) Function call routines.
(c) Backtracking
5. Alist contains LST=[10,7,9,15,12]. 8 is added
to the list. What will be the output? If
(a) LST as Stack (6) LST as Queue
Ans. (a) LST as Stack
LST = [8,10,7,9,15,12]
(6) LST as Queue
LST = [10,7,9,15,12,8]
Short Answer Type Questions [2/3 Marks]
6. Python program to check whether the list
is empty or not.|FileName:ch-datas\QU5]
Ans. A = [J
if not A:
print(“List is empty”)
Long Answer Type Questions [4 Marks]
7. Write a program to implement the stack
using list.
Ans.s=[]
Data Structure-Stack 13
print("1. PUSH\n2. POP \n3
Display")
choice-int (input ("Enter your
choice: "))
if (choice==1):
azinput("Enter any nunber :")
s.append(a)
elif. (choice==2):
if (s=-[]):
print ("Stack Empty")
else:
print ("Deleted element
is : ",s.pop())
elif. (choice=
1slen(s)
for i in range(1-1,-1,-1):
print (s[i])
):
else:
print("Wrong Input")
c=input("Do you want to continue
or not? ")
8. Write Push(Book) and Pop(Book) methods
in Python to Add a new Book and Remove
a Book from a List of Books, considering
them to act as PUSH and POP operations
of the data structure Stack.
Ans. def push(Book)
a=input("Enter any number
Book. append (a)
def pop(Book) :
if (Book==[])
print (“Stack Empty
else
print
is:",Book.pop())
(“Deleted element
Write a menu driven python program
using funtion Push(), Pop( and Display)
to implement the stack. The program will
store the name of the books.14
Ans.
Pogether wetk® Computer Science (Python)
def push(Book) :
name-input("Enter the book name")
Book. append(name)
def pop(Book) :
if Book=
print(
else:
Under Flow")
print ("Book Deleted” ,Book.pop())
def display (Book):
if Book==[]:
print ("Underflow!!!")
else:
print("Books in Stack")
1=1en(Book)
for i in range(1-1,-1,-1):
print(Book[i],
# main
Book=[]
while True:
print("\n1. Push\n2. Pop \n3. Display\
na. Exit")
ch=int(input (“Enter your choice")
if ch
push(Book)
elifch=
pop (Book)
elife!
display (Book)
else:
break
|. Write a menu driven python program
using function Push (), Pop () and Display)
to implement the stack, The program will
store the Employee details |.e. Employee
number, Employee name and Salary.
. def push(Emp)+
enozint(input ("Enter the Empolyee
Number") )
names input (“Enter the Employee Name")
sal-input("Enter the Salary")
Emp.append([eno, ename, sal})
def pop(Emp) +
if Emp=*[]:
print("Under Flow”)
else:
print("Employee
Deleted”, Emp. pop())
def display (Emp):
if Emp=-(]:
print("Underflow! !!")
else:
print("Employee record in Stack\n")
1=len(Emp)
for i in range(1-1,-1,-1):
print (Emp[i])
# main
Emp=(]
while True:
print("\nl.
n2. Pop \n3.
nu. Exit")
ch=int(input("Enter your choice”)
if ch==1:
push(Emp)
elif ch==2:
pop(Emp)
elif ch==3:
display (Emp)
else:
break
Recorg
Push
Display
: Competency/Case-based Question
11. Read the following code carefully which
is implementing the concept of STACK*
defisEmpty(STACK):
if len(STACK) =
Teturn True
else:
. return False
def pop(STACK):
if isEmpty (STACK):
return “Underflow”
else:
element = STACK.pop()
if len(STACK) == 0
top = None
else:
top =
return element
Jen(STACK) - 2
_ 4(a) How are the above two functions inter-
related?
The function isEmpty(STACK) will be
called when pop(STACK) is called
(b) What is the difference in between
STACK pop() and pop(STACK)
STACK.pop() is pre defined and
pop(STACK) is user defined
(c) What is the retum type of the function
defisEmpty (STACK)
PRACTICE QUESTIONS
Very Short Answer Type Questions [1 Mark]
Write the full form FIFO.
A list contains LST=[10,7,9,15,12]. An
element is removed. What will be the output?
If
(a) LSTas Stack (6) LST as Queue
Which method accepts two arguments
(index,element)? If the index is more than
the size, then it will insert at the end.
Data Structure-Stack 15
©» Boolean
(d) What will the pop(STACK) function
return if the stack already consist
of [‘A’’B’] at the position 0 and I
respectively
An B
(c) if len(STACK) == 0: What is the
purpose of this line in the above code:
\ns. It checks if the stack is already empty.
4. Which is a situation when there is no element
left and still wish to remove element?
Long Answer Type Questions [4 Marks]
5, Write algorithm for PUSH(insert) operation
in stack.
Write algorithm for POP(Remove) operation
in stack.
2
ANSWERS TO PRACTICE QUESTIONS
1
2
a
First in first out.
(a) LST as Stack
LST = [7,9,15,12]
(b) LST as Queue
LST = [10,7,9,15,12]
. Insert()
Underflow
. Algorithm for PUSH in stack
1, Start
2.Element = Input("Enter the value to
be added as element in Stack.")
3.Stak.append(Element) # Stak is the
mame of Stack. append() is used to
insert the
# element in the end of stack.
4, Top=Tope1
5. End.
. Algorithm for POP in stack.
Start
StakLen = len(Stak)
# len() is used to calculate the length
of the Stack.
if StakLen <=0
To check whether stack is empty or not
Print("Pop is not possible as stack is
empty")
else:
val = Stak.pop()
® pop() is used to remove the last
inserted element in Stack
top = top-1
return top
End
2DATABASE MANAGEMENT — SQL
LEARNING OUTCOMES
After going through this chapter students will be able to:
* understand RDBMS and its advantages
+ explain SQL and other related terminologies
compare and apply various keys in their relations
recognise the categories of SQL command
deploy the constraints in the table
identify the operator, clauses and functions
practice SQL commands
‘Soar eR CE RENEE AMBRE WE og ese
IMPORTANT TERMS & DEFINITIONS
z.
Data. It can be described as the raw of facts
and figures.
. Information. Processing of data into
meaningful form is called information.
. Database. Organised collection of logically
related data.
. DBMS. Data Base Management System. A
computer system that allows us to manage
Databases.
. Need for DBMS. Database provides
centralised control on its operational data.
Thus, with the help of a database
» redundancy can be reduced.
» inconsistency can be avoided.
« data integrity is maintained.
+ data can be shared.
security restrictions can be imposed.
6. Data Redundancy. Duplication (Replication)
of data is known as Data Redundancy.
7. Data Inconsistency. It is a situation/problem
where the same data is stored in two different
files in a different format.
. Data Security. Protection of data from
unauthorised persons against accidental’
intentional addition or modification or
deletion.
=
»
Data Privacy: It ensures security of data and
governs who has access to data.
10. Relation. Itis a two dimensional format which
contains rows and columns. A relation is also
known as a Table.
+ Domain. A set of unique values allowed for
@ column is known as its domain.
. Tuple. A row/record in a relation or #
horizontal subset is known as table.4. Cardinalit
18. P:
Aw © A column/ Field in a relation or
vertical subset.
Number of rows in a relation
denotes cardinality of the table.
Number of columns in a relation
16. SQL: Stands for Structured Query Language,
Itisa standard programming language used to
store, retrieve and manage data in relational
databases.
. Candidate Key: A column or a set of columns
which uniquely identify a row in a relation.
A table/relation can have multiple candidate
keys.
ry Key: A column or a set of columns
which can uniquely identify a row in a
relation.
. Alternate key: A candidate key which is nota
primary key but can serve as a primary key.
Foreign Key: It is a column that references
the primary key of another table.
. DDL: Stands for Data Definition Language.
It is a category of SQL command which is
used to manipulate database objects like table
structure. Examples of DDL commands are:
Create Table, Alter Table, Drop Table. Create
23
23.
24,
25.
26.
Database Management-SQL 17
UML. Stands for Data Manipulation Language.
It is a category of SQL command which is
used to manipulate the data. Examples of
DML commands are Insert, Delete, Update
and Select.
Arithmetic Operator are the operator used for
mathematical calculation e.g. +, -, *, /, Ye
Relational Operators. These operators are
used to compare two values or a column with
value in SQL. Different relational operators
are >(less than), >=(less than or equal to),
<(greater than), <=(greater than or equal to),
=(equal to), ! < > (not equal to).
Logical Operators. These operators are used
to combine two or more conditions. Different
logical operators are AND(&&), OR(),
NOT(!)
Data Type. Data type is required to specify
that what sort of value will be shared in
Particular column. It is important for the
overall optimization of our database.
MySQL Data Types:
* Numeric Types
* String Types ©
parameter sade set
See apa18
Pogether week® Computer Science (Python)—12
TEXT
Description
Holds up to 255 characters and allows,
a fixed length string.
Holds up to 255 characters and allows
a variable length string. If you store
characters greater than 55, then the data
type will be converted to TEXT type.
Allows a string with a maximum length
of 65,535 characters
Storage
(Declared column length of
characters * Number of bytes)
<= 255
+ String value(Len) + 1 WHERE.
column values require 0 ~ 255.
bytes
+ String value(Len) + 2 bytes
WHERE column values may
require more than 255 bytes
Actual length in bytes of String
value(Len) + 2 bytes, where Len
<216
Date and Time Data Type
; the date values in the
: YYYY-MM-DD, where},27. Create Table. This is a DDL Command used
to create anew table, We can specify the table
name, column name with its data-type.
Syntax
Create table
(
Column_namel data-type(data size/
limit)
constraints,
Column_name? data-type(data size/
limit),
Column_name3 data-type(data size/
limit)
%
For example
Create table student
(
Admno int(5) primary key,
First_Name varchar(15) not null,
LastName _varchar(15),
DOB date,
Fees decimal(9,2),
State varchar(10)
% 3
28. Describe. This command is used to view the
structure of the table (that is a column name,
data-type and constraints).
Syntax
Desc
or
describe
For example
Desc student;
29, Insert, This isa DML command used to insert/
add a new record at the end of the table,
Syntax ai
. Insert into (, ,
_ name3>) VALUES (;
For example
Select * from the student where
admno=1101;
Projection: This way is used to show specific
attributes from the table(s).
Syntax
Select , set
= where
;
For example
Update student Set state = ‘Haryana’
where admno = 1101;
33. Alter. This DDL command is used to add/
modify/remove structure(column) of the
table.
Syntax
Alter table add ;
For example .
Alter table student add gender char(1);
34. Delete. This DML command is used to
remove rows or record(s) from the table.
Syntax
Delete from where
dition>;
For example A
Delete from student;
20 Fogecher with® Computer Science (Python) —12
(6)
©
Syntax
Select , from where
;
For example
Select admno, name, fees from
student where state="Delhi’;
Distinct: This clause is used to
fetch(retrieve) unique values(non-
duplicate) from the column of the table.
Syntax
Select distinct from
;
For example '
Select distinct state from student;
Order by: This clause is used to
arrange the records of the relation
either in ascending or descending order
Syntax
Select * from order
by ;
For example
* Select * from student order by admno;
# by default ascending order (ASC)(e) [loving This clause is used to specify
a condition on grouped column.
Syntax
Select,sum from group by
having
count(column name) >
;
umpl
Select state, sum(fees) from
student group by state having
count(state)>5;
# To display state wise total fees
having more than 5 records.
37. Between operator. This operator is used to
display the data between a specified range
of Numbers or Date.
Syntax
Select * from where
between
and ;
Both and are
inclusive.
For example
+ select * from student where admno
between 1100 and 1199;
+ Select * from student where admno not
between 1100 and 1199;
38. In operator. This clause is used to fetch the
information from the table by providing one
or more values from the specified column.
‘Syntax .
Select , where in
name2> ,
();
Database Management-SQL 21
For example
» Select admno, name from student where
state in(‘Delhi’,’Haryana’);
+ Select admno, name from student where
state not in(‘Delhi’,’Haryana’);
39. Like operator. This clause is used to search
the data according to the given pattern and
for this we need to use the two wild card
characters.
* Percent symbol (%).Matches any string.
+ Underscore (_). Matching single
character.
Syntax
Select , from where
like ;
For example
Select * from student where name like
“AM;
#name starts with “A”.
40. Constraints. Constraints are rules to restrict
the type of data to be entered in a table. It
will be helpful in maintaining the accuracy,
integrity and reliability of the data. Most
commonly used constraints are Primary Key,
Foreign Key, Not Null, Check, default etc.
41. Aggregate Functions.
+ Sum(): This function is used to get total
value of specified column.
For example
Select sum(fees) from the student:
Max(): This function is used to find the
maximum value of the specified column
For example
Select max(fees) from the student;20 Pagecher euitk® Computer Science (Python) 12
»
* Update. This DML command is used to
modify/edit data/record(s) of the table.
Syntax
Update set
where
;
For example
Update student Set state = ‘Haryana’
where admno = 1101;
Alter. This DDL command is used to add/
modify/remove structure(column) of the
table.
Syntax
Alter table add ;
For example
Alter table student add gender char(1);
. Delete. This DML command is used to
Temove rows or record(s) from the table.
Syntax
Delete from where
;
For example
Delete from student;
# removes all records from the table.
Delete from student where state=’Delhi’
# remove only delhi records.
. Drop. This DDL command is used to remove
the records along with its structure of the
table from the database.
Syntax
Drop table ;
For example
Drop table student;
Clause. The condition through which record(s)
can be filtered.
(a) Where: This clause is used to search a
rows/record(s).
Syntax
Select , “column
name2> from where
;
For ts
Select admno, name, fees from
student where state=’Delhi’;
Distinct’ This clause is used to
fetch(retrieve) unique values(non-
duplicate) from the column of the table
Syntax,
Select distinct from
;
For example
Select distinct state from student;
Order by: This clause is used to
arrange the records of the relation
either in ascending or descending order.
Syntax
Select * from order
by ;
For example
+ Select * from student order by admm:
# by default ascending order (ASC)
+ Select * from student order by admne
dese;# Descending Order
Group by: This clause is used to grou?
the column(s) with aggregate functo"
Syntax
Select , aggres-
function(column name> trom
group by :
For example
Select state, sum( ees) from ste
group by state; # Display state"
total fees(©) [vine This clause is used to specify
a condition on grouped column
Syntax
Select , sum from group by
having
count(column name) >
;
For example
Select state, sum(fees) from
student group by state having
count(state)>5;
# To display state wise total fees
having more than 5 records,
37. Between operator. This operator is used to
display the data between a specified range
of Numbers or Date.
Syntax
Select * from where
between
and ;
Both and are
inclusive.
For example
+ select * from student where admno
between 1100 and 1199;
+ Select * from student where admno not
between 1100 and 1199;
Jn operator. This clause is used to fetch the
information from the table by providing one
or more values from the specified column.
Syntax .
Select , , from where in
();
38.
39,
40.
Database Management-SQL 21
Fore
xample
» Select admno, name from student where
state in(‘Delhi’,’ Haryana’);
» Select admno, name from student where
state not in(‘Delhi’,’Haryana’);
Like operator. This clause is used to search
the data according to the given pattern and
for this we need to use the two wild card
characters.
+ Percent symbol (%).Matches any string.
+ Underscore (_). Matching single
character.
Syntax
Select , from where
like ;
For example
Select * from student where name like
“AM;
#name starts with “A’.
Constraints. Constraints are rules to restrict
the type of data to be entered in a table. It
will be helpful in maintaining the accuracy,
integrity and reliability of the data. Most
‘commonly used constraints are Primary Key,
Foreign Key, Not Null, Check, default ete.
41. Aggregate Functions.
+ Sum(): This function is used to get total
value of specified column,
For example
Select sum(fees) from the student;
+ Max(): This function is used to find the
maximum value of the specified column
For example
Select max(fees) from the student;|
|
22 Aegecher wcth® Computer Science (Python)
Min(): This function is used to find the
minimum value of the specified column.
For example
Select min(fees) from the student;
Avg(): This function is used to display
the average of the specified column.
For example
Select Avg(fees) from the student;
Count(): This function is used to count
a number of values in the specified
column. It will not count NULL values.
For example
Select count(fees) from student;
42. Join Clause. It is used to combine records
from two or more tables in a database.
43.
Equi Join. It returns data from the tables
with matching values.
Syntax
Select column(s)(from any of the
REVIEW of the commands.
-- Database-Level Commands
DROP DATABASE databaseName
DROP DATABASE IF EXISTS databaseName
CREATE DATABASE databaseName
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists
SHOW DATABASE:
USE databaseName
SEL!
SHOW CREATE DATABAS
CT DATABASEQ,
-- Table-Level
DROP TABLE [IF EXISTS] tableName,
CREATE TABLE [IF NOT EXISTS] tableName (
colul
mnNamecolumnTypecolumnAttribute, .
PRIMARY KEY(columnName),
databaseName
tables) from Table |, Table2
where tablel.common colum
table2.common_ column;
Cross Join/ Cartesian Prodi
{CUA product
of two or more sets that consists of ai
combinations of elements drawn one
from each set. It is a set of records from
two or more tables are joined(inner jon)
or join condition is missing. Cartesian
product of two relations A and B js
written as A X B. Rows of both tables
will be multiplied, and columns will be
added. For Example, Table A contains
four rows and three columns, and TableB
contain 5 rows and 3 cols then Cartesian
product result to 20 rows(4X5) and 6
columns(3+3).
Syntax
Select column(s)(from any of
tables) from Tablel, Table2
-- Delete the database
~- Delete if it exists
-- Create a new database
~ Show all the databases in this se"
~ Set the default (current) database
~ Show the default database
~ Show the CREATE DATABASE sae"
|
|
|Database Management-SQL 23
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
)
SHOW TABLES -- Show all the tables in the default database
DESCRIBE / DESC tableName-- Describe the detailed structured for a table
ALTER TABLE tableName ... -- Modify a table, e.g, ADD COLUMN and DROP COLUMN
ALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE TABLE NAME ADD PRIMARY KEY (columnName)
ALTER TABLE TABLE NAME DROP PRIMARY KEY
ALTER TABLE tableName ADD FOREIGN KEY (columnName) REFERENCES tableName
(columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName
CREATE TABLE tableName -- Show the CREATE TABLE statement for this tableName
-- Row-Level
INSERT INTO tableName
VALUES (column! Value, column2Value,...) ~ Insert on all Columns
INSERT INTO tableName
VALUES (column! Value, column2Value,...), ~- Insert multiple rows
INSERT INTO tableName (column1Name, ...,columnName)
VALUES (column! Value, ...,columnN Value) ~ Insert on selected Columns
DELETE FROM tableName WHERE criteria
UPDATE tableName SET columnName = expr, ... WHERE criteria
SELECT * | column!Name AS aliasl, ...,columnNName AS aliasN
FROM tableName
WHERE criteria
GROUP BY columnName
ORDER BY columnName ASC|DESC, ...
HAVING groupConstraints24 Pagecher weth® Computer Science (Python)—12
SOLVED QUESTION BANK
Very Short Answer Type Questions [1 Mark]
|. Which command is used to add a new row?
Ans. Insert
2. Which command is used to change the
database?
Use
. Which command is used to remove the
row(s) from table?
. delete
4. Which command is used to close the
MySQL Software/application?
. exit;
5. Which command is used to modify rows
in a table?
. Update
6. Which clause is used to group the column(s)
with aggregate function?
. Group by
7. Which clause is used to remove duplicate
rows from the result of SQL select
statement?
Ans. District
4. Which key is used to uniquely identify row
in a table and also does not accept NULL
values?
. Primary
9. Which clause is used to arrange the rows
of a table?
. Order by
10. Name the command used to change the
database.
_ USE 36
(2) Select cust_name, Fd_Amount from
Bank where Fd_Amount<500000 and
Int_rate >7.00;
(f) Select * from Bank where year(FD_
Date)=2018;
(g) Select * from Bank where FD_Amount
IN (40000,50000);
. Write SQL commands for the statements
(a) to (h) on the table Bank
(a) Display the details of all FD whose
rate of interest is in the range 6% to
T%.
Display the Customer Name and FD
Amount for all the loans for which
the number of Months is 24, 36, or
48(using IN operator).
Display the Account Number, Cus-
tomer Name and FD Amount for all
the FD for which the Customer Name
ends with “Sharma”.
(d) Delete the records of “Rupinder
Kaur”,
©
©
(e) Add another column Maturity_Amt
of type Integer in the Bank table.
find the average FD amount, Label
the column as “Average FD Amount”.
(g) To find the total FD amount which
started in the year 2018?
(h) Update Maturity Amount of all bank
customers.
a,Maturity Amount = (FD_
Amount*Months* Int_rate)/(12*100)32 Pagecher with® Computer Science (Python) 12
\
S (a) Select * from bank where Int_rate>=6.00 and FD_Amount-~7.00,
(b) Select cust name,FD Amount from Bank where Months in(36,42,48),
(c) Select AccNo, cust_name, Fd_Amount from bank where cust_name like *%Sharma’
(d) Delete from Bank where cust_name="Rupinder Kaur’;
(e) Alter table bank add Maturity_Amt int:
(f) Select avg(FD_Amount)”Average FD Amount” from bank;
(g) Select sum(FD_Int) from bank where year(FD_Date)=2018;
a
Update Bank set Maturity_amt = ((FD_Amount)*Months*Int_rate)/(12*100);
(Q-28 to Q-29) Consider the following table Student & Stream.
Table: Student
Admno Sname Class Sec Fee Mobile Area sD
1001 RAMESH XI A 2500 987654321 Madipur 0
1078 KRISHNA XB 2400999911111 Jawala Heri 30
1006 FARDEEN XIL Cc 2600 987654321 Paschim Puri 40
1004 + SUBHAM XI A 2500 963025874 Madipur 20
1029 KRITIKA XI C2700 987456210 Madipur 30
1008 © SAMEEKSHA XI A 2450 987123456 Mangol Puri 20
1025 SALMA Xl BL 2580 998877445 Madipur 30
1036 | AMANDEEP XI BB -2600 999333555 Khyala 40
1037 TEJAS. XI C2650 (987951357 Paschim Puri «40
1029 HIMANSHU xX A
2750 951369874 Jawala Heri 0
Table : Stream
SID Stream_name
10 MEDILCAL
20 NON MEDICAL
30 COMMERCE WITH MATH
40 COMMERCE WITH IP
50 HUMANITIES29,
Write SQL commands for the statements
(a) to (h) on the above table: Student and
Stream
(a)
)
()
@
)
n
®)
(h)
(6)
(c)
(d)
(e)
a
(g)
(A)
Identify Primary Keys and Foreign
Key in the table student and primary
key in Stream table given above.
Display stream id and stream-wise
total fee collected.
Count no of students from each area.
Display all the student details those
who belongs to Madipur Area.
Increase the fees of all students
by10%.
Display unique area from the student
table.
Display details of those students whose
area contains ‘Puri’.
Display the information of those stu-
dents who are in class XII and section
is either B or C.
STUDENT Table : ADMNO Primary
Key,
Foreign Key S ID
STREAM Table : S_ID Primary Key
Select s_id, sum(Fee) from student
group by s_id;
Select area, count(area) from student
group by area;
Select * from student where
area=!Madipur’;
Update student set fee=fee+(fee*10)/100;
Select distinct(Area) from student;
Select * from student where Area like
“Yopuri';
Select * from student where Class =
“XII and Sec in(‘B','C’);
Write SQL commands for the statements
(@) to (4) on the table: Student and Stream
@
®
Display class and total fee collected
from each class,
Display admission no, students name
and stream name.
Ans,
=
@
(6
@)
(h)
(b)
©
©
&
1)
Database Management - SQL 33
Display all the student details who
have taken Commerce Stream.
Count number of students who have
opted for HUMANITIES stream.
Display information of commerce with
ip students whose name start with
‘S*. Arrange the record by admission
number.
Display details of all students who are
in the MEDICAL stream.
Display total fee of ‘Non-Medical’
Student.
Change the name of the Column
Sname to Student_Name.
Select Class, Sum(Class) from Student
group by Class;
Select admno, sname, stream_name
from student, stream where student.s_
id=steam.s_id;
OR
Select admno, sname, stream_name
from student s1, steam s2 where s.s_id
= 82.8 id;
Select * from student, stream where
student.s_id = stream.S_id and
stream_name like ‘COMMERCE%’;
Select count(Stream_Name) from
student, stream where student.s_
id=stream.s_id and stream_name =
‘HUMANITIES’;
Select admno, sname, Class, Sec, Fee,
Mobile, Area, Student.S_ID, Stream_
Name from student, Stream where
Student.S_ID=Stream.$_ID and Sname
like *S%" order by admno asc,;
Select * from student, stream
where student.s_id and stream_
name="Medical’;
Select sum(Fee) from Student, Stream
where Student.S_ID=Stream.$_ID and
Stream_name = ‘NON MEDICAL’
Alter table student change Student_
Name varchar(20);SA Apaches wceh® Computer Science (Python) 12
+0
Ans.
3h.
Given the following relation: STUDENT
‘Table: STUDENT
No. Name Age Department Dateofadm Fee Sex
1 Pankaj 24 Computer 10/01/97 120 M
2 Shalini 2 History 24/03/98 200 F
3 Sanjay 22 Hindi 12/12/96 300 M
4 Sudha 25 History 01/07/99 400 F
5 Rakesh 2 Hindi 05/09/97 250 M
6 Shakeel 30 History 27/06/98 300 M
7 Surya 34 Computer 25/02/97 210 M
8 Shikha 23 Hindi 31/07/97 200 F
Write SQL commands for the following TABLE : CUSTOMERS
ae No CNAME ADDRESS
(a) To show all information about the iM Richa jain ni
students of History department.
(5) To list the names of female students 101 Surbhi Sinha Chennai
who are in Hindi department. 103 Lisa Thomas Bangalore
(c) To list the names of all students with | 104 Imran Ali Dethi
their date of admission in ascending 105 Roshan Singh Chennai
cone TABLE : TRANSACTION
(a) To display student’s name, fee, age
for male students only. TRNO CNO AMOUNT TYPE DOT
(e) Tocount the number of students with | TOOl 101 1500 Credit 2017-11-23
Age>23. TO002 103-2000 Debit 2017-05-12
(a) Select * from student where department | T003. 102 3000 Credit. 2017-06-10
= “history”; T004 103 12000 Credit 2017-09-12
(b) Select * from student where department T004 101-1000 Debit. 2017-09-05
ACen (@) To display details of all transactions
(c) Select * from student order by dateofadm; of TYPE Credit from Table
(d) Select name, fee, age from student where TRANSACTION,
sex="m”; (6) To display the CNO and AMOUNT
(c) Select count(*) from student age>23; of all transactions done in the mont
Write SOL queries for (i) to (iv) and find
outputs for SQL queries (») to (viii) which
are based on the tables.
[Delhi Compt 2018-19}
September 2017 from the dle
TRANSACTION.
(©) To display the last date of transactio®
(DOT) from the table TRANSACTION
for the customer having CNO as 10%To display all CNOCNAME and
DOT (date of transaction) of
those CUSTOMERS from tables
CUSTOMERS and TRANSACTION
who have done transactions more
(@)
than or equal to 2000.
Select count(*), avg(amount) from
transaction where dot>=*2017-06-01";
te
Database Management-SQL 35
| 102 | Surbhi Sinha |
| 103 | Lisa Thomas |
| 105 | Roshan Singh |
(A Select eno, count(*), max (amount)
from transaction group by cno having
count(*)> 1;
(g) Select eno, ename from customer where
address not in (‘Delhi, ‘Bangalore’);
(A) Select distinct cno from transaction; 32. Write SQL queries for (i) to (iv) and find
(a) select * from TRANSACTION where outputs for SQL queries (v) to (viii), which
sype~'Credit’: are based on the tables:
° ; [CBSE Compt. 2018)
(3) selectCNO,Amount from Transaction TAGLESSAEESPEneon
wheremonth(DOT)=09 and year(DOT)
2017: .CODE| NAME __| SALARY] ITCODE|
(c) select Max(DOT) from Transaction -1001__TANDEEPJHA | 60000 |_12
, 1002 YOGRAJ SINHA) 70000 1S
where CNO=103; 1003 | TENZINJACK | 4500012
(d) selectcustomer.cno, cname, dot 1005 | ANOKHIRAJ 50000.
from customer, transaction where Iiicoa' TARaNASEwilSsioan
customer.cno = transaction.cno and ~ .
amount>=2000; TABLE: ITEM
wot cccneeccanet LITCODE | ITEMTYPE | TURNOVER |
COUNT(*) | AVG(AMOUNT) | Is _STATIONARY __ 3400000
+ "7 HOISTERY | _ 6500000
2 BAKERY 10090000
— +
|CNO | COUNT(*) |MAX(AMOUNT)
|
ate
| 101] 2| 1500)
| 103} 2 12000
+.
(a) To display the CODE and NAME of
all salesperson having “17” item Type
Code from the table SALESPERSON,
‘To display all details from table
SALESPERSON in descending order
of SALARY.
‘To display the number of SALESPER-
SON dealing in each TYPE of ITEM.
(Use ITCODE for the same)
(6)
te36 Pegether with® Computer Science (Python) 12
(@) To display NAME of all the salesperson table along with their corresponding ITEM.
TYPE from the ITEM table.
(e) Select max(salary) from salesperson; |
(A Select distinct itcode from salesperson;
(g) select code,name,iitcode from sales person s, item i where s.itcode
over>=7000000;
(A) Select sum (salary)from salesperson where itcode="i2”
Ans. (a) Select CODE, NAME from Salesperson where ITCOD
(b) Select * from Salesperson order by salary dese;
.itcode and turn.
(c)_ Select Type, count(*) from Salesperson group by type;
(d) Select NAME from Salesperson, Item where SALESPERSON. ITOCDE=ITEM ITCODE:
(e) 70000
n+ ]
| ITCODE |
| CODE | NAME| ITCODE |
eet Hpannennn at
| 1001 |SANDEEP JHA | 12|
(rh) (i)
33. Write SQL queries for (i) to (iv) and find outputs for SQL queries (») to (vii which ar
pased on the tables. ° ool!
nple Paper >
Table: Trainer
{ 7D. | City HireDate __ Salary.
| jo | Sunaina Mumbai | 1998-10-15 | 90000
102 Anamika | Delhi | 1904-12-24 80000
103 | Deepti | Chandigarh 2001-12-21 82000
S104 | Meenakshi | Delhi | 2002-12-25 | 78000
0s | Richa | Mumbai | 1996-01-12 95000
[106 | Maniprabha Chennai 2001-12-12 69000
DO eeTable: Course
CID CNAME FEES STARTDATE TID
C201 AGDCA — 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
€203 DCA 10000 2018-10-01 102
203 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 OLEVEL 18000 2018-07-25 105
@
©
©
(©
7)
@)
(h)
Ans. (a)
(6)
Display the Trainer Name, City and
Salary in descending order of their
hire date.
To display the TNAME and CITY
of Trainer of joined the institute
in the month of December 2001.
To display TNAME, HIREDATE,
CNAME, STARTDATE from tables
TRAINER and COURSE whose
FEES is less than or equal to 10000
To display number of trainer from
each city
select tid, tname,from trainer where
city not in(‘delhi’,’mumbai’);
select distinct tid from course;
select tid , count (*), min(fees) from
‘course group by tid having count(*)>1;
Select count(*),sum(fees) from course
where startdate <’2018-09-15;
select tname, city, salary from trainer
order by hiredate desc;
Select tname, city from trainer where
hiredate between ‘2001-12-01" and
*2001-12-317;
OR
Select tname, city from trainer
where hiredate >= ‘2001-12-01" and
hiredate<='2001-12-31";
OR
Select tname, city from trainer where
hiredate like *2001-12%';
|
34,
(c)
(e)
()
()
Database Management~SQL 37
Selecttname, hiredate, cname,
startdate from trainer, course where
trainer.tid=course.tid and fees<=10000;
Select city, count(*) from trainer group
by city;
Select tid, tname, from trainer where
city not in(‘delhi’, ‘mumbai’);
Distinct tid
101
103
102
104
105
tid count(*)
101. 2 12000
count(*) _ sum(fees)
4 65000
min(fees)
Write SQL queries for (a) to (d) and find
outputs for SQL queries (e) to (), which
are based on the tables.
{Sample Paper 2016-17
TABLE: WATCHES
200
"W004 |High fashion 7000 _ 250
W00S Golden time 25000 Gents 100
TABLE: SALE
Watehid | Qty Sold | Quarter _
‘wool 10 1
woos 5 1
woo | 20 2
woos 10 2
woot Ss 3
‘wo02 20 3 a
woos 10 3
wo03 15 438 Together ith® Computer Science (Python)
(a) To display
all the details of those
watches whose name
ends with ‘time’
To display watch’s name andprice of
those watches which have price range
between 5000-15000
To display total quantity in store of
unisex type watches
To display watch name and their
quantity sold in first quarter
(ce) Select max(price).min(qty_store)
from watches:
(f) Select quarter. sum(qty_sold) from
sale group by quarter:
Select watch_name.price.type from
watches w. sale s where W.W atchid=s.
watchid:
Select watch_name,
sum(qty_sold).qty_store
() W.watch=s.watchid group by
s.watchid:
select * from watches where watch_
name like ““eTIME’:
select Watch_name. Price from Watches
where price between 5000 and 15000:
OR
Select Watch_name. Price from Watches
(b)
(
@
@)
(h) qty_store.
Ans. (a)
(ib
(©) Select sum(Price) from Watches where
Type>“UNISEN*
(d) Select Watch name. Qty sold from
Watches, Sale where Watches. Watchid
= Sale, Watchid and Quarter = 1;
ce) MayiPrice) Min(Qty_ store)
25000, 100
Wy) quarter sum(qty_sold)
1 15S
2 30
3 45
+ 1S
(g) | wateh_name | price
“HighFashion 7000
Ss
8
where Price>=$000 and Price<=15000: | GoldenTime ot
Competency/Case-based Questions
35, Consider the table LOANS given below:
Table: LOANS
eS
““AceNo | Name [Loan Amt | EMI IntRate | Start Date
1001 RK. Gupta 300000 36 12.00 | 19-07-2009
1002 S.P.Shanna 500000 |
48 10.00 | 22-03-2008
1003 KP Jain 300000 36 NULL_ 08-03-2007
1004 MP. Yada 0 «|
= Yadav | 800000 | 60 10.00 06-12-2008
| S.P. Sinli oe
ia 20000036 12.50 03-01-2010
1006 P.Shanna 700000 ol
700000 | | 12.50 | 05-06-2008
1007 | K.S. Dhall | soo000 | 48 Satara —
| * i _|_ NULL [05-03-2008Database Management -SQL 39
(a) State the command that will give the output as:
Name
S. P. Shanna
K.S. Dhall
M.P. Yadav
P. Shanna
K.S. Dhall
Ans. Select name from LOANS where Loan_Amt>= 500000;
(6) What will be the output of the following command:
Select name, EMI from LOANS where Loan_Amt>500000 and Int_Rate is NULL;
Ans. None of the above
(©
John has given the following command to display the count of all loan holders whose
name ends with “Sharma”:
Select count from LOANS where Name like ‘Sharma
But he is not getting the desired result. Help him by finding out the correct command
fromthe followings:
Ans. Select Count(*) trom LOANS Where Name like “%Sharma’
@ State the command to display the maximum Loan_Amt and Cust_Name :-
Ans. Select Cust_name, max(Loan_Amt) from LOANS;
(©) Help Ramesh to display the count of all loan holders Whose interest is NULL.
Ans. Select Count(*) from LOANS where Int Rate is NULL.
36. Consider the SchoolBus table given below:
Table: School Bus
Ring | Area covered] G pacity | _Noofstudents Distance Transporter Charges
[ 1 Vasantkunj 10020 10 Shivamrravels 100000
| 2 | HauzKhas 80 _ 80 10 Anandtravels 85000
3 | Pitampura | “6055 30 Anand travels | 60000
[4 Rohini | 100 90 35 Anand travels 100000
8 | Yamuna Vihar) 50 60 20 BhallaCo. 58000
[6 | Krishna Nagar) 70 80 30 Yadav Co. 80000
|_7 | Vasundhara | 100 to 20 YadavCo. 100000
8 | Paschim Viner’ 40 40 20 Speedtravels | 55000
ee40 agecher week® Computer Science (Python) 12
(a) State the command that will give the output as:
Area covered
Yamuna Vihar
Krishna Nagar
Vasundhara
Ans. (iii) select area_covered from schoolbus where transporter - Yadav Co.’
OR transporter’Bhalla Co.';
(6) What will be the output of the following command?
Ans, [Rtno | Area covered | Capacity | Noofstudents Distance Transporter Charges
8 — PaschimVihar 40 40 20 Speed travels 55000
S| Yamuna Vihar 50 | ~S«6O 20 BhallaCo. 58000
dnara | 100. | 110. | 20 | YadavCo. | 100000
7 Vasundhara
(©). Ravi has given the following command to obtain the Longest distance Select max/(distanee)
from schoolbus where group by transporter;
But he is not getting the desired result.
Help him by writing the correct command.
Ans. select transporter, max(distance) from schoolbus group by transporter;
(@) Help Saumya to write the command to display the name of the transporter who is having
lowest capacity in his schoolbus?
Ans. select transporter:min(capacity) from schoolbus group by transporter:
(€) Choose the appropriate primary key.
Ans. Rino
PRACTICE QUESTIONS
Very Short Answer Type Questions [1 Mark]
1. Write the full form of SQL.
2. 7 i coe has its degree as 7 and cardinality as 18. Write the number rows and cotumts it
3. Name the two wild card characters,
4, Write the difference between CHAR and VARCHAR.
5, What do you mean by NULL?
6. What is the purpose of BETWEEN Clause?
7. Name the SQL command used for the following:
(a) To add new record
(b) To remove a recordDatabase Management-SQL 41
(c) To change the name of a column
(d)_ To change the database
(ce) To display records
(A To edit record
5A Table customer contains 5 rows and 7 columns, What will be its cardinality and degree?
A table Item and Store have one common column Item-Id. Item table consists of 5 rows and 3
columns while the store table consists of 7 rows and 5 columns. What will be the degree and
cardinality of these tables in the cartesian product?
A table student consists of 5 rows and 7 columns. Later on 3 columns added and 2 rows deleted.
After some time 5 new students added. What will be the degree and cardinality?
10.
Short Answer Type Questions [2/3 Marks]
11. What is an Alternate Key?
12. Write the full form of DDL and DML?
13. Differentiate between the terms primary key and alternate key.
14. What is the importance of a Primary Key in a table? Explain with a suitable example.
15, Differentiate between Candidate Key and Primary Key in context of RDBMS.
16. Differentiate between Candidate Key and Alternate Key in context of RDBMS.
17. Differentiate between DDL & DMLcommands. Identify DDL & DML commands from the
following:
(UPDATE, SELECT, ALTER, DROP)
18. What are candidate keys in a table? Give a suitable example of candidate keys in a table.
19. Observe the following table and answer the parts (i) and (ii) accordingly
Table: Product
| os
| 12-12-2011
(102 | Pencil 21-02-2013
103 | Braser 90 09-08-2010
“109 ~) Sharpener 90 31-08-2012
[ 13 Clips 900 12122011
(a) Write the names of most appropriate columns, which can be considered as candidate keys
(b) What is the degree and cardinality of the above table?
20. Differentiate between cardinality and degree of a table with the help of an example.
Long Answer Type Questions [4 Marks]
21. Write the SQL query questions from (i) to (iv) and write the output of SQL command for questions
from (v) to (vii) given below:42 Fasceher miek® Computer Science (Prthon)—12
EMPID
010
10s
182
215
244
300
400
441
FIRST
NAME
George
Mary
Sam
Sarah
Manila
Robert
Henry
Rachel
Peter
SALARY
75000
65000
80000
73000
50000
45000
Table: EMPLOYEES
LAST
NAME
Smith
Jones
Tones
Ackerman
Sengupta
ADDRESS
83 First Street
842 Vine Ave.
33 Elm St.
440 U.S. 10
24 Frends Street
CITY
Howard
Losantiville
Paris
Upton.
New Delhi
Samuel 9 Fifth Cross. Washington
Willams 12 Moore Street Boston
Lee 121 Harnson St. New York
Thompson 11 Red Road Paris
Table: EMPSALARY
BENEFITS DESIGNATION
15000 Manager
15000 Manager
25000 Director
12500 Manager
12000 Clerk
peony Clerk
Clerk
Salesman
Salesman
()_ To show firsmame, lasmame. address and ci
To display the content of Employees table in ascendin,
(ii) To display the firsmame,lasmame and total salary
and empsalary, where total salary is calculated as
(®) To display the maximum salary among managers
Give the Output of following SQL commands:
(®) Select firstname, salary from employees, em;
‘Empsalary.empid;
(oi) Select count(distinct designation) from .
Employees.empi
(oii) Select designation, sum(salary) from empsalan ;
22. Consider the following tables Product and Client. Wage by designation having count(*) >2:
(i) and give outputs for SQL queries (0) to (viii)
1p
ite SQL coy
ty of all employees living in paris.
ing order of Firstname.
of all managers from the tables employee
iploye
salary+benefits,
and clerks from the table Empsalary.
salary where designation = Salesman’ and
mands for the statements (!) '°2:
e
Database Management-SQL 43
TABLE: PRODUCT.
PID Product Name _ Manufacturer Price
TPOL Talcom Powder LAK 40
FWOS FaceWash ABC 45
BSOL Bath Soap ABC 55
SHO06 Shampoo XYZ 120
|
FW12 Face Wash | XYZ 95
TABLE: CLIENT :
cD ClientName
o1 Cosmetic Shop.
06 Total Health
12 Live Life
15 | Pretty Woman
16 «Dreams Bangalore TPOI
(i) To display the details of those Clients whose City is Delhi
(ii) To display the details of Products whose Price is in the range of 50 to 100 (Both values
included)
(iii) To display the ClientName, City from Table Client, and ProductName and Price from table
Product, with their corresponding matching P_ID
(iv) To increase the Price of all Products by 10
(v) SELECT DISTINCT CITY FROM Client;
(vi) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP BY
Manufacturer;
(vii) SELECT ClientName, ManufacturerName FROM Product, Client WHERE Client.Prod_Id
= Product.P_Id;
Write SQL commands for the following queries based on the relation Teacher given below
Table: Teacher
No ie Nawoe Age Department | Date_of_join Salary Sex
[eee Jugal 4 Computer | «10/01/97 12000 | M
2 | Sharmila 31 History | 24/03/98 20000 F
[3 | Sandeep 32 Maths 12/12/96 30000 M
ra | Sangeeta | 35 History | 01/07/99 40000 F~~
44 Aegether wwith® Computer Science (Python) 12
5 Rakesh 42 Maths. 05/09/97 25000 y
6 Shyam 50 History 27/06/98 30000 M
7 Shiv Om 44 Computer 25/02/97 21000 y
8 Shalakha 33 Maths, 31/07/97 20000 F
(a) To show all information about the teacher of Computer department,
(b) To list the names of female teachers who are in Maths department.
(©) To list the names of all teachers with their date of joining in ascending order.
(@) To display teacher’s name, salary, age for male teachers only.
(e) To count the number of teachers with Age>23.
24. Write SQL commands for the following queries on the basis of Club relation given below
Relation: Club
Coach-ID CoachName Age Sports date_of_app Pay Sex
1 Kukreja 35 Karate 27/03/1996 1000 M
2 Ravina | 34 Karate 20/01/1998 1200
3 ~ Karan 34 - Squash 19/02/1998 2000 M
4 Tarun | 33 Basketball 01/01/1998 1500 M
5 Zubin 36) Swimming «12/01/1998 750M
6 Ketaki 36 Swimming 24/02/1998 800 F
7 Ankita 39 Squash 2o/z1998 2200 F
8 Zareen 37 Karate 22/07/1998» 100F
9 Kush 41 | Swimming 13/01/1998 900M
10 Shailya 37 Basketball 1902/1998 1700 M
(a) To show all information about the swimming coaches in the club.
(b) To list the names of all couches with their date of appointment (date_of app) in desee™™*
order.
(c) To display a report showing coach name, pay, age, and bonus (15% of pay) for all a
(d) To insert @ new row in the Club table with ANY relevant data:
(6) Give the output of the following SQL statements:
(i) Select COUNT(Distinct Sports) from Club;
(ii) Select Min(Age) from Club where SEXDatabase Management-SQL 45
Write SQL commands for (a) to (f) and write the outputs for (g) on the basis of tables FURNITURE
and ARRIVALS.
Table: FURNITURE.
NO TTEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White lotus: Double Bed 23/02/2002 30000 25
2 Pink feather Baby cot 20/01/2002 7000 20
3 Dolphin Baby cot 19/02/2002 9500 20
4 Decent Office Table 01/01/2002 25000 30
5 Comfort zone Double Bed 12/01/2002 25000 25
6 Donald Baby cot 24/02/2002 6500 15
7 Royal Finish Office Table 20/02/2002 18000 30
8 Royal tiger Sofa 22/02/2002 31000 30
9 Econo sitting Sofa 13/12/2001 9500 25
10. Eating Paradise Dining Table 19/02/2002 11500 25
Table: ARRIVALS
NO ITEMNAME TYPE DATEOFSTOCK |. PRICE DISCOUNT
1 ow a 23/03/2003 25000 25
2 Old Fox Sofa 20/02/2003 17000 20
3 Micky Baby cot 21/02/2003 7500 1s
(a) To show all information about the Baby cots from the FURNITURE table.
(b) To list the ITEMNAME which are priced at more than 15000 from the FURNITURE table.
(¢)
To list ITEMNAME and TYPE of those items, in which date of stock is before 22/01/2002
from the FURNITURE table in descending order of ITEMNAME:
To display ITEMNAME and DATEOFSTOCK of those items, in which the discount t
percentage is more than 25 from FURNITURE table.
To count the number of items, whose TYPE is “Sofa” from FURNITURE table.
(d)
(e)
() To insert a new row in the ARRIVALS table with the following data:
14,“Valvet touch”, “Double bed”, {25/03/03}, 25000,30
Give the output of following SQL statement
(g)46 Aegecher with Computer Science (Python)— 12
Note: Outputs of the above mentioned queries should be based on original data given in both the
tables i.e., without considering the insertion done in (f) part of this question.
(©) Select COUNT(distinct TYPE) from FURNITURE;
(Select MAX(DISCOUNT) from FURNITURE, ARRIVALS
(i) Select AVG(DISCOUNT) from FURNITURE where TYPE="Baby cot”;
() Select SUM(Price) from FURNITURE where DATEOFSTOCK~12/02/02;
20. Consider the following tables GAMES and PLAYER. Write SQL commands for the statements
(2) to (d) and give outputs for SQL queries (e1) to (e4)
Relation: GAMES
Game Prize Schedule
GCode a Namber footages | leant
101 aoe 2 5000 23-Jan-2004
Board
102 Badminton 2 12000 12-Dec-2003
[ jo oe _
103 oe 4 8000 14-Feb-2004
Tennis
105 Chess 2 9000 01-Jan-2004
CT Lawn | - soon |
108 a || 25000 19-Mar-2004
_ [EA em
| PCode = Geode
1 Nabi Ahmad 1.
| lo
| 2 Ravi Sahai | 108
3 | Jatin 101
4 | Nazneen | 103
(a) To display the name of all Games with their Geodes
(b) To display details of those games which are having PrizeMoney more than 7000
(c) To display the content of the GAMES table in ascending order of ScheduleDate
(d) To display sum of PrizeMoney for each of the
in column Number)
(e1) Select COUNT(DISTINCT Number) FROM GAMES;
(e2) Select MAX(ScheduleDate), MIN(ScheduleDate) FROM GAMES;
Number of participation groupings (as shownDatabase Management SQL 47
(e3) Select SUM(PrizeMoney) FROM GAMES;
(e4) Select DISTINCT Geode FROM. PLAYER;
Consider the following tables WORKER and PAYLEVEL and answer (a) and (4) parts of this
question
Relation: WORKER
LECODE| NAME | DESIG | PAYLEVEL | DOs DoB
1 Radhey rn i _ -
Shyam Supervisor POO! 13-Sep-2004 23-Aug-1981
a i a
Chander | |
12 Nath Operator P003 22-Feb-2010 12-Jul-1987
13 | Fizza | Operator P003 14-June-2009 14-Oct-1983
- |
Ameen | |
15 | ed Mechanic P002 21-Aug-2006 13-Mar-1984
T |
18 _ Sanya Clerk P002 19-Dec-2005 09-June-1983
Relation: PAYLEVEL
PAYLEVEL PAY ALLOWANCE
POO! 26000 | 12000
002 22000 | 10000
O03 12000 6000
(a) Write SQL commands for the following statements:
(i) To display the details of all WORKERs in descending order of DOB.
(ii) To display NAME and DESIG of those WORKERs whose PLEVEL is either POO!
or P002,
(iii) To display the content of all the WORKERs table, whose DOB is in between *19-
JAN-1984" and '18-JAN-1987’,
(iv) To add a new row with the following:
19, ‘Daya kishore’, ‘Operator’, ‘P003’, 19-Jun-2008", *L1-Jul-1984"
(6) Give the output of the following SQL queries:
(@ Select count(plevel), plevel from worker group by plevel;
(ii) Select max(dob), min(doj) from worker;48 Pagecker eiek® Computer Science (Python) —12
(ii) Setect name, pay from worker w, paylevel p where w plevel=p.plevel and w:ecodect}
(iv) Select plevel, pay+allowance from paylevel where plevel=" p003";
28. Consider the following tables CARHUB and CUSTOMER and answer (a) and (5) parts of thi
question
Delhi 201
Table: CARHUB
Veode ae Make Color Capacity Charges
100 Innova Toyota WHITE 7 15
102 SXx4 ‘Suzuki BLUE 4 14
104 C Class Mercedes RED 4 35
105 A-Star Suzuki WHITE 3 14
108 Indigo Tata SILVER 3 12
Table: CUSTOMER
CCode CName VCode
1 Hemant Sahu 101
2 Raj Lal os
3 " Feroza Shah “tos
4 | KetanDial agg
(@ Write SQL commands for the following statements;
(© To display the names of all white colored vehicles
(ii) To display name of vehicle, make and capacity of vehicles in ascending order of t
sitting capacity
(ii) To display the highest charges at which a vehicle can be hired from CARHUB
(iv) To display the customer name and the corre:
them.
() Give the output of the following SQL queries:
( Select count(distinct make) from cabhub;
(Zi) Select max(charges), min(charges) from carhub;
(Iii) Select count(*), make from carhub;
(Iv) Select vehiclename from carhub where capacity = 4: