Xii CS Term Ii
Xii CS Term Ii
Xii CS Term Ii
Sh. D. V. Ramakrsihna
Assistant Commissioner
Kendriya Vidyalaya Sangathan Ranchi Region
Patron
Ravi Prakash
Post Graduate Teacher
Kendriya Vidyalaya Namkum
Subject Convenor
Python Programming
Database Management
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
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.
Mind Map
Data structures are a specific way of organizing data in a specialized format on a computer so
that the information can be organized, processed, stored, and retrieved quickly and effectively.
Different kinds of data structures are suited to different kinds of applications, and some are
highly specialized to specific tasks. More precisely, a data structure is a collection of data values,
the relationships among them, and the functions or operations that can be applied to the data.
Linear - Linear data structures have all their elements arranged in a linear or sequential fashion
such as Array, linked list, Stack and Queue
Nonlinear - In non-linear data structures, data is not arranged sequentially, instead, it is arranged
in a non-linear fashion. Elements are connected to each other in a non-linear arrangement
Data
Structure
Primitive Non
int, float, char Primitive
etc.
Linear Non-Linear
Stack
Stack is a linear data structure in which the elements can be added or removed only from one
end known as “Top” of the stack. The discipline of Stack is LIFO (Last In First Out) i.e. element
inserted last will be removed first.
There are various real life example of stack, stack of plate in the kitchen, a pile of books etc. It is
also used to implement functions, parsers, expression evaluation, and backtracking algorithms.
Application of Stack:
Complete Program :
def pop(stk):
a=stk.pop()
return a
def isEmpty(stk):
#Main Program
stack =[]
top= None
choice=None
while True:
print("**************** Program implement Stack*************")
print("1 Push")
print("2 Pop")
print("3 Display")
print("4 Exit")
choice=input("Enter your choice : ")
if choice=='1':
e=input("Enter element to insert")
push(stack,e)
elif choice=='2':
if isEmpty(stack):
print("Underflow! nothing to delete")
else:
a=pop(stack)
print("The delete item is ",a)
elif choice=='3':
display(stack)
elif choice=='4':
break
Important Questions:
Data Flow
Simplex – In this mode of communication, data is transmitted in one direction
only. e.g. Keyboard, monitor. It uses entire capacity of channel to send the data.
Half Duplex – Communication is bi-directional but not same time. i.e. Walkie-
Talkie. It uses entire capacity of channel is utilized for each direction.
Full Duplex – Communications is bi-directional simultaneously i.e. both sender
and receiver can be send data at same time.
Network Terminology
Node- The device connected to a network.
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 is 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 :
o Analog Signal – that has infinitely many level of intensity over a period of
time.
o 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.
Bandwidth – It is difference between the highest and the lowest frequencies
contained in the signal.
Parallel Communication
Series Communication
Synchronous Transmission
Asynchronous Transmission
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.
Circuit Switching vs Packet Switching
Network Devices
Modem
It stands for modulator and demodulator
Repeater
Repeaters are network devices that amplify or regenerate an incoming signal before
retransmitting it.
It operate 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.
It is a non-intelligent network device that sends message to all ports( i.e. Broadcast)
Types of Hub
Active Hub –
It strengthen the signal may boost noise too.
It need electricity.
Passive Hub –
It repeat/copy signals.
It does not need electricity
Switch
Network Switch or switch is also a network multiport device that allow multiple
computer 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.
Gateway
RJ45
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.
Router Gateway
It ensure that data packets are To connect two networks of different
switched to the right address with protocols as a translator
the best route.
It routes the data packets via similar It connects two dissimilar networks
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
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.
Moderate Data Rate.
Moderate Error Rate.
WAN
It connect device across globe.
It uses public network
Internet
BSNL
VSNL
Network Media
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
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
Higher bandwidth
Less signal attenuation
Immune to cross-talk
Optical fiber have long life more than 100 or above years
Grater immune to tapping
Resistance to corrosive material
Long distance transmission is possible
Immunity to electromagnetic interference
Optical Fibre-Disadvantage
Unidirectional propagation
High initial cost
Optical fiber more tensile stress than copper cables
Installation and maintenance
Fiber joining process is very costly and require skilled menpower
Difficult to splice (join)
Difficult to find error
Radio Wave
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
Bluetooth
Topology
Physical and Logical arrangement of nodes in the network is called Network Topology.
The Key Elements to be considered to choose correct topology for your network
Length of the Cable Needed – longer the cable, more work is required for setup
Cable Type- Depending on requirement of bandwidth
Cost- Installation Cost and Complexity
Scalability – Ease of expansion
Robustness – Ability to recover from error
Types of Topology
Bus
Ring
Star
Tree
Mess
Hybrid
Bus 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)
Reliable
Robust
Failure of node does not affect the working of the network.
Fault detection and isolation is easy.
Maintenance of the network is easy.
It doesn’t create bottlenecks where data collisions occur.
Tree Topology
In Tree Topology, the devices are arranged in a tree fashion similar to the branches of a
tree.
It multilayer architecture.
Protocol
Types of Protocol
TCP/IP
FTP
HTTP/HTTPS
IMAP
POP3
SMTP
PPP
TELNET
VoIP
It is used for the transfer of computer files among hosts over TCP/IP (internet).
It allows access to directories or folders on remote computers.
It uses client-server architecture.
It is statefull protocol
The default port is 21
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.
Default port for POP3 110 and secure port 995
It is also used to retrieve mail from mail server to client over internet (TCP/IP).
It allows access to mail from different device.
E-mail client establishes a connection with the server every time you log in and
maintained for the whole session.
Email will not automatically gets deleted.
Default Port is – 143 and Secure port is 993.
Advantage of VoIP
Save a lot of money
More than two people can communicate or speak
Supports great audio transfer
Provide conferencing facility
Disadvantages of VoIP
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.
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
Makes web more interactive through online social media web- based forums,
communities, social networking sites.
It is a website design and development world which aim to encourage sharing of
information and views, creativity and user interactivity between the users.
Video sharing possible in the websites
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.
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.
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
o Shared Hosting - Web server shared among customers
o Reseller Hosting – Become yourself as web host to sell others
o Virtual Private Server – One server as multiple server for multiple websites
o Dedicated Server- Entire web server is dedicated to same website
Exercise:
1. Which protocol is used to exchange files on Internet
2. What is the purpose of using a MODEM?
3. What type of address is the following?
20:B9:F1:63:2F:FB
4. Identify the topologies from the followings:
(i) In it the nodes form a circular path for data to travel and each node is connected to
two other nodes.
(ii) In it devices are connected through hub/switch, hub/switch is responsible for
receiving and transmitting data from each node to destination.
5. A School would like to go in for network of all the computers. Which topology would
you recommend and why?
6. What is communication channel? What choices do you have while choosing a
communication channel for a network?
7. What do you mean by network topology? Name most popular topologies.
8. Akhil is transferring songs from his mobile to his friend’s mobile via Bluetooth
connection. Name the network used by Akhil.
9.
Case Based
10. In Hyderabad, 5 ABC Bank branches are available. One is at RR Pet, other at Market, other at
Ashok Nagar, other at Fire Station and the last one at Bus Stand. Higher official want to keep a
network between these 5 branches. The branch names(A to E) and the number of computers in
each branch(given inside the rectangle) is given below.
ADMIN 100
SCIENCE 85
BUSINESS 40
ARTS 12
DELHI Head Office 20
(i) Suggest the most appropriate location of the server inside the HYDERABAD campus
(out of the 4 buildings), to get the best connectivity for maximum number of
computers. Justify your answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the
HYDERABAD campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be installed
to protect and control the internet uses within the campus?
(iv) 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
DELHI Head Office?
a. Email
b. Text Chat
c. Video Conferencing
d. Cable TV
1. Perfect Edu Services Ltd. 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. You as a network expert have to suggest the best network
related solutions for their problems raised in (i) to (iv), keeping in mind the distances between
the buildings and other given parameters.
[CBSE COMP 2015]
ENGINEERING 75 75
BUSINESS 40 40
MEDIA 12 12
(i) Suggest the most appropriate location of the server inside the CHENNAI campus (out of the
4 buildings), to get the best connectivity for maximum no. of computers. Justify your
answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the
CHENNAI campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be installed to
protect and control the internet uses within the campus ?
(iv) Which of the following will you suggest to establish the online face-to-face communication
between the people in the Admin Office of CHENNAI campus and DELHI Head Office ?
a. Email
Dept:
Common RDBMS:
Oracle, MS SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase, Adaptive
Server Enterprise, SAP Sybase IQ, Teradata, PostgreSQL, SQLite, etc.
Out of these MySQL, PostgreSQL and SQLite are Open source implementation.
MySQL
Runs on virtually all platforms including Linux, Unix and Windows. Popular for web
based application and online publishing. It is a part of LAMP (Linux, Apache, MySQL,
PHP) stack
SQLite
Relational DBMS but it is not client-server database engine rather, it is embedded into
end program. Arguably the most widely deployed database engine as it is used by several
browsers, OS and embedded systems (Mobiles).
PostgreSQL
General purpose object-relational DBMS.
It is the most advanced open source database system. It is free and open source i.e.
source code is available under PostgreSQL license, a liberal open source license.
Data is organized in two-dimensional tables called relations. The tables or relations are related
to each other.
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 the 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.
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:
A set of one or more attribute that can identify a record uniquely in the relation is called
Primary Key.
There can be only 1 primary key in a table
Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL)
i.e. we cannot left it blank.
Candidate Key
In a table there can be more than one attribute which contains unique values. These
columns are known as candidate key as they are the candidate for primary key.
Among these database analyst select one as a primary key based on requirement like
must contain unique value, compulsory entry and where maximum searching is done etc.
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.
Foreign key
From the Above table definition we can observe that the DEPTNO column of EMPLOYEE table
is deriving its value from DEPTNO of table DEPARTMENT. So we can say that the DEPTNO of
REFERENTIAL INTEGRITY:
Used to ensure relationship 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.
MySQL database system refers to the combination of a MySQL server instance and
MySQL database.
It operates using Client/Server architecture in which the server runs on the machine
containing the database and client connects to server over a network
MySQL is a multiuser database system, meaning several users can access the database
simultaneously.
The Server
Listens for client requests coming in over the network and access the database as per the
requirements and provide the requested information to the Client.
The Client
Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-end
programming which connect to server programmatically like connecting to MySQL using
Python Language or Java or any other language.
FEATURES OF MYSQL:
STARTING MYSQL:
Click on Start All Programs MySQL MySQL Server MySQL Command Line
Client
Create table <tablename> - This command / statement is used to create a new table in a
database. The syntax the is
Drop table <tablename> - This command is used to permanently delete the table from
database.
For example, drop table pet; will delete pet table from database
Alter table <tablename> - This command is used to modify the structure of existing table
such as adding new column, removing existing column, rename or changing data type, size
and constraints.
o Adding new column to exiting table
Syntax :
Update <tablename> - This command is used to update data from the table
Syntax:
Syntax:
ifnull(column, value_to_replace’)
Relational Operator
> greater than
< less than
>= greater than equal to
<= less than equal to
= equal
! = or <> not equal to
Logical Operator
And – evaluated true if all the logical expression is true otherwise false.
Or - evaluated true if any the logical expression is true otherwise false.
Logical operator is used to combine two or more logical expression,
Membership Operator
in –
Not in
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Comparing NULL
Like clause is used to match pattern using two wild card characters
_ (underscore) – single unknown character
% (modulo) - Zero or more unknown characters
e.g.
words staring with ‘t’ ‘t%’
words ending with ‘t’ ‘%t’
words containing ‘t’ - ‘%t%’
word with ‘t’ as second letter - ‘_t%’
words with ‘t’ as third last character – ‘%t_ _’
words containing four letter and ‘t’ as second letter – ‘_ t_ _’
Syntax:
SELECT */col_list
FROM tablename
ORDER BY col1 asc/desc, col2 asc/desc;
o sum() - Return the summation of all non-NULL values of the set of values.
In above example there are 14 row in the EMP table, but distinct clause
only consider unique value.
Group By Clause
o It is used in a SELECT statement to collect data across multiple records and group
the results by one or more columns.
Syntax:
SELECT column_name, aggregate_function
FROM table_name
GROUP BY column_name
Having clause –
o Having clause is used to place condition on aggregate function in conjunction with
group by clause.
o Having clause in placed after where clause in select statement.
Syntax:
SELECT columm_name, aggregate_function(col_name)
FROM table
WHERE condition
GROUP BY column_name
HAVING aggregate_function(column_name) operator expression;
The above query will display deptno, maximum salary and number of employees from
each department.
The query given below display deptno, maximum salary and number of employees
from those department which have maximum salary greater than equal to 3000.
4. Write SQL statement to add a column ‘‘COUNTRY’’ with data type and size as VARCHAR(70) to the
existing table named ‘‘PLAYER’’. Is it a DDL or DML or TCL command ?
5. Table Student has the columns RNO and SCORE. It has 3 rows in it. Following two SQL statements
were entered that produced the output (AVG(SCORE) as 45 and COUNT(SCORE) as 2) :
(i) AVG(SCORE)
(ii) Count(score)
6. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
7. How is a database related to a table ?
8. Mr. Sen has to create a table named ‘Employee’ with Columns to store EmpID, Name, Designation,
Age and Salary. EmpID is the Primary key and Name cannot be NULL. Some of the rows that will be
inserted are shown below.
Write SQL query to create the above table with appropriate data types and sizes of columns.
9. Ms. Rajshri is the Class Teacher of Class XII. She wants to create a table named ‘Student’ to store
marks in different subjects of her class. Identify any 4 columns for the table along with their suitable
data types.
10.“XYZ” Company conducts workshops for employees of organizations. The company requires
data of workshops that are organized. Write SQL query to create a table ‘Workshop’ with the
following structure:
(i) To display names of drivers and destination city where TELEVISION is being transported.
(ii) To display driver names and destinations where destination is not MUMBAI.
(iii) To display the names of destination cities where items are being transported. There
should be no duplicate values.
(iv) To display details of rows that have some value in DRIVERGRADE column.
(v) To display names of drivers, names of items and travel dates for those items that are
being transported on or before 1st April 2019.
(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.
(vii) To display the names of drivers, item names and travel dates in alphabetic (ascending)
order of driver names.
(viii) To display names of drivers whose names are three characters long.
18. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
19. Consider the table given below. Write SQL queries for (i) to (vii).
Columns REGID stores Registration Id, PREWEIGHT stores weight of the person before joining Gym,
CURRWEIGHT stores current weight, DOJ stores Date of Joining, BRANCH stores the branch of Gym
where the person has enrolled.
(i) To display names of members along with their previous and current weights who are in
Model Town branch.
(ii) To display all names of members, previous weight, current weight, Change in weight (i.e.
how much increase from previous weight or decrease from previous weight, Decrease will
be displayed with negative sign)
(iii) To display BRANCH wise count of members in the Gym. (i.e. display the BRANCH and
number of members in each BRANCH)
(iv) To display names and date of joining of all the members who joined in the year 2018.
(v) To display Names and Current weight of all the members in descending order of Current
Weight.
(vi) To display the names and date of joining of male members who have joined after 27th
September 2018.
(vii) To display names and date of joining of members who have their names starting with ‘S’
and ending with ‘a’.
20. Consider the table Flight given below, write command in SQL for (i) to (iv) and output for (v) to (viii)
Table : FLIGHT
EMP Table
DEPT Table
Ven Diagram
Syntax:
SELECT * FROM table1, table2;
Or
SELECT * FROM table1 CROSS JOIN table2;
Or
SELECT * FROM table1 JOIN table2;
e.g. SELECT * FROM emp, dept;
SELECT * FROM emp CROSS JOIN dept;
SELECT * FROM emp JOIN DEPT;
Output:
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
Equi Join-
It performs a JOIN against equality or matching column(s) values of the associated
tables.
Ven Diagram
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
+-------+--------+-----------+------+------------+---------+---------+--------+--------+------------+----------+
Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname belongs to
DEPT table. So, to retrieve data in this we will use join
SELECT emp.ename, emp.sal, dept.dname
FROM emp, dept WHERE emp.deptno=dept.deptno;
Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.
Syntax:
SELECT */column_list
FROM Table1 NATURAL JOIN TABLE2;
Or
SELECT */column_list
FROM TABLE1 join on common_column_name;
Example :
SELECT * FROM emp JOIN dept USING(deptno);
Or
SELECT * FROM emp NATURAL JOIN DEPT;
Output:
+--------+-------+--------+-----------+------+------------+---------+---------+------------+----------+
| deptno | empno | ename | job | mgr | hiredate | sal | comm | dname | loc |
+--------+-------+--------+-----------+------+------------+---------+---------+------------+----------+
| 20 | 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | RESEARCH | DALLAS |
| 30 | 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | SALES | CHICAGO |
| 30 | 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | SALES | CHICAGO |
| 20 | 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | RESEARCH | DALLAS |
| 30 | 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | SALES | CHICAGO |
| 30 | 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | SALES | CHICAGO |
| 10 | 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | ACCOUNTING | NEW YORK |
| 20 | 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | ACCOUNTING | NEW YORK |
| 30 | 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | SALES | CHICAGO |
| 20 | 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | RESEARCH | DALLAS |
| 30 | 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | SALES | CHICAGO |
| 20 | 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | ACCOUNTING | NEW YORK |
+--------+-------+--------+-----------+------+------------+---------+---------+------------+----------+
Customer Table:
customer_id cust_name city grade salesman_id
3002 Nick Rimando New York 100 5001
3007 Brad Davis New York 200 5001
3005 Graham Zusi California 200 5002
3008 Julian Green London 300 5002
3004 Fabian Johnson Paris 300 5006
3009 Geoff Cameron Berlin 100 5003
3003 Jozy Altidor Moscow 200 5007
Q1. Write a SQL query to display Salesman, cust_name and city from above table where the
salesperson and customer belongs to same city.
Ans:
SELECT s.name AS "Salesman",
c.cust_name, c.city
FROM salesman s,customer c
WHERE s.city=c.city;
Or
SELECT salesman.name AS "Salesman",
customer.cust_name, customer.city
FROM salesman,customer
WHERE salesman.city=customer.city;
Q2. write a SQL query to display ord_no, purch_amt, cust_name, city of those orders where
order amount exists between 500 and 2000.
Ans:
SELECT o.ord_no,o.purch_amt,
Unsolved Exercise:
1. Consider the following tables PARTICIPANT and ACTIVITY and answer the questions that follow :
(i) When the table ‘‘PARTICIPANT’’ was first created, the column ‘NAME’ was planned as
the Primary key by the Programmer. Later a field ADMNO had to be set up as Primary
key. Explain the reason.
OR
Identify data type and size to be used for column ACTIVITYCODE in table ACTIVITY.
(ii) To display Names of Participants, Activity Code, Activity Name in alphabetic ascending
order of names of participants.
(iii) To display Names of Participants along with Activity Codes and Activity Names for only
those participants who are taking part in Activities that have ‘bag’ in their Activity
Names and Points of activity are above 250.
2. In a database there are two tables ‘LOAN’ and ‘BORROWER’ as shown below:
Table: LOAN
Customer_Name Loan_no
Jones K-170
Smith K-230
Hayes K-155
Result_set object holds all the record (rows) returned by execute() method
Perform required operations using various cursor method
Close Cursor using close() method of Cursor object
mycursor.close()
fetchone() – It is method of cursor object that fetches next one row of a query
result set.
Fetchall() – it is another method of cursor object that fetches all the rows in
the result set.
rowcount()- it is a method of cursor object that returns the number of rows
affected by execute() method.
Creating Database from Python
Listing database in MySQL before the execution of the code
Output:
('information_schema',)
('mydb',)
('mysql',)
('newdb',)
('performance_schema',)
('school',)
('sys',)
('test',)
('xiicomm',)
Code:
Output:
Enter name of the person to update Address Rohit
Enter New Address Patna
1 records updated
Code:
General Instructions
Section -A
Each question carries 2 marks
Q. Part Question Marks
No No.
1. Give any two characteristics of stacks. (2)
(ii) Out of the following, which is the fastest wired and wireless medium (1)
of transmission?
3. Differentiate between char(n) and varchar(n) data types with respect (2)
to databases.
4. A resultset is extracted from the database using the cursor object (2)
(that has been already created) by giving the following statement.
Mydata=cursor.fetchone()
75
Kendriya Vidyalaya Sangathan, Ranchi Region
5. Write the output of the queries (a) to (d) based on the table, (2)
Furniture given below:
Table: FURNITURE
FID NAME DATEOFPURCHASE COST DISCOUNT
B001 Double 03-Jan-2018 45000 10
Bed
T010 Dining 10-Mar-2020 51000 5
Table
B004 Single 19-Jul-2021 22000 0
Bed
C003 Long 30-Dec-2016 12000 3
Back
Chair
T006 Console 17-Nov-2019 15000 12
Table
B006 Bunk 01-Jan-2021 28000 14
Bed
6. (i) Which command is used to view the list of tables in a database? (1)
(ii) Give one point of difference between an equi-join and a natural join. (1)
Table: MOVIEDETAILS
MOVIEID TITLE LANGUAGE RATING PLATFORM
M001 Minari Korean 5 Netflix
M004 MGR Magan Tamil 4 Hotstar
76
Kendriya Vidyalaya Sangathan, Ranchi Region
M010 Kaagaz Hindi 3 Zee5
M011 Harry English 4 Prime
Potter Video
and the
Chamber
of
Secrets
M015 Uri Hindi 5 Zee5
M020 Avengers: English 4 Hotstar
Endgame
OR
Table: SCHEDULE
SLOTID MOVIEID TIMESLOT
S001 M010 10 AM to 12 PM
S002 M020 2 PM to 5 PM
S003 M010 6 PM to 8 PM
S004 M011 9 PM to 11 PM
SECTION – B
Each question carries 3 marks
8. Julie has created a dictionary containing names and marks as key (3)
value pairs of 6 students. Write a program, with separate user
defined functions to perform the following operations:
77
Kendriya Vidyalaya Sangathan, Ranchi Region
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90,
"TOM":82}
OR
Alam has a list containing 10 integers. You need to help him create
a program with separate user defined functions to perform the
following operations based on this list.
● Traverse the content of the list and push the even numbers
into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
9. (i) A table, ITEM has been created in a database with the following (1)
fields:
ITEMCODE, ITEMNAME, QTY, PRICE
Give the SQL command to add a new field, DISCOUNT (of type
Integer) to the ITEM table.
(ii) Categorize following commands into DDL and DML commands? (2)
Table: CITY
FIELD NAME DATA TYPE REMARKS
78
Kendriya Vidyalaya Sangathan, Ranchi Region
AVGTEMP INTEGER
POLLUTIONRATE INTEGER
POPULATION INTEGER
11. Write queries (a) to (d) based on the tables EMPLOYEE and (4)
DEPARTMENT given below:
Table: EMPLOYEE
EMPID NAME DOB DEPTID DESIG SALARY
120 Alisha 23- D001 Manager 75000
Jan-
1978
123 Nitin 10- D002 AO 59000
Oct-
1977
129 Navjot 12- D003 Supervisor 40000
Jul-
1971
130 Jimmy 30- D004 Sales Rep
Dec-
1980
131 Faiz 06- D001 Dep 65000
Apr- Manager
1984
Table: DEPARTMENT
79
Kendriya Vidyalaya Sangathan, Ranchi Region
(c) To display the names of employees whose salary is not known, in
alphabetical order.
12. (i) Give two advantages and two disadvantages of star topology (2)
OR
13. BeHappy Corporation has set up its new centre at Noida, Uttar (4)
Pradesh for its office and web-based activities. It has 4 blocks of
buildings.
BeHappy Corporation
Block B
Block A
Block D
Block C
80
Kendriya Vidyalaya Sangathan, Ranchi Region
Block B - 50
Block C - 125
Block D - 10
81
Kendriya Vidyalaya Sangathan, Ranchi Region
KENDRIYA VIDYALAYA SANAGTHA RANCHI REGION
CLASS 12 TERM 2 SAMPLE QUESTION PAPER COMPUTER
SCIENCE (Code: 083)
Maximum Marks: 35 Time: 2 hours
General Instructions
Section -A
Each question carries 2 marks
Q. Part Question Marks
No No.
1. What is a data structure? Give two examples. (2)
(ii) Which type of network (out of LAN, PAN and MAN) is formed, when (1)
you connect two mobiles using Bluetooth to transfer a video?
(ii) Name any two functions used to extract data from cursor. (1)
Write the output of the queries (a) to (d) based on the table,
CLUB given above:
(i) SELECT COUNT (DISTINCT SPORTS) FROM CLUB;
(ii) SELECT MIN(AGE) FROM CLUB WHERE SEX = ‘F’;
(iii) SELECT AVG(PAY) FROM CLUB WHERE SPORTS = ‘KARATE’;
(iv) SELECT SUM(PAY) FROM CLUB
WHERE DATEOFAPP > ‘31/01/1998’;
6. (i) Which clause is used to remove duplicate rows of the table (1)
(ii) Give one point of difference between primary key and foreign key (1)
Table: STUDENT
No Name Stipend Stream AvgMark Grade Class
1 Karan 400.00 Medical 78.5 B 12B
2 Divakar 450.00 Comme 89.2 A 11C
rce
3 Divya 300.00 Comme 68.6 C 12C
rce
4 Arun 350.00 Humani 73.1 B 12C
ties
OR
Table: INVENTORY
ItemNo ItemName Scode Quantity
2005 Notebook Classic 23 60
2003 Ball Pen 0.25 24 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 25 60
2001 Eraser Small 26 220
OR
Vaishnav has a list containing names of 10 cities. You need to help
him create a program with separate user defined functions to
perform the following operations based on this list.
● Traverse the content of the list and push those names which
Kendriya Vidyalaya Sangathan, Ranchi Region
Page 84|
are having more than 5 characters in it.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[“Paris”, “England”, “Mumbai”, “Delhi”, “London”]
Section C
Each question carries 4 marks
11 Write SQL commands for the following queries (i) to (iv) based on the (4)
relations Product and Client given below:
Product:
P_ID ProductName Manufacturer Price Discount
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45 5
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120 10
FW12 Face Wash XYZ 95
(i) Write SQL query to display ProductName and Price for all products
whose Price is in the range of 50 to 150.
12. (i) Give two advantages and two disadvantages of bus topology (2)
OR
• Infrared
• Satellite Link
• Ethernet Cable