0% found this document useful (0 votes)
9 views63 pages

Part 3 Computer Science

This document provides an overview of computer networks, including definitions, benefits, and the evolution of networking from ARPANET to the Internet. It discusses data communication components, transmission media, network devices, topologies, and different types of networks such as LAN, MAN, and WAN. Additionally, it covers network protocols like HTTP, FTP, and TCP/IP that facilitate communication across networks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views63 pages

Part 3 Computer Science

This document provides an overview of computer networks, including definitions, benefits, and the evolution of networking from ARPANET to the Internet. It discusses data communication components, transmission media, network devices, topologies, and different types of networks such as LAN, MAN, and WAN. Additionally, it covers network protocols like HTTP, FTP, and TCP/IP that facilitate communication across networks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit : 2 introduction to Computer Networks

Network:-
The collection of interconnected computing devices is called a network. Two computing
devices are said to be interconnected if they are capable of sharing and exchanging
information.

Benefits of Network: -
(1) Resource Sharing: Resource Sharing means to make the
applications/programs, data(files) and peripherals available to anyone on the
network irrespective of the physical location of the resources and the user.
(2) Reliability: Reliability means to keep the copy of a file on two or more different
machines, so if one of them is unavailable (due to some hardware crash or any
other) them its other copy can be used.
(3) Cost Factor: Cost factor means it greatly reduces the cost since the resources can
be shared. For example a Printer or a Scanner can be shared among many
computers in an office/Lab.
(4) Communication Medium: Communication Medium means one can send and
receive messages. Whatever the changes at one end are done, can be
immediately noticed at another.
EVOLUTION OF NETWORKING
ARPANET (1969) – US Government formed an agency named ARPANET( Advanced
Research Project Agency Network) to connect computers at various universities and defence
agencies to share data/information efficiently among all of them.
NSFNET (1985) - National Science Foundation Network was a program of coordinated,
evolving projects sponsored by the National Science Foundation (NSF) from 1985 to 1995 to
promote advanced research and education networking in the United States. The program
created several nationwide backbone computer networks in support of these initiatives.
Initially created to link researchers to the NSF-funded supercomputing centers, through
further public funding and private industry partnerships it developed into a major part of
the Internet backbone.
INTERNET (1990)- INTER-connection NETwork , The worldwide network of networks.
Data communication terminologies:
Concept of communication: Communication is the act of sending and receiving data from
one device to another device or vice-versa. Data can be of any form i.e. text, image, audio,
video and multimedia files.
Components of Data communication:
Sender: A device that can send data over a network i.e. computer, laptop, smart phone etc.
Receiver: A device can receive data over a network i.e. computer, laptop, smart phone etc.
The sender and receivers are basically called nodes.
Message: It is the data/information that needs to be shared between the sender and
receiver.
Communication media: It is the medium through which the data/information is travelled
between the
sender and receiver. These may be wired or wireless.
Protocols: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network. Essentially, it allows connected
devices to communicate with each other, regardless of any differencesin their internal
processes, structure or design.
Measuring Capacity of Communication Media: In data communication, the transmission
medium is also known as channel. The capacity of a channel is the maximum amount of signals
or traffic that a channel can carry. It is measured in terms of bandwidth and data transfer rate
as described below:
Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of data
through that channel.
Higher the bandwidth, higher the data transfer rate.
Normally, bandwidth is the difference of maximum and minimum frequency contained in the
composite signals.
Bandwidth is measured in Hertz (Hz). 1
KHz = 1000 Hz, 1 MHz =1000
Data Transfer Rate
Data travels in the form of signals over a channel. One signal carries one or more bits over the
channel. Data transfer rate is the number of bits transmitted between source and destination
in one second. It is also known as bit rate. It is measured in terms of bits per second (bps).
The higher units for data transfer rates are:
1 Kbps=1024 bps
1 Mbps=1024 Kbps
1 Gbps=1024 Mbps
IP Address:
An IP address is a unique address that identifies a device on the internet or a local network.
IP stands for "Internet Protocol," which is the set of rules governing the format of data sent
via the internet or local network.
Switching techniques:
In large networks, there may be more than one path for transmitting data from sender to
receiver. Selecting a path that data must take out of the available options is called switching.
There are two popular switching techniques – circuit switching and packet switching.
Circuit switching: Circuit switching is a type of network configuration in which a physical
path is obtained and dedicated to a single connection between two endpoints in the network
for the duration of a dedicated connection. Ordinary landline telephone service uses
circuit switching.
Packet switching: Packet switching is the method by which the internet works; it features
delivery of packets of data between devices over a shared network. For example the school
web server is sending you a webpage over the internet or you sending an email to a friend.
Transmission Media: Transmission media is a communication channel that carries the
information from the sender to the receiver. All the computers or communicating devices in
the network must be connected to each other by a Transmission Media or channel.
 A Transmission medium is a medium of data transfer over a network.
 The selection of Media depends on the cost, data transfer speed, bandwidth and
distance. Transmission media may be classified as

Transmission Media: Guided (Wired)


Twisted Pair Cable: Twisted pair or Ethernet cable is most common type of media which
consists four insulated pairs of wires twisted around each other. It is low-cost, low-weight and
easy to install flexible cables. It can transfer data up to 1Gbps speed covering 100 meters
distance. It uses RJ-45 Connector for connecting computers and network devices. Co-axial
Cable: This type of cable consists a solid insulated wire surrounded by wire mesh, each
separated by some kind of foil or insulator. The inner core carries the signal and mesh
provides the ground. Co-axial Cable or Coax, is most common in Cable TV transmission. It
can carry data up to 500 meters.
Fiber Optic Cable: Optical fiber consists of thin glass or glass like material and carries light
signals instead of electric current. Signal are modulated and transmitted in the form of light
pulses from source using Light Emitting Diode (LED) or LASER beam. Optical fibers offer
secure and high-speed transmission up to a long distance.
Transmission Media: Unguided (Wireless)
Infrared Wave: It used for short-range (approx. 5 meters) communication using wireless
signals. It is mostly used in Remote operated devices like TV, Toys, Cordless phones etc.
Radio waves: Radio wave uses Radio frequencies (3KHz-3 GHz) to make broadcast
network like AM/FM network within city. Radio wave propagates in Omni direction
(surrounding) and penetrate solid walls/buildings.
Microwaves: Microwave are high energy radio waves, used for line of sight communication
using Parabolic antenna aligned with each other. It is high speed wave and can cover
distance up to 100 km).
Network Devices: Hardware device that are used to connect computers, printers, fax
machines and other electronic devices to a network are called network device. There are
many types of network devices used in networking and some of them are described below:
MODEM (Modulator Demodulator): It is a device that converts digital signal to analog
signal (modulator) at the sender’s site and converts back analog signal to digital signal
(demodulator) at the receiver’s end, in order to make communication possible via telephone
lines. It enables a computer to transmit data over telephone or cable lines.
There are two types of MODEM, which are as follows
(i) Internal Modem Fixed within a computer.
(ii) External Modem Connected externally to a computer.
Ethernet card: An Ethernet card in your computer serves one basic function: to transmit data
from the network to your computer. Ethernet cards are physical expansion cards that insert
into a PCI expansion slot on a computer.
RJ45: RJ45 connectors are commonly seen with Ethernet network cables. Ethernet cables
with RJ45 connectors are also called RJ45 cables. These RJ45 cables feature a small plastic plug
on each end, and the plugs are inserted into RJ45 jacks of Ethernet devices.
Hub: A Hub is a connecting device which connects multiple computers together to form a
Local Area Network (LAN). Hubs make broadcast type Network and do not manage traffic
over the network channel. Signal entering any port is broadcast out on all other ports. It
broadcast the signals to all computers connected in the network. It provides various RJ-45
ports to connect Twisted Pair cable in STAR topology, making them act as a single network
segment. Now days, Switch is used in place of Hubs.
Types of Hub:
 Active Hub: Amplifies the signal when required and works as a Repeater.
 Passive Hub: It simply passes the signal without any change.
Switch: A switch is a hardware device, which is used to connect several nodes to form a
Network. It redirects the received signals only to the intended Node i.e. controls Network
[Link] is also used to segment a big network into different Sub networks (Subnet) to
control the network traffic and security. It can also use to combine various small network
segments to form a big Network (as in Tree topology).
Hub V/s Switch: There is a vast difference between switch and hub. A hub forwards each
incoming packet (data) to all the hub ports, while a switch forwards each incoming packet to
the specified recipient.
Repeater: Repeater is a hardware device, which is used to amplify the signals when they are
transported over a long distance. The basic function of a repeater is to amplify the incoming
signal and retransmit it, to the other device.
Router: A router is used to connect different networks together. i.e. for two or more LANs to
be interconnected, you need a router
 The basic role of Routers in a network is to determine the best possible route
(shortest path) for the data packets to be transmitted. In a large network (WAN),
multiple routers works to facilitate speedy delivery of data packets.
 Router maintains a table of addresses (called routing table) that keeps a track of
paths connected to it.
Gateway:
 A gateway is a device, which is used to connect dissimilar networks. The gateway
establishes an intelligent connection between a local network and external
networks, which are completely different in structure.
 Gateway is also called protocol converter that convert data packets from one protocol to
other and connects two dissimilar networks.
 A gateway can be implemented in hardware, software or both, but they are usually
implemented by software installed within a router.
 A LAN gets connected to Internet (WAN) using a gateway.
Network Topologies:
Topology: Topology refers to the way in which the
device/computer/workstations attached to the network
are interconnected.
The layout of interconnection of devices in a network is
called Topology.
Different Topologies are: Star, Bus, Tree, Mesh.
BUS Topology: - The bus topology uses a common
single cable (backbone cable) to connect all the workstations. Each computer performs its
task of sending messages without the help of the central server. However, only one
workstation can transmit a message at a particular time in the bus topology.
Advantages:
(i) Easy to connect and install.
(ii) Involves a low cost of installation time.
(iii) Can be easily extended.
Disadvantages:-
(i) The entire network shuts down if there is a failure in the central cable.
(ii) Only a single message can travel at a particular time.
(iii) Difficult to troubleshoot an error.

STAR Topology: -In Star topology, each node is directly connected to a central device like Hub
or Switch. It is most popular topology to form Local Area Networks (LAN).
Advantages:
(i) Easy to troubleshoot
(ii) A single node failure does not affects the entire network.
(iii) Fault detection and removal of faulty parts is easier.
(iv) In case a workstation fails, the network is not affected.
Disadvantages: -
(i) Difficult to expand.
(ii) Longer cable is required.
(iii) The cost of the hub and the longer cables makes it expensive
over others.
(iv) All nodes are dependent on central node. if the central device (Switch) goes down
then entire network breaks down.

TREE Topology: - The tree topology combines the characteristics of the linear bus and the
star topologies. It consists of groups of star – configured workstations connected to a bus
backbone cable.
Advantages:
(i) Eliminates network congestion.
(ii) The network can be easily extended.
(iii) Faulty nodes can easily be isolated from the rest of the
network.
Disadvantages:
 Uses large cable length.
 Requires a large amount of hardware components and
hence is expensive.
 Installation and reconfiguration are very difficult.
Types of Computer Network:
A computer network may be small or big as per number of computers and other network
devices linked together. A computer network may contain devices ranging from handheld
devices (like mobile phones, tablets, laptops) connected through Wi-Fi or Bluetooth within a
single room to the millions of computers spread across the globe. Based on the size, coverage
area, data transfer speed and complexity, a computer network may be classified as:
LAN (Local Area Network): A Local Area Network (LAN) is a network that is limited to a
small area. It is generally limited to a geographic area such as within lab, school or building.
It is generally privately-owned networks over a distance up to a few kilometers. Now-a-days,
we also have WLAN (Wireless LAN) which is based on wireless network.
MAN (Metropolitan Area Network): MAN is the networks cover a group of nearby
corporate offices or a city and might be either private or public. Cable TV network or cable
based broadband internet services are examples of MAN.

WAN (Wide Area Network):These are the networks spread over large distances, say across
countries or even continents through cabling or satellite uplinks are called WAN. Typically, a
WAN combines multiple LANs that are geographically separated. It is a network of network.
The world’s most popular WAN is the Internet.
PAN (Personal Area Network): A Personal Area Network is computer network organized
around an individual person. It generally covers a range of less than 10 meters. Personal Area
Networks can be constructed with cables or wirelessly.

Comparison between PAN, LAN, MAN and WAN: -

Parameter PAN LAN MAN WAN


Area covered Small Area (upto A building or A city (upto 100 Entire country,
10m radius) campus (upto Km radius) Continent or
1 km) Globe
Networking Negligible inexpensive expensive Very expensive
Cost
Transmission Speed High High speed Moderate speed Low speed
speed
Error Rate Lowest Lowest Moderate Highest
Network WLAN, USB LAN/WLAN, Router, Gateway Router, Gateway
Devices used Dongle, Blutooth HUB/Switch,
Repeater,
Modem
Technology/ infrared, Ethernet, Wi- Optical fiber, Microwave,
Media used Bluetooth Fi Radio wave, Satellite
Microwave

Network Protocols:

HTTP (Hyper Text Transfer Protocol) :


 The Hyper Text Transfer Protocol is a set of rules which is used to access/retrieve
linked web pages across the web using web browser program.
 The more secure and advanced version is HTTP is HTTPS (HTTP Secure), which
controls the transfer of information in encrypted form to provide more security
and privacy.
 Other protocols like File Transfer Protocol (FTP) and Telnet can also be used with
URL. FTP is used to transfer files from web server to web client or vice-versa.
 Telnet is protocol which used for login on remote computer to access/transfer
files or trouble shooting.
FTP (File Transfer Protocol) is a network protocol for transmitting files between
computers over Transmission Control Protocol/Internet Protocol (TCP/IP) connections.
Point-to-Point Protocol (PPP) is a TCP/IP protocol that is used to connect one computer
system to another. Computers use PPP to communicate over the telephone network or the
Internet. A PPP connection exists when two systems physically connect through a telephone
line.

TCP/IP stands for Transmission Control Protocol/Internet Protocol and is a suite of


communication protocols used to interconnect network devices on the internet. TCP/IP is
also used as a communications protocol in a private computer network.
TELNET is commonly used by terminal emulation programs that allow you to log into a
remote host. However, TELNET can also be used for terminal-to-terminal communication
and interprocess communication. TELNET is also used by other protocols (for example, FTP)
for establishing a protocol control channel.
E-Mail (Electronic Mail):
Email is the short form of electronic mail. It is one of the ways of sending and receiving
message(s) using the Internet. An email can be sent anytime to any number of recipients at
anywhere. The message can be either text entered directly onto the email application or an
attached file (text, image, audio, video, etc.) stored on a secondary storage. An existing file
can be sent as an attachment with the email.
E-Mail Protocols:
Email are handled and exchanged through various mail servers in order to deliver email to
mail client. The mail client and mail servers exchange information with each other using
some protocols. The followings are commonly used protocols for email handling-
SMTP (Simple Mail Transfer Protocol): This protocol is used to send emails from
sender to recipient’s mail server.
IMAP (Internet Message Access Protocol): This is a standard client/server protocol for accessing e-
mails from local e-mail server.
POP3 (Post Office Protocol 3): This protocol facilitates users to access mailboxes and
download messages to their computer.
Voice over Internet Protocol (VoIP):
 Voice over Internet Protocol or VoIP, allows voice call (telephone service) over the
Internet. VoIP offers voice transmission over a computer network (IP) rather than
through the regular telephone network. It is also known as Internet Telephony or
Broadband Telephony. Examples of VoIP:- WhatsApp, Skype, Google Chat etc.
 VoIP works on the principle of converting the analogue voice signals into digital
and then transmitting them over the broadband line.
 These services are either free or very economical. That is why these days
international calls are being made using VoIP.

Overview of Internet:
 Internet is a network of networks that consists of millions of private, public,
academic, business, and government networks, that are linked by various wired,
wireless, and optical networking technologies.
 The Internet is a global system of interconnected computer networks that use the
standard Internet protocol suite (TCP/IP) to serve several billion users
worldwide.
 The modern Internet is an extension of ARPANET (Advance Research Project
Agency Network), created in1969 by the American Department of Defense.
 In 1990 the British Programmer Tim Berners-Lee developed Hypertext and HTML
to create World Wide Web (WWW).
 The Internet carries an extensive range of information resources and services,
such as the inter-linked hypertext documents of the World Wide Web (WWW), the
communicational infrastructure to support mail, chat and transfer of Text, Images,
Audio, Video etc.

Introduction to web services:

World Wide Web (WWW):


World Wide Web, which is also known as a Web, is a collection of websites or web pages
stored in web servers and connected to local computers through the internet. These
websites contain text pages, digital images, audios, videos, etc. Users can access the content of
these sites from any part of the world over the internet using their devices such as computers,
laptops, cell phones, etc. The WWW, along with internet, enables the retrieval and display of
text and media to your device.
There sources of the Web (HTML pages) are transferred via the Hypertext Transfer Protocol
(HTTP), may be accessed by users by a software application called a web browser, and are
published by a software application called a web server.
Tim Berners-Lee—a British computer scientist invented the revolutionary World Wide Web
in 1990 by defining three fundamental technologies that lead to creation of www: HTML
,URL, HTTP.

HTML(Hyper Text Markup Language):


Hyper Text Markup Language (HTML) is a language which is used to design standardized
Web Pages, so that the Web contents can be read and under stood from any computer using
web browser.
Basic structure of every web page is designed using HTML. HTML uses tags to define the way
page content should be displayed by the web browser. Web pages are stored as .html or .htm
files.
Extensible Markup Language (XML): Extensible Markup Language is a markup language
and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of
rules for encoding documents in a format that is both human-readable and machine-
readable.

Domain Name: A domain name is a unique, easy-to-remember address used to access


websites, such as '[Link]', and '[Link]'.

URL(Uniform Resource Locator):


URL—Uniform Resource Locator is a unique address of web resources located on the web. It
provides the location and mechanism (protocol) to access the resource. URL is sometimes
also called a web address.
A URL contains protocol, domain, sub domain and name of web page along with directory.

In the above URL, http is the protocol name, it can be https, http, FTP, Telnet, etc. www is a
sub domain. [Link] is the domain name. Textbook is directory and [Link] is
webpage.
The complete unique address of the page on a website is called URL (Uniform Resource
Locator) e.g. [Link]
Since computers on the network are identified by its IP addresses, so it is required to convert
a Domain name or URL typed in the Browser, in to its corresponding IP address. This
process is called Domain Name Resolution. This resolution is done by the designated servers
called DNS servers, provided by the Internet Service Providers (ISP) like BSNL, Airtel, Jio etc.
Website:
 Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
website.
 A website is a collection of web pages related through hyperlinks, and saved on a
web server. A visitor can navigate pages by clicking on hyperlinks.
 The main purpose of website is to make the information available to people at
large. For example, a company may advertise or sell its products, a government
organization may publish circulars, float tenders, invite applications for
recruitments etc.
 A website can be accessed by providing the address of the website (URL) in the
browser. The main page of website (Home page) will be open when it is opened
on the browser.
Web Page:
 A web page is a document on the WWW that is viewed in a web browser. Basic
structure of a web page is created using HTML (Hyper Text Markup Language).
 To make web pages more attractive, various styling CSS (Cascading Style Sheets)
and formatting are applied on a web page.
 Further, program codes called scripts also used to make webpage interactive and
define different actions and behavior. JavaScript, PHP and Python are commonly
used script language.
 The first page of the website is called a home page which contains Menus and
Hyperlinks for other web pages.
 A web page is usually a part of a website and may contain information in different
forms, such as: text, images, audio & video, Hyperlinks, interactive contents (chat
etc.)
A web page can be of two types: Static Web Page and Dynamic Web Page

Web Browsers:
 A web browser or simply ‘browser’ is a software application used to access
information on the World Wide Web. When a user requests some information, the
web browser fetches the data from a web server and then displays the webpage
on the user’s screen.
 The popular web browsers are Google Chrome, Mozilla Firefox, Internet Explorer,
Opera, Safari, Lynx and Netscape Navigator, Microsoft Edge etc.
 A web browser essentially displays the HTML documents which may include text,
images, audio, video and hyperlinks that help to navigate from one web page to
another. The modern browsers allow a wide range of visual effects, use encryption
for advanced security and also have cookies that can store the browser settings
and data.
Web Server:
 A web server is used to store and deliver the contents of a website to web clients
such as a browser.
 A Computer stores web server software and a website's contents (HTML pages,
images, CSS style sheets, and JavaScript files). The server needs to be connected to the
Internet so that its contents can be made accessible to others.
 Web server as a software, is a specialized program that understands URLs or web
addresses coming as requests from browsers, and responds to those requests.
 The server is assigned a unique domain name so that it can be accessed from
anywhere using Internet. The web browser from the client computer sends a HTTP
request for a page containing the desired data or service. The web server then accepts
request, interprets, searches and responds (HTTP response) against request of the
web browser. The requested web page is then displayed in the browser of the client. If
the requested web page is not found, web server generates “Error: 404 Not found” as
a response.
Web Hosting:
 A web hosting service is a type of Internet hosting service that allows individuals and
organisations to make their website accessible via the World Wide Web. In Simple,
uploading of website on Web Server is known as hoisting. To upload the website, we
need some web space on server to upload website. This space is available on some
nominal charges.
 All web servers are assigned a unique numeric address called IP address when
connected to the Internet. This IP address needs to be mapped/changed to domain name
(Textual name) of the website using DNS (Domain Name Service). Thus, user can access
website by providing domain name through a browser (URL). The domain name has to
be registered (purchased) with an authorized agency i.e. Registrar Domain Names.
QUESTIONS ON COMPUTER NETWORKING
MULTIPLE CHOICE QUESTIONS(1 MARK EACH)
1. ______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP (C) PPP (D) HTTP

2. Which of the following is used to receive emails over Internet?


a) SMTP b) POP c) PPP d) VoIP

3. What is the size of IPv4 address?


(a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes

4. _________protocol provides access to command line interface on a remote computer.

a)FTP b)Telnet c)VoIP d)SMTP


5. ______is a communication methodology designed to deliver electronic mail (E-mail) over
the internet.

. (a) VoIP (b) HTTP (c) PPP (d) SMTP


6. Which protocol is used for transferring files over a TCP/IP network?
a) FTP b) SMTP c) PPP d) HTTP

7. Network in which every computer is capable of playing the role of a client, or a server or
both at same time
is called
a) local area network b) peer-to-peer network c) dedicated server network d) wide
area network

8. ........................is a communication methodology designed to establish a direct and


dedicated communication between an internet user and his/her ISP.
a) VoIP (b) SMTP (c) PPP (d)HTTP

9. Identify the device on the network which is responsible for forwarding data from one
device to another
(a) NIC (b) Router (c) RJ45 (d) Repeater

10. Which of the following device send data to every connected node?
a)Switch b)Repeater c)Router d) Hub

11. In which type of switching first the connection is established between sender
and receiver and then the data is transferred?
a) Circuit b)Message c)Packet d)None

12. Identify the cable which consists of an inner copper core and a second
conducting outer sheath:
(i)Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
13. In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
14. Which of the following devices modulates digital signals into analog signals
that can be sent over traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem

15. Out of the following guided media, which is not susceptible to


external interference?
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire

16. Which of the following device is used for sorting and distribution of data packet
to their destination based on their IP Address?
(i) Gateway (ii) Router (iii) Bridges (iv) Switch

17. Which of the following device is used to connect network of different


protocols so that they can communicate properly?
(i) Gateway (ii) Router (iii) Bridges (iv) Switch

18. Which type of Network is generally privately owned and links the devices in a
single office, building or Campus?
a. LAN b. MAN c. WAN d. PAN

19. Raj, is working as a Tech Support Engineer and sometimes he wants to


work on Client’s computer from his office. Identify the traditional protocol
used for this purpose?
a. FTP [Link] c,HTTP d.POP3

20. Raj is looking for some information about How Router works, for this he
opens the browser and typed the URL of requested site. In few moments he
received the requested page on his browser screen. Identify the type of
protocol, used between Browser (Client) and Web Server for the
communication?
a. TCP/IP [Link] c,SMTP d.POP3

2 MARKS QUESTIONS
1. Write two points of difference between Bus topology and star topology.
2. Write two points of difference between XML and HTML.
3. Write the full forms of the following:
(i) HTTP (ii) FTP
4. Discuss the use of TELNET
5. Write two advantages and two disadvantages of circuit switching.
6. Differentiate between Web server and web browser. Write any two popular web browsers.

7. Classify each of the following Web Scripting as Client Side Scripting and
Server Side Scripting :
(i) Java Scripting
(ii) ASP
(iii) VB Scripting
(iv) JSP

8. What is Bandwidth? What is the measuring unit of Bandwidth in term of range


of frequencies a channel can pass?
9. (a) Write the full forms ithe following:
(i) FTP (ii) HTTPS
b)Name the protocols which are used for sending and receiving emails?

10. Write two differences between Coaxial and Fiber transmission media.

5 MARKS QUESTIONS
1. A professional consultancy company is planning to set up their new offices in India with its
hub at
Hyderabad. As a network adviser, you have to understand their requirement and suggest them
the best
available solutions. Their queries are mentioned as (i) to (v) below.

a) Which will be the most appropriate block, where TTC should plan to install their server?

b) Draw a block to block cable layout to connect all the buildings in the most appropriate
manner for efficient communication.

c) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bengalore with its London based office.
● Satellite Link
● Infrared
● Ethernet

d) Which of the following device will be suggested by you to connect each computer in each
of the buildings?
● Switch
● Modem
● Gateway

e) Company is planning to connect its offices in Hyderabad which is less than1 km. Which
type of network will be formed?

Sol: (i) The company should install its server in finance block as it is having maximum
number of computers.
(ii) The layout is based on minimum cable length required, which is 120 metres in the
above case.
(iii) Satellite Link.
(iv) Switch.
(v) LAN

2. FutureTech Corporation, a Bihar based IT training and development company, is planning to


set up training centers in various cities in the coming year. Their first centeris coming up in
Surajpur district. At Surajpur center, they are planning to have 3different blocks - one for
Admin, one for Training and one for Development. Each block has number of computers,
which are required to be connected in a network for communication, data and resource
sharing. As a network consultant of this company,you have to suggest the best network related
solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind the
distances between variousblocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur
center (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.

(ii) Suggest why should a firewall be installed at the Surajpur Center?

(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to
most efficiently connect various blocks within the Surajpur Center.

(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router

(v) Suggest the best possible way to provide wireless connectivity between Surajpur Center
and Raipur Center.

Sol: i) Development because it contains more number of computers


ii) Surajpur centre has multiple blocks and firewall ensures security. So it is required. It
allows or block unwanted attacks.
iii)

iv) a) Switch/Hub – In every block to interconnect the devices within every block
b) Router -In development block because server is going to be placed here
v) Satellite

3. Total-IT Corporation, a Karnataka based IT training company, is planning to set up


training
centers in various cities in next 2 years. Their first campus is coming up in Kodagu district.
At Kodagu campus, they are planning to have 3 different blocks, one for AI, IoT and
DS (Data Sciences) each. Each block has number of computers, which are required to
be connected in a network for communication, data and resource sharing. As a network
consultant of this company, you have to suggest the best network related solutions for them
for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between
various blocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
Ans: IoT block, as it has the maximum number of computers.

(ii) Suggest a device/software to be installed in the Kodagu Campus to take care of data
security.
Ans:Firewall

(iii) Suggest the best wired medium and draw the cable layout (Block toBlock) to most
efficiently connect various blocks within the Kodagu Campus.
Ans:Optical fiber
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
Sol:a) Switch/Hub: In each block to interconnect the computers in that block.
b) Router: In IoT block (with the server) to interconnect all the three blocks.

(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between
Kodagu Campus and Coimbatore Campus.
Sol:VoIP

4. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web
based activities. The company compound has 4 buildings as shown in the diagram below:

i) Suggest a cable layout of connections between the buildings.


ii) Suggest the most suitable place (i.e. building) to house the server of this organisation
with a
suitable reason

iii) Suggest the placement of the following devices with justification:


a. Internet Connecting Device/Modem
b. Switch

iv) The organisation is planning to link its sale counter situated in various parts of the
same city,
which type of network out of LAN, MAN or WAN will be formed? Justify your answer.

v) What do your mean by PAN? Explain giving example.

Sol: i)

ii) Orbit Building


iii) a. Internet Connecting Device/Modem- Orbit Building
b. Switch- Each Building
iv) MAN, it is formed to connect various locations of the city via various
communication media.
v) PAN is “Personal Area Network”, basically configured at home area.

5. Magnolia Infotech wants to set up their computer network in the Bangalorebased campus
having four
buildings. Each block has a number of computers that are required to be connected for ease of
communication, resource sharing and data security. You are required to suggest the best
answers to
the questions i) to v) keeping in mind the building layout on the campus.
i) Suggest the most appropriate block to host the Server. Also justify your choice.

ii) Suggest the device that should should be placed in the Server building so that they can
connect to Internet Service Provider to avail Internet Services.

iii) Suggest the wired medium and draw the cable block to block layout to economically
connect the various blocks.

iv) Suggest the placement of Switches and Repeaters in the network with justification.

v) Suggest the high-speed wired communication medium between Bangalore Campus and
Mysore campus to
establish a data network.

Sol: i) Admin Block since it has maximum number of computers.


ii) Modem should be placed in the Server building
iii) The wired medium is UTP/STP cables.

iv) Switches in all the blocks since the computers need to be connected to the network.
Repeaters between Admin and HR block& Admin and Logistics block. The reason
being the distance is more than 100m.
v) Optical Fiber cable connection.
Unit : 3 Database Management and Mysql

Relational
Database
Model
Introductory
Database
Concepts of
Constraints
Database

Database
Management

Common Database
Database Languages
Operations & SQL

Database
Keys

Structured Query Language (SQL)

SQL

DDL DML TCL Query

Operations in SQL

SELECT ALIAS ORDER BY


MATHS RELATIONAL LOGIC
OPERATION OPS OPS
IN / IS / LIKE /
NOT IN IS NOT NOT LIKE
DISTINCT GROUP BY HAVING
EQUI NATURAL CARTESIAN
JOIN JOIN PRODUCT
Database Management System (DBMS)

Common Terminologies related to database:


 Data -> Raw facts or figures
 Database -> A collection of interrelated data.
 DBMS -> A collection of files and a set of programs allowing users to access/modify
these files are known as Database Management System.
 Data Redundancy - > Duplication of data.
 Data Security -> Protection of data against accidental/intentional disclosure to
unauthorized person or unauthorized modification/destruction.
 Data Privacy -> Right of individual/organization to determine when/how/what information
to be transmitted to others.

Need of using Database:


 Helps to store data in a structured manner
 Query in the Database (i.e. ask questions about the data)
 Sort and Manipulate Data in the Database
 Validate the Data Entered and check for inconsistencies
 Produce Flexible Reports
Advantage of using Database:
 Reduce data redundancy
 Control inconsistency
 Facilitates sharing of data
 Enforce standards
 Ensure data security
 Maintain integrity
Limitations of implementing Database:
 Compromise of Security and Integrity without good control
 Performance overhead
 Extra hardware required sometimes
 Complex system
Types of DBMS:
 Hierarchical DBMS
 Network Based DBMS
 Object Based DBMS
 Relational DBMS

RELATIONAL DATA MODEL


Relational Data Model is defined as a model of defining a database as a collection of
tables/relations i.e. arrangement of values in rows/tuples and columns/fields/attributes.
Common Terminologies related to Relational Data Model:
 Relation: Collection of data organized in rows and columns where each cell has atomic
value. (same as Table)
 Tuple: Row of a table (same as Record)
 Attribute: Column of a table (same as Field)
 Domain: Range of values (data types) allowed for an attribute
 Degree: No. of attributes/columns/fields in a table
 Cardinality: No. of tuples/rows/records in a table
 View: Virtual table (no physical existence) derived from one or more base table for ease of
query only.
 Referential Integrity: Property of database that requires every value of one attribute of a
Relation must be present in another attribute (same datatype) in a different (or the same)
relation.
Example:

In the above table STUDENT, degree = 7 and cardinality = 5.

Database Key
Key in a database is defined as a set of attributes to identify each record uniquely in a table. A Key
must be unique and not null.
Classification of Keys:

Key

Candidate Primary Key Alternate Key Foreign Key


 Key Key
 Candidate Key: Candidate key is defined as a set of minimum no. of attributes to uniquely
identify a record in a table. A table may have multiple candidate keys.
 Primary Key: The one candidate key chosen by Database Administrator for a table to
uniquely identify a record in a table is said to be Primary Key of that table. A table can have
exactly one Primary Key.
 Alternate Key: Candidate key(s) not chosen by Database Administrator in a table is/are
defined as alternate key(s). A table can have 0 or more alternate keys.
 Foreign Key: Foreign Key is a non-key attribute derived from primary key of some other
table. A table can have 0 or more foreign keys.

Data types in SQL


 Numeric data types: Used for representing number in a column
e.g. –
int(m) – Integer of maximum length m i.e. maximum number of digits allowed in m.
float(m,d), decimal (m,d), numeric(m,d) – Real number of maximum length m where
maximum number of digits permissible after decimal point is d and before decimal point is
m-d.

 Date & Time data types: Used to represent date, time, or both in a column. Data is enclosed
with quotes ‘ ’ or “ “.
e.g. - date, datetime, time

 String / Text data types: Used to represent text in a column. Data is enclosed with quotes ‘ ’
or “ “.
e.g. –
char(m) – Fixed length character of length m where 1 character takes 1 Byte in memory.
Memory space is wasted if text size is less than m.
varchar(m) – Variable length character allowing maximum number of characters m. It
saves memory allocation for text having lesser size than m.

blob – Binary Large object for huge size text.

 NULL – NULL is said to be the absence of any value in a column. No arithmetic or


comparison operation can be performed on NULL value.

Classification of Database Language

Data Definition Language (DDL):


Data Definition Language (DDL) defines the different structures in a database like table, view,
index etc.
DDL statements are used to create structure of a table, modify the existing structure of the table
and remove the existing table.
e.g. - CREATE, ALTER, DROP
Syntax of DDL statements:
 CREATE TABLE table_name
(column_name datatype constraint)
 ALTER TABLE table_name
ADD column datatype constraint (if any)
MODIFY column new_datatype new_constraint (if any)
DROP column
 DROP TABLE table_name

Data Manipulation Language (DML):


Data Manipulation Language (DML) statements are used to access and manipulate
data in existing tables.
The manipulation includes inserting data into tables, deleting data from the tables and modifying
the existing data.
e.g. – INSERT, UPDATE, DELETE

Types of DML statements:


 INSERT record
INSERT INTO table_name(columns) VALUES (1 or more comma separated values)
 UPDATE one or more columns in already existing record(s)
UPDATE table_name SET column = value or expression
(comma separated if multiple columns updated) WHERE condition
 DELETE record
DELETE FROM table_name WHERE condition

Transaction Control Language (TCL):


Database ensures that a database transaction i.e. complete set of records involved in a transaction
either fully completed or not taken place at all to maintain data consistency. Transaction Control
Language (TCL) statements allows to save or revert database transactions.
e.g. –
COMMIT – Save the changes permanently in the database
ROLL BACK – Revert back the changes made in database

Query:
Query is a type of SQL commands which accepts tables (relations), columns (fields or attributes)
and conditions or specifications if any and display the output by means of a temporary table which
consists of data represented through fields and records.
Structure of Query:
SELECT < 1, multiple ( comma i.e. , separated) or all columns >
FROM < 1 table or multiple tables ( comma i.e. , separated) in case of join >
WHERE <condition on column(s)>
GROUP BY <1 column>
HAVING < condition on aggregate function on a column only if group by exists >
ORDER BY <0, 1 or more ( comma i.e. , separated) columns >
Note:
I. Among above SELECT and FROM are mandatory statements in a query and all other
statements are optional.
II. SELECT statement contains one or more columns. * should be used to display all columns.
Functions or expressions on columns can also be done.
III. FROM statement contains multiple tables only if columns from more than one tables are
displayed through SELECT statement in case of product or join operations. Here records
can be fetched from multiple tables.
IV. WHERE clause may contain multiple conditions related with logical OR / AND operators.
Logical NOT operator can be used on a condition also.
V. GROUP BY clause is used if statistical records are to be displayed based on a field/column.
In this case SELECT statements should contain GROUP BY field and aggregate function
on another column at least. Once a group is formed individual records cannot be accessed
in the same query.
VI. ORDER BY clause can be used to arrange the output records in ascending (by default) or
descending order of values in one or more columns.
Order of execution of a query
Step 1: Identify table(s) with FROM clause
Step 2: Filter records using WHERE clause
Step 3: Form group if any using GROUP BY clause
Step 4: Filter groups using HAVING clause only if GROUP BY is used
Step 5: Arrange the output records in ascending or descending order using ORDER BY
Step 6: Display the fields mentioned in SELECT clause.

Database Constraints
Rules imposed on the values of one or more columns in the tables are called database constraints.
The database constraints are:
UNIQUE Ensures that all values in a column are different. No two records have
same values in that column.
NOT NULL Ensures that a column can never have NULL values.
PRIMARY KEY Uniquely identify a record. It is a combination of UNIQUE and NOT
NULL.
CHECK Specify the domain of values with certain criteria for a column.
DEFAULT Provides default value for a column when no value is specified.
REFERENCES / Ensures referential integrity between the foreign key of dependent /
FOREIGN KEY referencing table and primary key of independent / referenced table.

SQL STATEMENTS WITH EXAMPLES


Create two tables EMPL and DEPT as follows:
In DEPT table:
1. DEPT_ID is primary key
2. DNAME is not null
3. MAX_STRENGTH should be minimum 1
In EMPL table:
1. EID is primary key
2. ENAME is not null
3. HOMETOWN is ‘BANGALORE’ by default
4. SALARY is between 5000.00 and 300000.00
5. MGR_ID refers to EID of manager
6. DEPT_ID refers to DEPT_ID of table DEPT
A. Write DDL statement to create a database OFFICE and define two tables mentioned as above
under OFFICE database.
Create new database OFFICE in MySQL as following:
CREATE DATABASE OFFICE;
Work inside the database OFFICE as following:
USE OFFICE;
Note: By default, TEST database is used which is in-built database in MySQL. So no need to
create test. Only ‘use test;’ statement can be written to enter test.
DDL statement to create DEPT table is as following:
SOLUTION 1 SOLUTION 2
CREATE TABLE DEPT CREATE TABLE DEPT
( (
DEPT_ID VARCHAR(4) PRIMARY KEY, DEPT_ID VARCHAR(4),
DNAME VARCHAR(15) NOT NULL, DNAME VARCHAR(15) NOT NULL,
DLOC VARCHAR(20), DLOC VARCHAR(20),
MAX_STRENGTH INT(2) CHECK MAX_STRENGTH INT(2),
(MAX_STRENGTH >= 1) PRIMARY KEY(DEPT_ID),
); CHECK (MAX_STRENGTH >= 1)
);
Schema or structure of table DEPT is as follows:

DESC DEPT;

DDL statement to create EMPL table is as following:

CREATE TABLE EMPL


(
EID VARCHAR(6) PRIMARY KEY,
ENAME VARCHAR(30) NOT NULL,
GEN CHAR(1) CHECK (GEN IN ('M', 'F', 'T')),
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) CHECK (SALARY BETWEEN 5000 AND 300000),
MGR_ID VARCHAR(6) REFERENCES EMPL(EID),
DEPT_ID VARCHAR(4) REFERENCES DEPT(DEPT_ID)
);

or,
CREATE TABLE EMPL
(
EID VARCHAR(6),
ENAME VARCHAR(30) NOT NULL,
GEN CHAR,
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) ,
MGR_ID VARCHAR(6) ,
DEPT_ID VARCHAR(4) ,
PRIMARY KEY(EID),
CHECK (GEN IN ('M', 'F', 'T')),
CHECK (SALARY BETWEEN 5000.00 AND 300000.00),
FOREIGN KEY(MGR_ID) REFERENCES EMPL(EID),
FOREIGN KEY(DEPT_ID) REFERENCES DEPT(DEPT_ID)
);

Schema or structure of table EMPL is as follows:

DESC EMPL;
Name of tables defined in current database so far.

SHOW TABLES;

B. Write DML statements to insert records in two tables.

DML statements to insert records in DEPT are as follows:

INSERT INTO DEPT VALUES ('D01', 'FINANCE', 'MUMBAI', 20);

INSERT INTO DEPT VALUES ('D02', 'ADMIN', 'KOLKATA', 15);

INSERT INTO DEPT VALUES ('D03', 'IT', 'CHENNAI', 5);

DML statements to insert records in EMPL are as follows:

INSERT INTO EMPL VALUES ('E0001', 'RITU SEN', 'F', '2002-06-20', 'KOLKATA',
40000.00, NULL, 'D03');

INSERT INTO EMPL VALUES ('E0002', 'MALCOM RAY', 'M', '1998-11-12',


'BANGALORE', 50000.00, NULL, 'D02');

INSERT INTO EMPL(EID, ENAME, GEN, DOJ, HOMETOWN, SALARY, DEPT_ID)


VALUES ('E0003', 'SUNDAR P', 'M', '2008-12-09', 'BANGALORE', 40000.00, 'D01');

INSERT INTO EMPL VALUES ('E0004', 'ANISHA RAWAT', 'F', '2019-09-04', 'DELHI',
20000.00, 'E0001', 'D03' );

INSERT INTO EMPL VALUES ('E0005', 'SANA KHAN', 'F', '2017-08-31', 'DELHI',
30000.00, 'E0003', 'D01');

C. Write SQL statements for the following queries and display their outputs.

1. Display all the records from table DEPT.


SELECT * FROM DEPT;

2. Display name and salary of all the employeEs from table EMPL.
SELECT ENAME, SALARY
FROM EMPL;
4. Display DNAME in ascending order of MAX_STRENGTH.

SOLUTION 1 SOLUTION 2 OUTPUT


SELECT DNAME SELECT DNAME
FROM DEPT FROM DEPT
ORDER BY ORDER BY
MAX_STRENGTH; MAX_STRENGTH ASC;

Note:
 Sorting in SQL is by default in ascending order of values be it numeric or alphabetical
order. Hence ASC is default keyword and need not be used in ORDER BY statement.
 In case of arranging the output of query in descending order of values DESC keyword must
be used in ORDER BY statement.

Comparison operators
= > < >= <= <> !=

4. Display name and gender of employees whose hometown is BANGALORE.


SOLUTION OUTPUT
SELECT ENAME, GEN
FROM EMPL
WHERE HOMETOWN =
'BANGALORE';

5. Display the name of departments which are not located in KOLKATA.

SOLUTION 1 SOLUTION 2 OUTPUT


SELECT DNAME SELECT DNAME
FROM DEPT FROM DEPT
WHERE DLOC <> WHERE DLOC !=
KOLKATA'; 'KOLKATA';

6. Display name of employees and salary in descending order of names where DEPT_ID is
not 'D03'.
SOLUTION OUTPUT
SELECT ENAME,
SALARY
FROM EMPL
WHERE DEPT_ID !=
'D03'
ORDER BY ENAME
DESC;

7. Display EID, ENAME of employees whose DOJ is after January, 2015.

SOLUTION OUTPUT
SELECT EID, ENAME
FROM EMPL
WHERE DOJ > '2015-01-31' ;

[Note: DATE should be preferably mentioned in 'yyyy-mm-dd' format.]

Logical Operators
OR AND NOT
Logical operators are used in where clause. AND, OR are binary operations which require 2
conditions. NOT is unary operator which requires one condition only.
 AND : c1 and c2 → If both c1 and c2 are true the overall condition is true.
 OR : c1 or c2 → If at least one between c1 or c2 are true the overall condition is true.
 NOT : not c1 → If c1 is true the overall condition is false and vice versa.

BETWEEN: BETWEEN operator can be used as a substitute of and operation where the minimum
and maximum value is to be checked for a single column.

8. Display the records of those employees whose salary is between 35000 and 45000.
SOLUTION1 SOLUTION2
SELECT * FROM EMPL SELECT * FROM EMPL
WHERE SALARY >=35000 WHERE SALARY BETWEEN
AND SALARY <=45000; 35000 AND 45000;
Checking a list of values

IN: IN operator is a substitute of OR operation(s) among equality checking of a single column with
multiple values.
NOT IN: NOT IN operator is used for non-equality checking of a column with multiple values.

9. Display name and hometown of employees who belong to departments 'D01' or 'D02'.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT ENAME, SELECT ENAME,
HOMETOWN HOMETOWN
FROM EMPL FROM EMPL WHERE
WHERE DEPT_ID = 'D01' DEPT_ID IN ('D01', 'D02');
OR DEPT_ID = 'D02';

10. Display EID and SALARY of employees whose half of salary is neither 10000 nor 20000.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT EID, SALARY SELECT EID, SALARY
FROM EMPL FROM EMPL
WHERE NOT (SALARY/2 = WHERE SALARY/2 NOT
10000 OR SALARY/2 = IN (10000, 20000);
20000);

Wildcard Characters

A string constant to be checked with a value stored in a column may have one or more characters
missing in case of sub string checking. Such placeholder can be of two types:
_ → Replacement or placeholder of exactly one character in the string constant value.
(underscore)
% → Replacement or placeholder of 0 or more characters in the string constant value.

LIKE: A string constant containing one or more wildcard characters can be checked for equality
with LIKE operator only, not =.
NOT LIKE: Likewise NOT LIKE operator checks inequality checking with a string constant
containing one or more wildcard characters. It cannot be done using <> or !=.

11. List the name of employees whose name starts with 'S' and have length at least 5.
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE 'S____%';

[Hints: 4 underscores i.e. _ after S]


12. List the name of employees whose name ends with 'N' or does not contain 'M' in it.

SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE '%N'
AND ENAME NOT LIKE '%M%';

NULL checking
IS: IS is a special operator which is used to check absence of value i.e. NULL in a column as no
other comparison operator can be used on NULL values.
IS NOT: Likewise, IS NOT is used to check the presence of values i.e. NOT NULL in a column.
13. Print ENAME and DEPT_ID of employees who do not have manager i.e. MGR_ID is blank.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NULL;

14. Print ENAME and DEPT_ID of employees who have manager i.e. MGR_ID is not empty.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NOT NULL;

Display redundant or unique values


ALL: ALL keyword allows all the values occurring including duplicate values to be displayed in
output. SQL allows duplicate values in output. ALL is by default used in SQL, so need not be used
explicitly.
DISTINCT: By default, SQL does not remove any duplicate values in the output on its own.
Hence DISTINCT keyword is used along with a column where redundant values need to be
removed before displayed.
15. List the hometowns of all the employee (Including duplicate values).
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT SELECT ALL
HOMETOWN HOMETOWN
FROM EMPL; FROM EMPL;

16. List the name of places which are hometown of any employee. (No duplicate values)
SOLUTION OUTPUT
SELECT DISTINCT
HOMETOWN
FROM EMPL;

Aggregate functions

SUM( ) AVG( ) MAX( ) MIN( ) COUNT( )

Aggregate or statistical functions can be used on a group of records.


Using GROUP BY clause: Display outputs regarding each group formed by the GROUP BY field.
Without using GROUP BY clause: Display output corresponding to the overall table may or may
not be filtered by where clause.
For example, consider the following ITEM table:

GROUP BY: GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Once the group is formed individual records cannot be accessed in that query. Several
clusters or groups are formed based on the number of different values in the GROUP BY column
present in the table.
For example, if GROUP BY is applied on TYPE field of ITEM table 3 groups are formed – Crops
have 2 records, Leaves and Pulses have one record each.
Renaming field and table
AS is an optional keyword to rename a column a table in FROM clause or an expression on
column(s) in SELECT clause. If there is blank space in alias then it must be surrounded by ' ' or '' ''.
Column renaming is done for customized display of query output.
Table renaming is done for giving convenient names to the tables in join operations for
ease of access by programmers.
17. Display the number of distinct DLOC mentioned in table DEPT.
SOLUTION OUTPUT
SELECT COUNT(DISTINCT DLOC) as 'NO. OF
LOCATIONS'
FROM DEPT;

18. Display the earliest and latest DOJ of employees as per EMPL.
SOLUTION OUTPUT
SELECT MIN(DOJ) 'EARLIEST', MAX(DOJ)
'LATEST'
FROM EMPL;

19. Display the number of employees of each gender GEN.


SOLUTION OUTPUT
SELECT GEN, COUNT(*) COUNT
FROM EMPL
GROUP BY GEN;

20. Display the total SALARY paid by each department.


SOLUTION OUTPUT
SELECT DEPT_ID, SUM(SALARY) 'TOTAL
SALARY'
FROM EMPL
GROUP BY DEPT_ID;

HAVING: It is a conditional statement used along with group by clause only. It compares the
values with the outcome of aggregate functions belonging to each group already formed by
GROUP BY clause.
Difference between WHERE and HAVING:

21. Display the hometowns and no. of employees belonging to them if the headcount per
hometown is at least 2.
SOLUTION OUTPUT
SELECT HOMETOWN, COUNT(EID) 'NO
OF EMPLOYEE'
FROM EMPL
GROUP BY HOMETOWN
HAVING COUNT(EID) >= 2;

22. Display the number of employees working in each DEPT_ID excepting 'D01' where no. of
employees in the DEPT_ID is more than 1.
SOLUTION OUTPUT
SELECT DEPT_ID, COUNT(*) AS 'NO OF
EMPLOYEE'
FROM EMPL
WHERE DEPT_ID != 'D01'
GROUP BY DEPT_ID
HAVING COUNT(*) > 1;

Cartesian Product
Cartesian product is performed on two tables and it produces all the combination of records in both
tables. It does not require any common column.
If tables A, B have m, n columns and p, q records respectively then resultant table A x B has m+n
columns and p x q records.
23. Perform Cartesian Product between EMPL and DEPT.
SOLUTION 1 SOLUTION 2 SOLUTION 3
SELECT * SELECT * SELECT *
FROM EMPL, DEPT; FROM EMPL INNER JOIN FROM EMPL JOIN
DEPT; DEPT;
[RECOMMENDED
STATEMENT]
JOIN
NATURAL JOIN: Natural join is a binary operator which works on two tables. They should have
one column which have same name and domain. It a combination of Cartesian product and a where
clause with equality checking on the common columns.
 Other conditions in that query are ANDed with the join condition.
 Natural join is mostly done on Foreign key field of one table and Primary key field of
another table.
 If tables A, B have m, n columns and p, q records respectively then resultant table has m+n
columns and minimum(p,q) records.

EQUI JOIN: Equi join is a join operation which works on the equality condition of values in two
columns from two tables having similar data type. NATURAL JOIN, EQUI JOIN are said to be
INNER JOIN.
24. Perform Natural Join between these two tables.
SOLUTION 1 SOLUTION 2
SELECT * SELECT *
FROM EMPL NATURAL JOIN FROM EMPL, DEPT
DEPT; WHERE EMPL.DEPT_ID =
DEPT.DEPT_ID;
[RECOMMENDED STATEMENT]

25. Display every ENAME and their corresponding DNAME.


SOLUTION OUTPUT
SELECT ENAME, DNAME
FROM EMPL, DEPT
WHERE EMPL.DEPT_ID = DEPT.DEPT_ID;

26. List the name of employees who work in ADMIN department.


SOLUTION OUTPUT
SELECT ENAME
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DNAME = 'ADMIN';

27. Display no. of employees working in those departments whose DLOC is CHENNAI.
SOLUTION OUTPUT
SELECT COUNT(*) 'NO. OF EMPLOYEES'
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DLOC = 'CHENNAI';

28. Display ENAME of employees who have manager along with that display ENAME of their
corresponding manager as well.
SOLUTION OUTPUT
SELECT [Link] 'EMPLOYEE', [Link]
'MANAGER'
FROM EMPL E, EMPL M
WHERE E.MGR_ID = [Link];

29. Display ENAME and the amount of bonus to be paid to that employee where bonus = 5000 +
5% of SALARY.
SOLUTION OUTPUT
SELECT ENAME, SALARY,
5000 + 0.05 * SALARY 'BONUS'
FROM EMPL;

D. Write DML statements for the following purpose:


1. Assign DEPT_ID 'D03' to those employees who are presently working at 'D02'.
SOLUTION OUTPUT
UPDATE EMPL
SET DEPT_ID = 'D03'
WHERE DEPT_ID = 'D02';

SELECT * FROM EMPL;

2. Increase SALARY of all the employees by 10%.


SOLUTION OUTPUT
UPDATE EMPL
SET SALARY = 1.1 *
SALARY;

SELECT * FROM EMPL;

3. Delete the department 'D02' from DEPT table.


SOLUTION OUTPUT
DELETE FROM DEPT
WHERE DEPT_ID = 'D02';

SELECT * FROM DEPT;


E. Write DDL statements for the following purpose:
1. Add DPHONE field to table DEPT which should be a number of 10 digits and unique for each
department.
SOLUTION OUTPUT
ALTER TABLE DEPT
ADD DPHONE INT(10) UNIQUE;

DESC DEPT;

2. Drop the column MAX_STRENGTH from DEPT.


SOLUTION OUTPUT
ALTER TABLE DEPT
DROP MAX_STRENGTH;

SELECT * FROM DEPT;

3. Modify the datatype of SALARY in table EMPL to an integer of length 6 and drop the existing
check constraint.
SOLUTION OUTPUT
ALTER TABLE EMPL
MODIFY SALARY INT(6);

DESC EMPL;

Questions ;
Q. No. 1 to 20 are MCQs of 1 mark each

1. An attribute in a table is foreign key if it is the _________key in any other table.


a) Candidate b) Primary c) Unique d) Alternate
2. What is the domain of an attribute?
(a) The set of possible values that the attribute can take
(b) The name of the attribute
(c) The data type of the attribute
(d) None of the above
3. Which of the following is not a database constraint?
a. CHECK b. DEFAULT c. UNIQUE d. NULL
4. The data types CHAR (n) and VARCHAR (n) are used to create _______ and
_______ types of string/text fields respectively in a database.
a) Fixed, equal b) Equal, variable c) Fixed, variable d) Variable, equal
5. Which of the following is a DDL command?
A. UPDATE B. INSERT C. DELETE D. ALTER
6. Which command is used to open the database “SCHOOL”?
a. USE SCHOOL b. OPEN SCHOOL
c. USE DATABASE SCHOOL d. SHOW SCHOOL
7. In the given query which keyword has to be inserted?
INSERT INTO employee______(1002, “Kausar”, 2000);
a) Value b) Values c) Values into d) Into Values
8. Which SQL statement is used to display all the data from PRODUCT table in the
decreasing order of PRICE?
a. SELECT * FROM PRODUCT ORDER PRICE BY DESC ;
b. SELECT * FROM PRODUCT PRICE ORDER BY DESC;
c. SELECT * FROM PRODUCT ORDER BY DESC PRICE;
d. SELECT * FROM PRODUCT ORDER BY PRICE DESC;
9. Which of the following function is used to FIND the largest value from the given
data in MYSQL?
a) MAX () b) MAXIMUM () c) LARGEST () d) BIG ()
10. Which keyword is used for aliasing a table?
a) ASC b) AS c) IS d) None of these
11. __________ aggregate function does not ignore NULL values in a column.
a) Min() b) Sum() c) Avg () d) Count ()
12. SELECT name FROM class WHERE subject_____NULL;
Which comparison operator may be used to fill the blank space in above query?
a) = b) LIKE c) IS d) <>
13. Which SQL statement is used to display all the data from ITEMS table where
INAME is ending with ‘L’?
a. SELECT * FROM ITEMS WHERE INAME LIKE ‘L%’;
b. SELECT * FROM ITEMS WHERE INAME LIKE ‘%L’;
c. SELECT * FROM ITEMS WHERE INAME LIKE ‘%L%’;
d. SELECT * FROM ITEMS WHERE INAME LIKE ‘_L_’;
14. Which join combines each row from the first table with every row from the
second table to make the result set?
a. CROSS JOIN b. OUTER JOIN c. INNER JOIN d. EQUI JOIN

State True / False for Q. No. 15 and 16


15. MySQL statement to delete a table STUDENT from the database SCHOOL is
DELETE TABLE STUDENT;
16. Where and Having clauses can be used interchangeably in SQL queries.

Q. No. 17 to 20 are ASSERTION ( A ) and REASONING ( R ) based questions.


Mark the correct choice as:
a. Both A and R are true and R is the correct explanation for A.
b. Both A and R are true and R is not correct explanation for A.
c. A is true but R is false.
d. A is false but R is true.
17. Assertion (A): A foreign key in the relational data model is a set of attributes in
one
relation that references the primary key of another relation.
Reason (R): Foreign keys are used to establish relationships between tables.

18. Assertion(A): DBMS is an application package which arranges the data in orderly
manner in a tabular form.
Reason(R): It is an interface between database and the user. It allows the users to
access and perform various operations on stored data using some tools.

19. Assertion(A): Aggregate function AVG() calculates the average of a set of values
and produces a single value as result.
Reason(R): The aggregate functions are used to perform some basic calculations
like sum, max, min, etc on a set of numbers.

20. Assertion(A): While inserting records in EMP table, value of DateOfBirth field
must be enclosed withing quotes ‘ ‘.
Reasoning(R): Date is represented as char / varchar always.

Q. No. 21 to 30 are questions of 2 marks each


21. a) What do you mean by degree and cardinality of a table?
b) Consider the following table and find its degree and cardinality.

22. What do you mean by referential integrity? Explain with suitable example.

23. Write MySQL statement to create a table named REMEDIAL based on the
following specification:
Table: REMEDIAL
Attribute Data type Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY

24. Write MySQL statements to do the following:


a. Enter into the database OFFICE and display the name of all the tables.
b. Display the structure of the table ‘EMPL’.

25. Consider the following table PLAYER:


PNO PNAME SPORTS COUNTRY SALARY
C001 VIRAT CRICKET INDIA 112
F003 RONALDO FOOTBALL PORTUGAL 1134
T007 ROGER TENNIS SWITZERLA 795
ND
B002 SINDHU BADMINTON INDIA 59
a. Suggest the most suitable Primary Key. Justify your answer.
b. Identify the alternate Keys.

26. Consider the table MOTOR having the following attributes:


VNO, MODEL, BRAND, PRICE

Write SQL statement for the following:


a. Modify the existing column MODEL as varchar(30) and NOT NULL.
b. Increase PRICE by 20% for the BRAND ‘TATA’
27. Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP

28. A MySQL table, sales have 10 rows. The following queries were executed on
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10

SELECT COUNT(discount) FROM sales;


COUNT(discount)
6
Write a statement to explain as to why there is a difference in both the counts.

29. Explain Group by clause with a suitable example.

30. Distinguish between Natural Join and Equi Join.

Q. No. 31 to 40 – 3 marks question


31. Write output of the SQL queries based on the following table Employee:

(i) select name, project from employee order by project;


(ii) select name, salary from employee where doj like '2015%';
(iii) select min(doj), max(dob) from employee;

32. Write output of the SQL queries based on the following tables Projects and
Employee:

(i) select project, count(*) from employee group by project;


(ii) select pid, pname, eid, name from projects p, employee e where
[Link]=[Link];
(iii) select avg(salary) from employee where doj between '2018-08-01' and
'2018-08-31';
33. Write SQL statements to do the following:

i. Define CID in CUSTOMER table as Foreign Key that refers to CID i.e.
Primary Key of COMPANY table.

ii. Display the ‘CUSTOMER NAME’, ‘PRODUCT NAME’ who have purchased
any product from the ‘COMPANY NAME’ ‘SONY’.

iii. Increase the QTY by 15 for the products with PRICE below 40,000.

34. Consider the GAMES table and answer the following questions:

i. Identify the possible Candidate Keys in the above table.


ii. Suggest the most suitable column for Primary key of the above table. Give
reason behind your answer.
iii. Write down the Alternate Keys for the above table.

35. Consider a table STORE having attributes as following:


ItemNo –numeric
ItemName – character of size 20
Scode – numeric
Quantity – numeric

Abhay wants to do the following operations on the STORE table. Please help him
to do by writing appropriate SQL statements.
i. Insert the following record in the STORE table:
(2010, Notebook, 23, NULL)
ii. Add a new column price with data type as decimal.

iii. Remove STORE table from the database.

36. What do you mean b y CHECK constraint and DEFAULT constraint? Explain
with suitable example.
37. Consider the following tables and answer the questions below:
i. What will be the degree and cardinality of the resultant table after performing
Cartesian Product between PRODUCT and CLIENT?
ii. What will be the degree and cardinality of the resultant table after performing
NATURAL JOIN between PRODUCT and CLIENT?
iii. Are these values same? What can be the reason for this?
38. i. Write down the purpose of using aggregate functions in MySql.
ii. Give example of any two aggregate functions and their purposes.
iii. Can we use aggregate functions without GROUP BY clause? Justify.

39. i. What is the significance of NULL value in database?


ii. Name the operator that can check for NULL value in a column.
iii. Name the SQL command to permanently save the changes caused by DML
statements in the database.

40. i. Name the aggregate functions valid on a column of DATE data type.
ii. Suggest a keyword for renaming an attribute or a table in MySql.
iii. Write down the syntax of representing the common column CODE while
performing Equi Join between two tables GAME and USER.

Q. No. 41 to 45 – 5 marks question


41. i. Differentiate between ‘WHERE’ clause and ‘HAVING’ clause in MySQL with
appropriate example.

ii. Consider the following table and find the output of the following queries:

a. select SEX, avg(SALARY) from TEACHER group by SEX;

b. select SUBJECT, count(*) from TEACHER group by SUBJECT


having count(*)>1;

c. select SUBJECT, min(SALARY) from TEACHER


where TNAME not like ‘%Kumar’ group by SUBJECT;
42. i. Differentiate between DELETE and DROP in MySQL. Cite suitable examples.

ii. Consider the following tables – Bank_Account and Branch:

What will be the output of the following statement?


SELECT * FROM Bank_Account, Branch;
iii. Choose the correct option:
The above SQL query represents __________________ operation.
a. Outer join b. Natural join c. Equi join d. Cross join
43. Fill in the blanks with appropriate keywords in order to complete the following
SQL queries:
CAR
CID BRAND MODEL TYPE COLOUR PRICE
CO1 MARUTI SWIFT HATCHBACK WHITE 5,00,000
D32 HYUNDAI VERNA SEDAN BLACK 16,00,000
F32 TATA NEXON SUV RED 9,00,000
C29 KIA SELTOS SUV BLUE 17,00,000

i. Display all the databases present in MySQL of a system.


show ___________ ;

ii. Display the values in TYPE column of the table CAR after removing the
duplicate values from the output.
select ___________ TYPE from CAR;

iii. Display MODEL, PRICE, COLOUR from CAR whose COLOUR is neither
RED nor BLUE.
select MODEL, PRICE, COLOUR from CAR
where COLOUR _________ (‘RED’, ‘BLUE’);

iv. Display the total number of records present in CAR table.


select _________(CID) from CAR;

v. Display Discount on each CAR where Discount is 5% of the PRICE.


select MODEL, PRICE*0.05 _______ ‘DISCOUNT’ from CAR;

44. i. Write two advantages of using database.


ii. Distinguish between CHAR and VARCHAR data type. Which one is preferable
in general and why?
iii. Write down the significance of the data type NUMERIC(7,3).

45. i. What do you mean by Self Join. Give an example.


ii. Fill in the blanks with appropriate keywords for creating the table DRESS with
the following specifications:
 Default COLOR is ‘BLACK’.
 PRICE between 0 and 8000.
CREATE _____(a)_____ DRESS
(
DCODE INT PRIMARY KEY,
DNAME VARCHAR(15),
COLOR VARCHAR(10) ____(b)____ ‘BLACK’,
PRICE DECIMAL(6, 2) _____(c)____ PRICE BETWEEN 0 and 8000
);

Q. No. 46 to 50 – Case Study based questions of 4 marks each


46. Consider the following tables ITEM and CUSTOMER and find the outputs of the
following queries:

i) SELECT ITEM_NAME, MAX(PRICE), COUNT(*) FROM ITEM


GROUP BY ITEM_NAME;

ii) SELECT CNAME, MANUFACTURER FROM ITEM, CUSTOMER


WHERE [Link]=[Link];

iii) SELECT ITEM_NAME, PRICE*100 FROM ITEM WHERE


MANUFACTURER="ABC";

iv) SELECT DISTINCT CITY FROM CUSTOMER;


47. Consider the tables ITEM and CUSTOMER and write the queries:

(i) Display the total PERIODS for each SUBJECT from SCHOOL table.
(ii) Display TEACHERNAME, GENDER from the tables SCHOOL and ADMIN
whose DESIGNATION is ‘COORDINATOR’.

(iii) Display TEACHERNAME and DOJ in the descending order of CODE.

(iv) Display TEACHERNAME whose DOJ is in the year 2000.


48. Modern Public School is maintaining fees records of students. The
database administrator Aman decided that-
• Name of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno – numeric
Name – character of size 20
Class - character of size 20
Fee – Numeric
PayDate – Date
Primary Key – (Rollno, Class)
Answer the following questions:

(i) Write the DDL statement to create database School.


(ii) Write the SQL statement to create Fees table in School database with the
above-mentioned specifications.
(iii) Write SQL statement to display all the table names in School database.

49. Consider the table Fees mentioned in Q. No. 48 and answer the following
questions:

i. Insert the following record into the table


Rollno-1201, Name-Akshay, Class-12th, Fee-350, PayDate-24 JUNE 2019

ii. Increase the second quarter fee of class 12th students by 50.
iii. Delete the record of student with Rollno-1212
iv. Aman wants to display the schema (structure) of Fees table. Which command
will he use from the following:
a) CREATE b) ALTER c) SHOW d) DESCRIBE

50. Sagar, a cloth merchant creates a table CLIENT with a set of records to maintain
the client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the
table, he has entered data of 7 clients in the table.

Based on table CLIENT, write SQL statements for the following:

i. Write the statements to Update a record present in the table with data for
Qtr2 = 200, Qtr3 = 600 , total = sum of all Qtrs where the Client_ID is C660.
ii. Delete all records where total is between 500 to 900.
iii. Make changes in ClientName with data type varchar(20) and not null
constraint.
iv. Remove the column Total from the CLIENT table.
_________

SOLUTIONS
1. B 2. a 3. d 4. c 5. d
6. a 7. b 8. d 9. a 10. b
11. d 12. c 13. b 14. a 15. False
16. False 17. a 18. a 19. b 20. c
21. a) Degree - no. of attributes in a table, Cardinality – no. of records in a table.
b) Degree – 4, cardinality – 6
22. Foreign key of one table refers to the Primary key of another table.
23. CREATE TABLE REMEDIAL
(
SNAME VARCHAR(20) NOT NULL,
ROLL INT(5) UNIQUE,
FEES FLOAT(7,2),
ADMN INT(5) PRIMARY KEY
);
24. a. USE OFFICE;
b. DESC EMPL; or DESCRIBE EMPL;
25. a. PNO as unique throughout table and not null.
b. PNAME, SPORTS, SALARY.
26. a. ALTER TABLE MOTOR MODIFY MODEL VARCHAR(30) NOT NULL;
b. UPDATE MOTOR SET PRICE = PRICE * 1.20 WHERE BRAND = ‘TATA’;
27. DML - INSERT, UPDATE
DDL - ALTER, DROP
28. Count(*) will return the number of records in the table sales. Count(discount) will
return the number of records having not null values in the discount field of sales
table.
29. GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Groups are formed based on the number of different values in the
GROUP BY column present in the table.
30. In Natural Join the common attribute between two tables appears only once. Where
as in Equi Join the common attribute appears as it is i.e. twice. Hence these
common attributes are accessed as table_name.attribute in the query to resolve the
conflict.
31. i.
Name Project
Ranjan P01
Muneera P01
Alex P02
Akhtar P04
Satyansh P04
ii.
Name Salary
Ranjan 150000
Akhtar 125000
iii.
min(DOJ) max(DOB)
2015-01-21 1996-11-15
32. i.
Project count(*)
P01 2
P04 2
P02 1
ii.
PID PName EID
P01 Road 102 Carpenting E01
P04 Footover Bridge K-13 E02
P01 Road 102 Carpenting E03
P02 Civil Lines Parking E04
P04 Footover Bridge K-13 E05

iii.
avg(Salary)
135000

33. i. ALTER TABLE CUSTOMER


ADD FOREIGN KEY(CID) REFERENCES COMPANY(CID);

ii. SELECT [Link], [Link]


FROM COMPANY CO, CUSTOMER CU
WHERE [Link] = [Link] AND [Link] = ‘SONY’;

iii. UPDATE CUSTOMER SET QTY = QTY*1.15 where PRICE<40000;

34. i. Candidate keys - GCode, GameName, PrizeMoney, ScheduleDate


ii. Primary key - GCode as not null and unique for each game.
iii. Alternate key - GameName, PrizeMoney, ScheduleDate

35. i. INSERT INTO STORE VALUES (2010, ‘Notebook’, 23, NULL);


ii. ALTER TABLE STORE ADD PRICE DECIMAL(10,2);
iii. DROP TABLE STORE;

36. CHECK – Ensure that the attribute contains only permissible set of values.
DEFAULT – Ensure the default value is inserted if no value is mentioned.
e.g. -
CREATE TABLE STOCK
(
SNO INT PRIMARY KEY,
SNAME VARCHAR(20),
LOCATION VARCHAR(15) DEFAULT ‘BANGALORE’,
PRICE FLOAT(7,2) CHECK (PRICE BETWEEN 0.00 AND 10000.00)
)
37. i. After Cartesian product, Degree = 8, Cardinality = 25
ii. After natural join, Degree = 7, Cardinality = 5
iii. No, because cartesian product is the all-possible combination of tuples between
two tables. Where as Natural join selects only those tuples for whom the values of
the common attributes are same.

38. i. Aggregate functions perform calculation on a set of values, and returns a single
value. If used with GROUP BY clause, it returns one value for each group.
SUM() - returns the total sum of a numerical column
MAX() - returns the largest value within the selected column

ii. Yes. Then it returns a single value for the selected attribute by considering all the
records in that table.
39. i. NULL is said to be absence of any value in an attribute. NULL cannot participate
in any operation.
ii. IS
iii. COMMIT
40. i. MAX(), MIN(), COUNT()
ii. AS
iii. SELECT * FROM GAME G, USER U WHERE [Link]=U,CODE;

41. i. WHERE clause allows to filter data from individual rows of a table based on
certain conditions. In contrast, the HAVING clause allows to filter data from a
group of rows in a query based on conditions involving aggregate functions.
ii.
a)
SEX AVG(SALARY)
M 68666
F 65000

b)
SUBJECT COUNT(*)
Computer Science 2

c)
SUBJECT MIN(SALARY)
Computer Science 75000
English 55000
Economics 71000

42. i. DELETE is used for deleting records from a table. DROP is used to delete the
entire schema of any database object like table.
e.g. –
DELETE FROM STUDENT WHERE ROLL = 5;
DROP TABLE STUDENT;
ii.
E_CODE NAME E_CODE LOCATION
E01 ASHISH E05 MUMBAI
E02 SURESH E05 MUMBAI
iii. d. Cross join
43. i. databases
ii. distinct
iii. not in
iv. count
v. as
44. i. Data integrity, data security
ii. Char data type stores data of fixed length, whereas the Varchar data type stores
variable length data. Varchar is preferable as it is more flexible for data of any size.
iii. It can represent 7 digit real number with 3 digits in the right of decimal point.
45. i. A self-join is a regular join, but the table is joined with itself.
SELECT * FROM EMP A, EMP B where [Link] = [Link];
ii.
(a) TABLE
(b) DEFAULT
(c) CHECK
46. i.
ITEM_NAME MAX(PRICE) COUNT(*)
Personal Computer 37000 3
Laptop 57000 2

ii.
CNAME MANUFACTURER
N Roy PQR
R Singh XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC

iii.
ITEM_NAME PRICE*100
Personal Computer 3500000
Laptop 5500000

iv.
City
Delhi
Mumbai
Bangalore

47. (i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL


GROUP BY SUBJECT;

(ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE


DESIGNATION = ‘COORDINATOR’ AND [Link]=[Link];

(iii) SELECT TEACHERNAME, DOJ FROM SCHOOL ORDER BY CODE


DESC;

(iv) SELECT TEACHERNAME FROM SCHOOL WHERE DOJ LIKE ‘%2000’;


48. i. CREATE DATABASE SCHOOL;
ii. USE SCHOOL
create table Fees
(
Rollno numeric(5),
Name varchar(20),
Class varchar(20),
Fee Numeric(7,2),
PayDate Date,
Primary Key(Rollno, Class)
);
iii. SHOW TABLES
49. i. INSERT INTO FEES VALUES(1201, ‘Akshay’, ‘12th', 350, ‘2019-06-24’);
ii. UPDATE TABLE FEES SET FEE = FEE+50 WHERE CLASS=’12th’;
iii. DELETE FROM FEES WHERE ROLLNO =1212;
iv. d) DESCRIBE
50. i. UPDATE CLIENT SET Qtr2 = 200, Qtr3 = 600, Total = Qtr1+Qtr2+Qtr3
WHERE Client_ID = ‘C660’;
ii. DELETE FROM CLIENT WHERE Total between 500 AND 900;
iii. ALTER TABLE CLIENT MODIFY ClientName VARCHAR(20) NOT NULL;
iv. ALTER TABLE CLIENT MODIFY DROP Total;

Interface of Python with an SQL database

Connecting SQL with Python


A Python library - mysql connector is required which provides connectivity from Python to Mysql.
There are mainly six steps that must be followed in Python environment to create a database
connectivity application. Steps for Creating Database Connectivity Applications:-

1. Import the package required for database access.


2. Open a connection to database.
3. Create a cursor instance.
4. Execute a query.
5. Extract data from result set or make the changes permanent.
6. Clean up the environment.

To establish the connection, write codes in script mode:


1. Import the Library
import [Link]
2. connect() statement to create a connection to the Mysql server and returns a Mysql connection
object mydb and pass three parameters, if required then also pass database parameter.
mydb=[Link](host='localhost',user='root',passwd='password')
3. Creating cursor object of a class cursor which allows python code to execute sql commands.
mycursor=[Link]()
4. execute() statement with sql query to execute SQL query from python.
[Link](“sql query”)
5. To read the data from the table of database using fetchone()/ fetchmany()/ fetchall() methods
as per requirement and store in a resulset.
myresult = [Link]()

To save the current transactions of inserting, updating and deleting data we use:
[Link]()
6. close() to close the connection and clean up the environment
[Link]()

Code For Creating A Mysql Database Through Python


import [Link]
mydb = [Link](host="localhost", user="john", password="john")
mycursor = [Link]()
[Link]("CREATE DATABASE mydatabase")

Code For Creating A Table In Mysql Through Python


import [Link]
mydb = [Link](host="localhost",user="john",password="john",
database="mydatabase")
mycursor = [Link]()
[Link]("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")

Code For Inserting Data In A Mysql Table Through Python


import [Link]
mydb = [Link](host="localhost", user="john",password="john",
database="mydatabase")
mycursor = [Link]()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Mary", "ABC")
[Link](sql, val)
[Link]()

Code For Displaying Data From A Mysql Table Through Python


import [Link]
mydb = [Link](host="localhost",user="john", password="john",
database="mydatabase”)
mycursor = [Link]()
[Link]("SELECT * FROM customers")
myresult = [Link]()
for x in myresult:
print(x)

Code For Deleting A Record From Mysql Table Using Python


import [Link]
mydb =
mydb = [Link](host="localhost", user="john",password="john",
database="mydatabase")
mycursor = [Link]()
sql = "DELETE FROM customers WHERE name = 'XYZ'"
[Link](sql)
[Link]()

Code For Updating A Record From Mysql Table Using Python


import [Link]
mydb = [Link](host="localhost", user="john",password="john",
database="mydatabase")
mycursor = [Link]()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 123'"
[Link](sql)
[Link]()

[Link]: To count total number of records affected by the execute method.


print([Link])
Mind Map – Python MySql Connectivity

1 Mark Questions (MCQ)

1. To establish a connection with MySQL from Python which of the following functions is used?
(a) connection()
(b) connect()
(c) open()
(d) cursor()

2. execute() method can execute ________ .


(a) DDL statements
(b) DML statements
(c) DDL and DML statements.
(d) Select statement only

3. To establish a connection between Python and sql database, connect() is used. Which of the
following arguments may not necessarily be given while calling connect()?
(a) host
(b) database
(c) user
(d) password

4. What is the purpose of the `rowcount` attribute in Python-Mysql database connectivity?


(a) Number of rows affected by the last executed command
(b) Total number of rows in the database
(c) Total number of columns in the database
(d) Number of tables in the database
5. Which method is used to retrieve N number of records
(a) fetchone()
(b) fetchall()
(c) fetchmany()
(d) fetchN()

6. To make the changes made by any SQL Queries permanently in database, which function is used
after execution of the query?
(a) save()
(b) commit()
(c) execute()
(d) dump()

7. How is dynamic insertion of values achieved in SQL queries?


(a) Using execute()
(b) Using dynamicValues()
(c) Using ‘%s’ format specifier or format()
(d) Using insertValues()
8. _______ it is a pointer or iterator which points towards the resultset of the SQL query.
(a) cursor
(b) rset
(c) temp
(d) None of these

9. To get all the records from result set, you may use ___________.
(a) [Link]()
(b) [Link]()
(c) [Link]()
(d) [Link]()

10. Which of the following is not a valid method to fetch records from database in python.
(a) fetchmany()
(b) fetchone()
(c) fetchmulti()
(d) fetchall()

11. Which attribute of cursor is used to get number of records stored in cursor (Assumeg cursor
name is mycursor)?
(a) [Link]
(b) mycursor.row_count
(c) [Link]
(d) [Link]

12. Which of the following package must be imported in Python to create a database connectivity
application?
(a) [Link]
(b) [Link]
(c) [Link]
(d) [Link]

13. Which of the following method reflects the changes made in database permanently?
(a) <connection>.done()
(b) <connection>.final()
(c) <connection>.reflect()
(d) <connection>.commit()

14. Which method of cursor class is used to fetch limited rows from the table?
(a) [Link](SIZE)
(b) [Link](SIZE)
(c) [Link](SIZE)
(d) [Link](SIZE)

15. Which method of cursor class is used to get the number of rows affected after any of
the Insert/update/delete database operation executed from Python?
(a) [Link]
(b) [Link]
(c) [Link]
(d) [Link]

16. Which of the following component acts as a container to hold the data returned from the query:
(a) table
(b) cursor
(c) resultset
(d) container

17. To get the next record from the result set, we may use .
(a) [Link](next)
(b) [Link]()
(c) [Link]()
(d) [Link]()

18. SQL command is passed to which function to run after establishment of the connection
between python and database
(a) cursor()
(b) execute()
(c) connection()
(d) fetchall()

19. Which of the following function is used to close the connection between python and database?
(a) [Link]()
(b) [Link]()
(c) [Link]()
(d) [Link]()

20. Which is the correct statement about fetchone()


(a) Fetch the next row of a query result set, returning a single tuple, or None when no more data is
available
(b) Fetch the First row of a query result set, returning a single tuple, or None when no more data is
available
(c) Fetch the current row of a query result set, returning a single tuple, or None when no more data
is available
(d) None of the above
Ans:
1 (b)
2 (c)
3 (b)
4 (a)
5 (c)
6 (b)
7 (c)
8 (a)
9 (b)
10 (c)
11 (d)
12 (a)
13 (d)
14 (b)
15 (a)
16 (c)
17 (d)
18 (b)
19 (c)
20 (a)

2 Marks Questions
1. Which method we use to establish the connection and clear the connection?
Ans: connect() and close() methods with connection object.

2. Which statement we use to access the MySQL module?


Ans: import [Link]

3. What are the difference between fetchone() and fetchmany()?


Ans: fetchone(): It will return one record from the result set.
fetchmany(n): It will return number of records as per value of n and by-default only one record.

4. How can you use Python with MySQL?


Ans: Python can be used with MySQL in a number of ways. One way is to use the [Link]
python library, which is a MySQL driver written in Python. This library can be used to connect to a
MySQL database and perform various operations, such as creating and executing SQL queries.

5. What is a cursor in the context of MySQL?


Ans: A cursor is a pointer that points to a specific location in a database table. In MySQL,
cursors are used to iterate through the rows of a table and retrieve data from them.

6. What’s the difference between autocommit and commit?


Ans: Autocommit is a database feature that automatically commits changes to the database as soon
as they are made. This means that changes are immediately visible to other users and there is no
need to explicitly call the commit() method. Commit, on the other hand, is a database feature that
allows changes to be made to the database and then explicitly committed by the user. This allows
the user to control when changes are made visible to other users.

7. How can you check if a table exists in MySQL?


Ans: You can check if a table exists in MySQL by using the SHOW TABLES command. This will
show you a list of all the tables in the database. If the table you are looking for is not in the list,
then it does not exist.

8. How do you disconnect from the database?


Ans: Use the close() method. [Link]() closes the connection from the database, where db is
connection object.

9. What is database connectivity?


Ans: Database connectivity refers to connection and communication between an application and a
database system.

10. What is connection? What is its role?


Ans:A Connection (represented through a connection object) is the session between the application
program and the database. To do anything with database, one must have a connection object.

3 Marks Questions
1. What is a result set? Give example with coding.
Ans: A result set refers to a logical set of records that are fetched from the database by executing a
query and made available to the application-program.
Eg: myresult = [Link]()

2. Which package must be imported in Python to create a database connectivity application? Give
example with coding.
Ans:There are multiple packages available through which database connectivity applications
can be created in Python. One such package is [Link], mysqlclient, etc. can
also be used for connectivity.
Eg: import [Link]

3. Explain the following result retrieval methods:-


(a) fetchone()
(b) rowcount
(c) fetchall ()
Ans: (a) fetchone() :- The fetchone() method will return only one row from the result set in the
form of tuple containing a record.
(b) rowcount() :- [Link] that always return how many records have been retrieved
so for using any of the fetch..() methods.
(c) fetchall() :- The fetchall() method return all the rows from the result set in the form of a
tuple congaing the records.

4. Write the python script to read the whole data from the table emp and display all the records.
Ans: import [Link]
mydb=[Link](host="localhost",user="root",passwd="root",database="school")
print (mydb)
mycursor=[Link]()
numrow=[Link]("select * from student")
print([Link]())
[Link]()

5. Write the main difference among fetchone(),fetchmany() and fetchall().


Ans: fetchone() fetches a single record or row from the resultset.
fetchmany () method returns blocks of results according to a set limit. It will fetch n records at a
time from the table.
fetchall() fetches all the records or rows at a time from the table.

4 Marks : Case Based Questions

1. The code given below inserts following record in to a table EMPLOYEE


EMPNO – Integer
ENAME – string
SALARY - Integer
BONUS - Integer
DEPTID – string

Help your friend Sonia in writing the following missing statements to complete the code:-

import ______________ # Statement1


mydb=[Link](host="localhost",user="root",passwd='root',database="class12")
mycursor= _____________ # Statement 2
[Link]("INSERT INTO EMPLOYEE VALUES(114,'BP Singh',56400,800,'D01')")
___________________ # Statement 3
print([Link], "Record inserted")
___________________ # Statement 4

Ans:
Statement 1: [Link]
Statement 2: [Link]()
Statement 3: [Link]()
Statement 4: [Link]()

2. Avni is trying to connect Python with MySQL for her project. Help her to write the python
statement on the following:
i. Name the library, which should be imported to connect MySQL with Python.
ii. Name the function, used to run SQL query in Python.
iii. Name the function required to make the changes permanent.
iv. Name the fuction to clear the environment.

Ans:
i. [Link]
ii. execute()
iii. commit()
iv. close()

3. Your friend Jagdish is writing a code to fetch data from a database Shop and table name Products
using Python. He has written incomplete code. You have to help him to write complete code:
import __________ as m # Statement-1
object1 = [Link](host="localhost", user="root", password="root", database="Shop")
object2 = object1._________ # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2._________(query) # Statement-3
__________.close() # Statement-4

Ans:
Statement 1: [Link]
Statement 2: cursor()
Statement 3: execute()
Statement 4: object1

4. The code given below reads the following record from Table named Employee and display those
record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank.

Write the following missing statements to complete the code on behalf of your friend Sandeep:
Statement 1 – to form the cursor object
Statement 2 – to query string.
Statement 3 - to execute the query that extracts records of those Employees whose salary >=30000
and <=90000.
Statement 4 - to close the connection.
import [Link]
mydb=[Link](host='localhost',user='root',passwd='Password',database='bank')
mycursor=_________________ # statement1
mycursor.________________ #statement 2
data= __________________ # statement 3
for x in data:
print(x)
______________ # statement 4

Ans:
Statement 1: [Link]()
Statement 2: execute('''SELECT * FROM Employee WHERE salary >= 30000 and salary <=
90000;''')
Statement 3: [Link]()
Statement 4: [Link]()

5. The code given below inserts the following record in the table Emp:

Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be accepted
from the user.
Help your friend in writing the following missing statements to complete the code:
Statement 1 – to create a connection
Statement 2 – to form the cursor object
Statement 3 – to execute the command that inserts the record in the table Emp.
Statement 4 - to add the record permanently in the database
import [Link] as mysql
def sql_data():
mycursor=_________________ #Statement 1
eno=int(input("Enter Employee Number: "))
Ename=input("Enter Employee Name: ")
Designation=input("Enter Designation: "))
Salary=int(input("Enter Salary: "))
Bonus=int(input("Enter Bonus: "))
querry="insert into emp values({},'{}',{},{})".format(eno,ename,designation,bonus)
______________________ #Statement 2
______________________ # Statement 3
print("Employee Data Added successfully")

Ans:
Statement 1: con1= [Link](host="localhost",user="root", password="tiger",
database="Employee")
Statement 2: [Link]()
Statement 3: [Link](querry)
Statement 4: [Link]()

5 Marks Questions

1. Write the steps to perform an Insert query in database connectivity application. Table Student
values are rollno, name, age (10,’Ashok’,26).

Ans: import [Link] as mydb


conn= [Link](host=”localhost”, user=”root”, passwd=”1234”, database="school")
cur=[Link]()
[Link](“INSERT INTO student values(10,’Ashok’,26);”)
[Link]()

2. Observe the following python code and answer the questions:


import [Link] as ___________#Statement 1
con = [Link](host="localhost", user="root", passwd="", database="test")
mycursor= ___________#Statement 2
[Link](" CREATE TABLE studentinfo (name VARCHAR (30), age INT(3)")
sql = """INSERT INTO studentinfo( name, age) VALUES ('Ashok',17) """
_____________________ #Statement 3
_____________________ #Statement 4
_____________________ #Statement 5

i) Write the python statement to give appropriate alias name in statement1.


ii) Write the python statement to establish the database cursor as statement2.
iii) Write the python statement to insert the row into the table as statement 3 by using the string
‘sql’ given above.
iv) Write the python statement to make the changes permanent.
v) Write the python statement to clear the environment.

Ans:
Statement 1: c
Statement 2: [Link]()
Statement 3: [Link](sql)
Statement 3: [Link]()
Statement 3: [Link]()
3. Write the python function to accept the name as parameter and find out whether record present
in the table or not. Table Student columns are rollno, name, age.

Ans: import [Link]


def check_name(name):
mydb=[Link](host="localhost",user="root",passwd="root",
database="school")
cur=[Link]()
[Link]("select * from student")
s=[Link]()
for k in s:
if((k[1]==name)):
print("Record Found",k)
break

4. Observe the codes given below and fill in the blanks:-


_________________________________# statement 1
mydb = [Link]( host="localhost", user="yourusername", password="yourpassword",
database="mydatabase" )
mycursor = [Link]()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway No. 21")
[Link](sql, val)
_________________ # statement 2
mycursor.___________("SELECT * FROM customers") # statement 3
myresult = _________________________________# statement 4
for x in myresult:
print(x)
________.close() #statement 5

Ans:
Statement 1: import [Link] as mycon
Statement 2: [Link]()
Statement 3: execute
Statement 4: [Link]()
Statement 5: mydb

5. The Code given below is deleting a record from table EMPLOYEE.


Fill in the blanks to complete the code
import [Link]
mydb=_________(host="localhost",user="root",passwd='root',database="class12") #statement 1
mycursor=_____________ #statement 2
__________________("DELETE FROM EMPLOYEE WHERE EMPNO=114") # statement 3
_______________ # statement 4
_______________ # statement 5
Ans:
Statement 1: [Link]
Statement 2 [Link]()
Statement 3: [Link]
Statement 4: [Link]()
Statement 5: [Link]()

You might also like