Sei sulla pagina 1di 97

LUKNOW PUBLIC SCHOOL

SESSION-2019-20

STUDY MATERIAL

FRAGMENT 1

SUBJECT: INFORMATICS PRACTICES

CLASS-XII
 CHAPTERS INCLUDED:

Chapter 1: COMMUNICATION AND NETWORK CONCEPTS

CHAPTER 2: OPENSOURCE CONCEPTS

CHAPTER 13: MYSQL REVISION TOUR

CHAPTER 14: DATABASE TRANSACTION

CHAPTER 15: MORE ON SQL-GROUPING RECORDS AND TABLE JOIN

CHAPTER 16: TABLE AND INTEGRITY CONSTRAINTS

TEACHERS’ CONTRIBUTORS:

 GAJENDRA SINGH DHAMI, PGT (CS), SOUTH-CITY BRANCH


 AMIT PATHAK,PGT (IP),RAE-BARELI BRANCH
 MD. GHAYAS,PGT (IP),GOMTI NAGAR BRANCH
 ANSHUMAN KHARE,PGT(IP),JANKIPURAM BRANCH
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY

Chapter 1: COMMUNICATION AND OPENSOURCE CONCEPTS

A computer network is a collection of interconnected computers and other devices which are able to
communicate with each other and share hardware and software resources.
Advantages of network:
 Resource Sharing: hardware and software resources can be shared.
 Cost saving: sharing of resources reduces cost.
 Collaborative user interaction: services like video conferencing can be used collaborative interaction.
 Time saving: as distance barrier is removed sending of data is quick and fast, it saves time.
 Increased storage: interconnected computers provide larger storage capacity.

NETWORKING HARDWARE AND COMMUNICATION MEDIA


Transmission Media: A transmission medium is a medium of data transfer over a network. It can be wired or
wireless.

Wired Media:
A number of various types of cables are used to transfer data over computer networks.
These are Twisted Pair Cable, Co-axial Cable, and Optical Fiber Cable.

Twisted Pair Cable –


It contains four twisted pairs covered in an outer shield. These pairs are colour coded. An RJ-45 connecter is
used to connect this cable to a computer. It is of two types:

UTP (Unshielded Twisted Pair): As the name suggests in UTP cables individual pairs are not shielded.
Characteristics of UTP cable:
 It is a low-cost cable available for setting up small networks.
 It is a thin (External diameter app. 0.43cm) and flexible cable and therefore it offers ease of
installation.
 It can carry data upto a length of 100m at a stretch.

STP (Shielded Twisted pair): It is the same cable as the UTP, but with each pair shielded individually. An
outer shield then covers all the pairs like in UTP.
Characteristics of STP cable:
 As compared to UTP, STP offers better immunity against internal and external electromagnetic
interferences.
 It is expensive than UTP cable.
 As compared to UTP cable, STP cable is difficult to install.
COMMUNICATION AND NETWORK CONCEPTS 1
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY

Co-axial cable (or coax) –A coaxial cable consists of two conductors that share a common axis. The inner
conductor is a straight wire and the outer conductor is a shield that might be braided or a foil.
Characteristics of Co-axial cable:
 It can carry data for a larger distance (185m - 500m) at a stretch.
 Less susceptible to electromagnetic fields
 Bulkier and less flexible than twisted pair.
 Due to its thickness (1cm diameter) and less flexibility, it is difficult to
install as compared to twisted pair cable.

Optical Fiber cable -


Optical Fibers are long, thin strands of glass about the thickness of a human hair. They are arranged in
bundles called optical fiber cables and used to transmit data through light signals over long distances.
An optical fiber has following parts:
Core - It is the thin glass rod at the center through which the light
travels
Cladding - It is the outer optical material surrounding the core that
reflects the light back into the core
Buffer coating - It is the plastic coating that protects the cable from
damage and moisture

Characteristics of Optical Fiber Cable:


 It can carry data for a very large distance at a stretch.
 Not susceptible to electromagnetic fields
 Specially skilled people are required to install optical fiber cables.
 Till date it is the most expensive and at the same time the most efficient cable available for computer
networks.

Wireless Media
Electromagnetic waves are used for wireless communication over computer networks.
Frequencies of waves are measured in Hertz (Hz).
Based on their frequencies, electromagnetic waves are categorized into various categories. These categories
are (in increasing order of frequencies): radio waves, microwaves, infrared radiation, visible light, ultraviolet
radiation, X-rays, and Gamma rays.
Out of these only radio waves, microwaves, and infrared rays are used for wireless communication.
Radio Waves -
Radio waves have a frequency range of 3 KHz to 3GHz. Radio waves are used for communication over
distances ranging from a few meters (in walkie-talkies) upto covering an entire city. These waves are easy to
generate, can travel long
COMMUNICATION AND NETWORK CONCEPTS 2
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
distances and can penetrate buildings easily. That's why they are widely used for communication, both
indoors and outdoors.
Cordless phones, AM and FM radio broadcast, Garage door openers etc. are examples of radio wave
transmission.
Characteristics of Radio Wave Transmission:
 These waves are omni-directional, so the transmitting and receiving antennas need not be aligned.
 Relatively inexpensive than wired media.
 It offers ease of communication over difficult terrain
 The transmission can be interfered by motors or other electrical equipment
 Permission from concerned authorities is required for use of radio wave transmission
 Less secure mode of transmission
Micro Waves –
Micro waves have a frequency range of 300MHz (0.3 GHz) to 300 GHz. Microwaves travel in straight lines
and cannot penetrate any solid object. Therefore for long distance microwave communication, high towers
are built and microwave antennas are put on their tops.
Characteristics of Micro Wave Transmission:
 Free from land acquisition rights
 Relatively inexpensive than wired media
 Offers ease of communication over difficult terrain
 The transmission is in straight lines so the transmitting and receiving antennas need to be properly
aligned ( line of sight transmission)
Infrared Waves;
Infrared waves have a frequency range of 300 GHz to 400 THz. Infrared waves are so called because they
have a frequency range of just less than that of red light. These waves are used for short range
communication (approx. 5m) in a variety of wireless communications, monitoring, and control applications.
Home-entertainment remote-control devices, Cordless mouse, and Intrusion detectors are some of the
devices that utilize infrared communication.
Characteristics of Infrared Wave Transmission:
 It is a line of sight transmission; therefore information passed to one device is not leaked to another
device.
 No government license is required for their use
 It is a line of sight transmission, therefore at a time only two devices can communicate.
 The waves do not cross any solid object in between Performance drops with longer distances

Bluetooth -Bluetooth technology uses radio waves in the frequency range of 2.402 GHz to 2.480 GHz. This
technology is used for short range communication (approx. 10m) in a variety of devices for wireless
communication. Baby monitors, door openers, and cell phones are some of the devices that utilize Bluetooth
communication.
Characteristics of Bluetooth Transmission:
 Line of sight between communicating devices is not required.
 Bluetooth can connect upto eight devices simultaneously.
 Slow data transfer rate (upto 1Mbps).

Satellite Link –
Satellite links are used for very long distance wireless communication which may range from intercity to
intercontinental. Transmission from the earth to a satellite is known as uplink. Transmission from a satellite
to the earth is known as downlink.

COMMUNICATION AND NETWORK CONCEPTS 3


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
Characteristics of Transmission using satellite link:
 Satellites cover large area of earth
 Since communication over very long distances is possible, this becomes a commercially attractive
option.
 This system is expensive
 Requires legal permissions.

NETWORK DEVICES:
Other than the transmission media many other devices are required to form computer networks. Some of
these devices are:
NIC(Network Interface Card / Unit) :An NIC (Network Interface Card) is a device that enables a computer to
connect to a network and communicate.
Any computer which has to be a part of a computer network must have an NIC.

Hub: A Hub is an electronic device that connects several nodes to form a network and redirects the received
information to all the connected nodes in broadcast mode.
Hub is a device that allows us to connect multiple computers/devices together in a network. A hub has ports
into which the cables from individual computers' NICs are inserted.

 Active Hub :- These are the hubs which have their own power supply and can clean , boost and relay
the signal along the network. It serves both as a repeater as well as wiring center. These are used to
extend maximum distance between nodes.
 Passive Hub :- These are the hubs which collect wiring from nodes and power supply from active hub.
These hubs relay signals onto the network without cleaning and boosting them and can’t be used to
extend distance between nodes.

Switch:
A Switch is an intelligent device that connects several nodes to form a network and redirects the received
information only to the intended node(s).
A switch is an intelligent hub.

Repeater:
A Repeater is a device that is used to regenerate a signal which is on its way through a communication
channel. A repeater regenerates the received signal and re-transmits it to its destination.

Bridge:
A bridge is a repeater, with add on functionality of filtering content by reading the MAC addresses of source
and destination. It is also used for interconnecting two LANs working on the same protocol.

Gateway: A Gateway is a device, which is used to connect different types of networks and perform the
necessary translation so that the connected networks can communicate properly.
COMMUNICATION AND NETWORK CONCEPTS 4
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY

Router: it is a networking device that forwards data packets between computer networks. Routers perform
the traffic directing functions on the Internet

Modem (Modulator - Demodulator): A modem is a peripheral device that enables a computer to transmit
data over, telephone or cable lines.
It modulates an analogue carrier signal to encode digital information, and also demodulates such a carrier
signal to decode the transmitted information. This is why modem is an acronym of MOdulator/DEModulator.

Types of computing devices on a network:


Node:
A Node is a device, which is directly connected to a computer network. It can be a computer or any other
device like printer, scanner etc.
Workstation: A workstation is a special computer designed for technical or scientific applications. Intended
primarily to be used by one person at a time, they are commonly connected to a local area network and run
multi-user operating systems.
Server:A computer that facilitates sharing of data, software and hardware resources on the network is
known as the server. A network can have more than one server also. Each server has a unique name by
which it is identified by all the nodes on the network. Servers can be of two types:
a) Dedicated and
b) Non dedicated servers
Dedicated Servers: These are generally used on big network installations where one computer is reserved
for server's job. It helps all nodes access data, software and hardware resources. Since it does not
double up as a workstation but only manages the network, so it is known as a dedicated server and
such type of networks are called master- slave networks.
Non dedicated servers: In small networks, a workstation can double up as a server. These servers are
known as non dedicated servers. The small networks using such a server are known as Peer to Peer
networks.

NETWORK TOPOLOGIES:
A Topology is an arrangement of physical connections among nodes in a network.
Bus Topology:
Characteristics of Bus topology:
 It is easy to install.
 It requires less cable length and hence it is cost effective.
 Failure of a node does not affect the network.
 In case of cable (backbone) or terminator fault, the entire network breaks down. (disadvantage)
 Fault diagnosis is difficult. (disadvantage)

COMMUNICATION AND NETWORK CONCEPTS 5


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
 At a time only one node can transmit data.

Star Topology: In star topology each node is directly connected to a hub/switch. If any node has to send
some information to any other node, it sends the signal to the hub/switch.

Characteristics of Star topology:


 It is more efficient topology as compared to bus topology.
 It is easy to install.
 It is easy to diagnose the fault in Star topology.
 It is easy to expand depending on the specifications of central hub/switch
 Failure of hub/switch leads to failure of entire network.(disadvantage)
 It requires more cable length as compared to bus topology.(disadvantage)
Ring topology:
 Nodes are connected in a circular ring.
 Data transfer is done in one direction.
 If any node is damaged entire network is affected. (disadvantage)

Tree Topology: Tree topology is a combination of bus and star topologies. It is used to combine multiple star
topology networks. All the stars are connected together like a bus.
Characteristics of Tree topology:
 It offers easy way of network expansion
 Even if one network (star) fails, the other networks remain connected and working.

NETWORK PROTOCOLS
A network protocol is a set of rules for communication among networked devices.
Protocols generally includes rules of how and when a device can send or receive the data, how is the sent
data packaged, and how it reaches its destination.

COMMUNICATION AND NETWORK CONCEPTS 6


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
There are a number of protocols defined for computer networks
HTTP, TCP/IP, PPP,FTP
HTTP (Hyper Text Transfer Protocol):
 HTTP is used to transfer all files and other data (collectively called resources) from one computer to
another on the world wide web.
 When an HTTP client (a browser) sends a request to an HTTP server (web server) , the server sends
responses back to the client. This transfer of requests and responses is done following HTTP protocol.

TCP/IP (Transmission Control Protocol / Internet Protocol): Communication between two computers on
internet is done using TCP/IP protocol. TCP/IP can also be used as a communications protocol in a private
network.
 Job of dividing the original message into packets and re-assembling the received packets into the
original message is done by TCP protocol.
 Internet protocol(IP) is used to address and routing of packets to right destination.
Different packets from the same message may be routed differently, but they reach the same destination
and are reassembled there.
PPP (Point to Point Protocol):
 It is a protocol for direct communication between two computers, typically a personal computer
connected by phone line to a server.
 Most Internet service providers (ISPs) use PPP for customer dial-up access to the Internet. PPP is used
over many types of physical networks including cellular telephone, serial cable, phone line, trunk line,
specialized radio links, and fiber optic links.
UDP: User datagram protocol is used to send data like IP.

Some more application protocols:


SMTP: Simple mail transfer protocol) is used to send e-mail.
POP (post office protocol) is used to access or receive e-mail from servers.
FTP: File transfer protocol is used to upload and download files
Types of Networks:
On the basis of area covered computer networks are classified as:
 PAN - Personal Area Network
 LAN - Local Area Network
 MAN - Metropolitan Area Network
 WAN -Wide Area Network
PAN (Personal Area Network):
 A PAN is a network of Communicating devices (Computer, Phone, MP3/MP4 Player, Camera etc.) in
the proximity of an individual.
 It can cover an area of a few meters radius.
 When files are transferred from a PC to an MP3 player, a PAN is set up between the two. There can
also be multiple devices in PAN. A PAN can be set up using guided media (USB cable) or unguided
media (Bluetooth, Infrared).
LAN (Local Area Network):
 A LAN is a network of computing/Communicating devices in a room, building, or campus. It can cover
an area of a few meters to a few kilometers radius.
 In addition to operating in a limited space, a LAN is owned, controlled, and managed by a single
person or organization.
 A LAN can be set up using wired media (UTP cables, Co-axial cables etc.) or wireless media (Infrared,
radio waves).
 If a LAN is setup using unguided media, it is known as WLAN (wireless LAN).
MAN (Metropolitan Area Network):
COMMUNICATION AND NETWORK CONCEPTS 7
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
 A MAN is a network of computing/communicating devices within a city. It can cover an area of a few
kilometers to a few hundred kilometers radius.
 A network of schools, or banks, or Government offices etc., within a city, are examples of MANs. A
MAN is usually formed by interconnecting a number of LANs and individual computers. All types of
communication media (guided and unguided) are used to set up a MAN.
 A MAN is typically owned and operated by a single entity such as a government body or a large
corporation. A good example of a MAN is the interconnected offices of a state government.
WAN (Wide Area Network):
 A WAN is a network of computing/communicating devices crossing the limits of a city, country, or
continent. It can cover an area of over hundreds of kilometer radius.
 A network of ATMs, BANKs, National Government Offices, International Organizations' Offices etc.,
spread over a country, continent, or covering many continents are examples of WANs.
 The best known example of a WAN is the internet.

IDENTIFICATION OF COMPUTERS AND USERS OVER A NETWORK:

MAC (Media Access Control) address:


 A MAC (Media Access Control) address is a unique 12 digit (6 digits for manufacturer code and 6
digits for serial number) hexadecimal number assigned to each NIC.
 MAC address of an NIC never changes.
 MAC addresses are 12-digit hexadecimal (or 48 bit) numbers. By convention, MAC addresses are
usually written in one of the following two formats:
MM:MM:MM:SS:SS:SS or MM-MM-MM-SS-SS-SS
For example, in the following MAC address: 00:A0:C9 : 14:C8:35

IP Address:
 An IP (Internet Protocol) address is a unique 4 digit hexadecimal number assigned to each node on a
network. IP address settings of a node can be changed by the user.
 Every machine in a network has another unique identifying number, called its IP Address.
 An IP (IPv4)address is a group of four bytes (or 32 bits) each of which can be a number from 0 to 255.
A typical IP address looks like this: 59.177.134.72
 There are two versions of IP addresses: version 4 (IPv4) and version 6 (IPv6). IPv6 32 uses 128 bits
(IPv4 uses 32 bits) for an IP address.
IP Address Vs MAC Address:
 The IP address is assigned by the network administrator or the internet service provider while the
MAC address is assigned by the manufacturer.
COMMUNICATION AND NETWORK CONCEPTS 8
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
 If a computer is transferred from one network to another, its IP address gets changed whereas the
MAC address remains the same.
From the IP address it is usually possible to track the tentative location of the computer but this is not the
case with a MAC address.
URL:
 Uniform Resource Locator is the character based name of file or location on internet.URL has three
parts.
Format of URL: server type//domain name/file path
 Example: http://www.cbse.nic.in/welcome.htm
Domain Name: Domain names are character based names used in URLs to identify particular Web servers.
 A Domain Name is a name assigned to a server through Domain Name System (DNS). For example, in
the URL http://www.cbse.nic.in/welcome.htm, the domain name is www.cbse.nic.in.
 A domain name usually has more than one parts: top level domain name or primary domain name
and sub-domain name(s). For example, in the domain name , in is the primary domain name; nic is
the sub-domain of in; cbse is the sub-domain of nic.
 There are only a limited number of top level domains, and these are divided into two categories:
Generic Domain Names and Country-Specific Domain Names. For example:

COMMUNICATION AND NETWORK CONCEPTS 9


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
Generic or logical Domain Names:
·com - commercial business Country Specific Domain Names:
·edu - Educational institutions .in - India
·gov - Government agencies ·au - Australia
·mil - Military ·ca - Canada
·net - Network organizations .ch - China
·org - Organizations (nonprofit) .nz - New Zealand
.pk - Pakistan
Domain Name Resolution is the process of getting corresponding IP address from a domain name

NETWORK SECURITY:
The term Network Security refers to all activities undertaken to protect a computer network from attacks to its
security. This covers protection of computers in the premises and data on the network from both internal and
external attacks.

Threats to network security:


Denial of service attacks:
A Denial of Service (DoS) attack is an attempt to make one or more network resources unavailable to
their legitimate users. Examples of such attacks are:

Denial of Access to Information:


Corrupting, Encrypting, or changing the status of information so that it is not accessible to its legitimate
user.
Denial of Access to Application:
Forced shutting of an application as soon as the user opens it.
Denial of Access to Resources:
Blocking a resource, may be a printer or scanner or USB port, of a computer from proper working.
Denial of Access to a Website:
Continuously sending bulk requests to a website so that it is not available to any other user.

Intrusion Problems: An Intrusion problem is an attempt to mischievously steal some information from
someone's computer. Examples of Intrusion are:

Snooping :Snooping refers to gaining unauthorized access to another person's or /organization's data.
 By getting someone's login information by casually watching what he/she is typing.
 Reading the files on someone's computer in an unauthorized manner
 Using some softwares which keeps track of the activities and data being sent or received on
someone's computer.

Eavesdropping -Eavesdropping refers to unauthorized access to another person's or organization's data


while the data is on its way on the network.
This may be done in a number of ways:
 By setting up parallel telephone lines.
 By installing some software (spyware) in the target computer.
 By installing some receiver which captures the data while on its way.

COMMUNICATION AND NETWORK CONCEPTS 10


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY

Malwares: Malicious programs that causes harm to computer and its resources in some form.
 Viruses: Viruses are malicious programs which replicate and attach to other programs in order to corrupt
the executable codes. Virus enters the computer system through an external source and become
destructive.
 Worms: Worms are also self- replicating programs that not only create multiple copies of itself on one
computer but propagate through the computer network. Worms log on to computer systems using the
username and passwords and exploit the system.
 Trojan horse: - Though it is a useful program, however, a cracker can use it to intrude the computer
system in order to exploit the resources. Such a program can also enter into the computer through an
email or free programs downloaded through the Internet.
 Spams: Unwanted e-mail (usually of a commercial nature sent out in bulk)
 Cookie: When the user browses a website, the web server sends a text file to the web browser.This small
text file is a cookie.
 Hacking: Hacking is an unauthorized access to computer in order to exploit the resources.
 Cracking: Cracking can be defined as a method by which a person who gains unauthorized access to a
computer with the intention of causing damage.

Cyber Law: Cyber law refers to all the legal and regulatory aspects of Internet and the World Wide Web.
"INFORMATION TECHNOLOGY ACT, 2000" [ITA2000] was enacted by Parliament of India to protect the field
of e-commerce, e-governance, e-banking as well as penalties and punishments in the field of Cyber
Crimes. The above Act was further amended in the form of IT Amendment Act, 2008 [ITAA-2008]
Some of the CYBER OFFENCES UNDER THE IT ACT:
 Tampering with computer source documents - Section 65
 Hacking -Section 66
 Publishing of information which is obscene in electronic form -Section 67

Cyber Crimes:
Cybercrime is defined as a crime in which a computer and internet is used in an illegitimate way to harm
the user. Cyber criminals may use computer technology to access personal information, business trade
secrets, or use the internet for exploitive or malicious purposes.
 Cybercrimes can be against persons or against property or against the government.
 The list of Cyber Crimes includes
 harassment by computer (Cyber Stalking, defamation)
 pornography illegal downloads,
 plagiarism software piracy/counterfeiting,
 copyright violation of software, counterfeit hardware,
 black market sales of hardware and software,
 theft of equipment and new technologies fraud (credit card fraud, fraudulent use of ATM accounts, stock
market transfers, telecommunications fraud), theft of (electronic) money

COMMUNICATION AND NETWORK CONCEPTS 11


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
PROTECT A NETWORK FROM ATTACKS:
A number of steps are taken to protect network from various threats. These steps include:
Login-Password: By assigning login names and strong passwords to the users of a system, it can be ensured that
only authorized people access a computer.

Firewall: A firewall is a hardware device or software that is installed to monitor the data entering the
computer/Network or leaving it. A firewall permits only that data to enter or leave a computer/Network for
which permissions have been granted by the computer/network administrator.
Anti-Virus Software: These days anti-virus software’s work against not only the virus but also against almost all
kinds of malware. Therefore by installing a full version legal (not the pirated one or freeware) anti-virus software
network security can be increased.
File Permissions: A data file on a computer can be created, read, or modified. An application file can be run or
executed. Accordingly, different rights (privileges) can be given to different users of a computer to perform one
or more of these tasks.
Biometric tools: thumb impression,retina scan,etc. for authentication

Encryption: encoding data or message in non-readable form so that it cannot be accessed by unauthorized
users.

Decryption :decoding the encrypted code to its original form so that it can be accessed by authorized user only.

Digital certificate: it is secure code provided to authenticate any document on internet for its authenticity.

WIRELESS/MOBILE COMPUTING
Wireless communication is simply data communication without the use of landlines. Mobile computing
means that the computing device is not continuously connected to the base or central network.
1. GSM(Global System for Mobile communication): it is leading digital cellular system. In covered areas, cell
phone users can buy one phone that will work any where the standard is supported. It uses narrowband
TDMA, which allows eight simultaneous calls on the same radio frequency.
2. CDMA(Code Division Multiple Access): it is a digital cellular technology that uses spreadspectrum
techniques. CDMA does not assign a specific frequency to each user. Instead ,every channel uses the full
available spectrum.
3. WLL(Wireless in Local Loop) : WLL is a system that connects subscribers to the public switched telephone
network using radio signals as a substitute for other connecting media.
4. Email(Electronic Mail): Email is sending and receiving messages by computer.
5. Chat: Online textual talk in real time , is called Chatting.
6. Video Conferencing: a two way videophone conversation among multiple participants is called video
conferencing.
7. SMS(Short Message Service): SMS is the transmission of short text messages to and from a mobile pone, fax
machine and or IP address.
8. 3G and EDGE: 3G is a specification for the third generation of mobile communication of mobile
communication technology. 3G promises increased bandwidth, up to 384 Kbps when a device is stationary.
EDGE(Enhanced Data rates for Global Evolution ) is a radio based high speed mobile data standard.
9.4G networks will be based on packet switching only. It will be able to support faster transmission. They are
projected to provide speeds up to 100 Mbps while moving and 1Gbps while stationary. It is a wireless access
technology. 4G can provide better-than-TV quality images and video-links.

COMMUNICATION AND NETWORK CONCEPTS 12


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
10.VOIP :VOIP stands for voice over internet protocol. It enables the transfer of voice using packet switched
network rather than using public switched telephone network. By using VOIP software, phone calls can be
done using standard internet connection.
11.Telnet :remote login service.
12.Remote Destop Sharing : TeamViewer is proprietary software for remote control, desktop sharing, online
meetings, web conferencing and file transfer between computers.
13.Cloud computing: It is a general term for anything that involves delivering hosted services over the
Internet.Cloud Computing is the use of hardware and software to deliver a service over a network (typically
the Internet). An example of a Cloud Computing provider is Google's Gmail. Gmail users can access files and
applications hosted by Google via the internet from any device.

COMMUNICATION AND NETWORK CONCEPTS 13


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
NETWORKING EXERCISES
1.Which communication channel(s) is/are suitable in each of the following situations:
a. Setting up a LAN b. Transfer of data from a laptop to a mobile phone.
c. Transfer of data from one mobile phone to another.
d. Creating a remote control that can control multiple devices in a home.
e. Very fast communication between two offices in two different countries.
f. Communication in a hilly area
g. Communication within a city and its vicinity where cost of cabling is too high.
2. Why is a switch called an intelligent hub?
3. When is a repeater used in a computer network?
4. Diagramatically show how would you connect 6 PCs, 1 server, 1 printer, and 2 scanners in
a. Star topology b. Bus topology
5. Two engineers in the same room have connected their Palm-tops using bluetooth for working on a Group
presentation. Out of the following, what kind of Network have they formed?
LAN, MAN, PAN, WAN
6. What is a MAC address? What is the difference between a MAC address and an IP address?
7. Give some examples of domain names and URLs. How is a domain name different from a URL?
.8.What is domain name resolution?
9. Define Network security? What kind of attacks can be made on data and computer networks?
10. List some methods which are used for network security.
11. Differentiate (with examples wherever possible) between :
a. LAN and MAN b. MAN and WAN c. Hub and Switch d. Guided and Unguided media
12. Write one advantage of star topology over bus topology and one advantage of bus topology over star
topology.
13.Mrs Shasikala is working in an Global Organization. She wants to login in his office computer from her home.
Suggest the protocol for the same.
14.Which device is used for connecting multiple networks over different protocols?
15.Identify the following topologies.
(1) A signal / data packet transmitting from one end to other end in linear way.
(2)Each node is connected to two and only two neighboring nodes in circular form
16.Differentiate between Dedicated and Non-dedicated server.
17. identify the following types of address :
COMMUNICATION AND NETWORK CONCEPTS 14
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
(i) http://www.abc.com/index.htm (ii) 182.68.9.165 iii)aa:bb:1c:22:f3:e4
18. (c) How is a Trojan Horse harmful to a network ?
19. (d) What do the following top level domains signify ?
(i) .edu (ii) .org iii).com iv).in
20. (f) List two measures to secure a computer network.
21. a) Mrs. Geetha is surfing over internet and he wants to know the IP Address of particular website. Do you
know which process he has to do to obtain IP Address from website’s name?
b) Mr. Loknath wants to send/receive e-mail over TCP/IP networks(internet).Which protocol he can use for
this purpose?
c) Which transmission technologies can we use for connecting two countries over an ocean?
d) Mr. Ram is interested in transferring songs from his mobile to Mr. Shyam’s mobile. .Suggest two suitable
wireless options he may use for doing the same.
e) Neha wants to upload/download files from/to a remote internet server.Write the name of the relevant
communication protocol, which will let her do the same.
f) It is technology on computer networks whose purpose is to prevent unwanted networking connection
according to some filtering/blocking rules. What is it?
g) A school with 20 stand-alone computers is considering networking them together and adding a server.
State 2 advantages of doing this.
h)Arrange the following in decreasing order of their speed. Also mention speed of data in brackets.
Ethernet cable, optical fibre, coaxial cable, telephone cable.
i) Define the role of : a)modem b)router c)gateway d)NIC e)RJ-45
j) Define the term Bandwidth. Give any one unit of Bandwidth
k) _______is a device, which is used to connect different types of networks and perform the necessary
translation so that the connected networks can communicate properly.
MULTIPLE CHOICE
1. Which of the following topologies is a combination of more than one topologies?
a. Bus b. Tree c. Star d. None of these
2. Which of the following is used for wireless communication?
a. Optical Fiber b. UTP cable c. Radio Waves d. Coaxial Cable
3. Which of the following is not a transmission medium?
a. Telephone Network b. Coaxial Cable c. Modem d. Microwaves
4. IP addresses of two computers on a network:
COMMUNICATION AND NETWORK CONCEPTS 15
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
a. Can be the same b. cannot be the same c. Are not defined d. Must match with a third computer
5. Bluetooth can be used for
a. Long distance communication b. Short distance communication
c. In mobile phones only d. None of the above
6. Micro waves are
a. Uni directional b. Omni directional c. Guided media d. Not used for communication.
7. Snooping is
a. A threat to data security b. Not a threat to data security c. Good for laptops d. A topology
8. A repeater
a. Regenerates the received signal b. Destroys the received signal
c. Can be used as a hub d. None of the above
9. Satellite links are generally used for
a. PANs b. LANs c. MANs d. All of the above
10. A domain name maps to
a. A URL b. An IP address c. A website d. All of the above
11.YTE industries had setup a center to cater services to entire city of Jamnagar at Indira nagar for its office and
web based services. The company has four centers as shown in the diagram below: 4

AREA1 AREA2

AREA3 AREA4

connectivity distance building Number of


AREA1 to AREA2 building 40m. computers
AREA2 to AREA4 building 120m. AREA1 130
AREA4 to AREA3 building 55m. AREA2 45
AREA2 to AREA3 building 70m. AREA3 55
AREA1 to AREA4 building 115m. AREA4 33
AREA1 to AREA3 bulding 130m

COMMUNICATION AND NETWORK CONCEPTS 16


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY

Now answer the following:


I. Draw a cable layout of connections between centers. Name the topology used and labels the lines and
devices.
II. Which type of network is formed after connection all the AREAS?
III. Suggest the most suitable place to house server and why?
IV. Suggest the placement of switch/hub .
V.Organization is planning to link all the service centers of the city to its international office at
London.Which communication link will be used ,without investing much?

COMMUNICATION AND NETWORK CONCEPTS 17


XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
CHAPTER 2:Open source concepts

Freeware :
 Softwares that are available at no cost
 it cannot be modified.
Example: Adobe Reader, Free Studio and Skype.
Free software:
 Software free of cost and also can be copied and redistributed.
 It can be modified as source code is available.
 It can pose a threat as source code is available for exploitation by crackers.
Example :The Linux kernel, Apache, The Gimp ,PostgreSQL is an object-relational database.
Shareware:
Software whose license fee is payable after some time.
Example :Adobe acrobat 8 professional,PHP Debugger 2.1.3.3,Winzip,Getright
OSS (Open source software):
 Software whose source code is available free of cost and which can be modified, redistributed and
copied.
 It can pose a threat as source code is available for exploitation by crackers.
Example:Apache HTTP web server,Mozilla’s Firefox web browser,Thunderbird email
client,OpenOffice, PHP,perl

FLOSS Free and open source software, also OSS, FOSS, or FLOSS (free/libre opensource software) is software
that is liberally licensed to grant the user right to use, study, change, and improve its design through
the availability of its source code.
Proprietary software(closed source):
 the software that require cost for license to use.
 it cannot be modified as source code is not avaibale.
 It is owned by a single body or organization.
 These provide more security as no source code is available when compared to open source software.
Examples: Windows 10,Macintosh etc.
GNU: GNU’S is not unix
• The GNU Project was launched in 1983 by Richard Stallman of Free Software Foundation (FSF) to
develop a complete Unix-like operating system which is free software: the GNU operating system.

Examples of FLOSS/FOSS :
Operating systems and Desktop environments
• Linux - Operating system kernel
• Ubuntu - Linux distribution with full complement of software for everyday Use.
• Google Chrome OS
• BOSS( Bharat Operating Systems Solutions)
Office software
 OpenOffice.org - office productivity software. Comparable to Microsoft Office. It uses an open file
format and can read and write Microsoft Office files
• NeoOffice - Mac OS X version of OpenOffice
• PDFCreator - creates PDFs from any Windows program.
Graphics and multimedia
• GIMP - Bitmap graphics editor, similar to Adobe Photoshop
• Blender - Advanced 3D modelling and rendering application.
• Songbird - similar to iTunes with built-in browser.
Internet related software
• Apache webserver - web server
OPENSOURCE CONCEPTS 1
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
• Mozilla Firefox - web browser
• Mozilla Thunderbird - mail client
• Google Chrome - Google's web browser

Programming related
• Eclipse - software framework and Java IDE
• PHP - server-side programming language
• PERL - Dynamic programming language
• Python - server-side scripting for websites.
• MySQL - Database management system
• postgreSQL:database management
• Java - Programming language
Open Document format (ODF)
• The Open Document format (ODF) is a format for office documents, such as spreadsheets, databases,
presentations and word-processing documents. Open Document is a free and open format.
• Open Document's main file extensions are .odt (for text documents), .ods forspreadsheets), and .odp
(for presentations).

Ogg Vorbis
• Ogg Vorbis is open audio compression format.
• It is comparable to other formats such as MP3, VQF, AAC etc. used to store and play digital music.
CHARACTER ENCODING SYSTEM
Character encoding system consists of a code that associates each character from a given system with
something else, such as a sequence of natural numbers, binary numbers or electrical pulses, in order
to facilitate the transmission of data (generally numbers and/or text) through telecommunication
networks or for storage of text in computers
• ASCII, EBCDIC, and UNICODE are the most widely used character encoding systems for computers.
ASCII: American Standard Code for Information Interchange is 7-bit character coding.
EBCDIC :Extended Binary Coded Decimal Interchange Code (EBCDIC) is an 8-bit character encoding
ISCII
• ISCII - Indian Script Code for Information Interchange is common standard for coding Indian Scripts.
• ISCII is an 8 bit encoding system as compared with the 7 bit ASCII.
INDIAN scripts can be entered( Devnagri, Kannad, Tamil, Gurumukhi etc use Unicode)
• Using phonetic text entry
• Using keymap based entry.
UNICODE - Universal Code is a single standard code which can cater to all the world's languages.
UNICODE is language, platform and vendor independent.
• Unicode characters are represented in one of the three encoding forms:
a 32-bit form (UTF-32), a 16-bit form (UTF-16), and an 8 bit form (UTF-8).
• The 8-bit, byte oriented form, UTF-8, has been designed for ease of use with existing ASCII-based
systems.

Different Types of Fonts


Post Script- This font consists of two parts which are both necessary for the font to be properly printed
and displayed on screen.
True Type-These fonts contain both the screen and printer font data in a single component, making the
fonts easier to install.
Open Type- Like True Type fonts, this contains both the screen and printer font data in a single
component. However, open type fonts also support multiple platforms and expanded character sets.

Static and Dynamic fonts-


On the basis of their configuration, fonts are categorized as static fonts and dynamic fonts.

OPENSOURCE CONCEPTS 2
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
Static fonts –
In these types of fonts the characters are designed and digitized and then stored in font files. Every time
printing takes place, same character will appear with same shape e.g. Times New Roman, Arial etc.
Dynamic fonts –
Dynamic font is a web browser technology used when visiting any website that uses fonts which are not
installed on client's machine. All hand written fonts such as handwritten alphabets, calligraphic letters,
graffiti etc are dynamic fonts because of individual variations.

Entering Indian language text:


Many tools have been developed to facilitate the typing of Indian language text. They support two types
of text entries:
Phonetic Text Entry-
In this type of text entry, traditional keyboards with English keys are used. But while typing, the Indian
alphabets are written phonetically (i.e., the way they sound as per the pronunciation) in English Script
and then converted to corresponding language word.
Keymap based Text Entry-
In this method the keyboard keys are mapped to specific characters using a keymap. A keymap is
internally stored as a table.

ABBREVIATION AND THEIR EXPANSION


ISCII - Indian Script Code for Information Interchange
GNU: GNU’S is not Unix
OSS : (Open source software)
FOSS: FREE OPEN SOURCE SOFTWARE
FLOSS: FREE LIBRE OPEN SOURCE SOFTWARE
GPL: General Public License
TTF: True Type Font
GPS: Global System For Mobile Communication
GPRS: General Packet Radio Service
EDGE: Enhanced Data rates for global evolution
GIF: Graphical Interchange File Format
TIFF: Tagged Interchanged Format
BMP: BITMAP IMAGE.
JPEG: Joint Photograph Expert Group
MPEG: MOTION PICTURES EXPERT GROUP
PNG: Portable Network Graphics.
SVG: Scalar Vector Graphics
WIFI: WIRELESS FIDELITY WIFI IS WIRELESS LAN(1Mbps to 20 Mbps)
WIMAX: Wordwide operability through microwave access is wireless internet service to entire
city(50Mbps to 70Mbps)
MPEG-1 or MPEG-2 Audio Layer III, more commonly referred to as MP3, is an encoding format for digital
audio which uses a form of lossy data compression.
Advanced Audio Coding (AAC) is a standardized, lossy compression and encoding scheme for digital audio.
LAMP: LINUX APACHE MYSQL PHP
PHP: HYPERTEXT PREPROCESSOR
UNICODE : UNIOVERSAL CODING
RDBMS: RELATIONAL DATABASE MANAGEMENT SYSTEM
HTTP: HYPERTEXT TRANSFER PROTOCOL
TCP/ IP: TRANSMISSIOM CONTROL PROTOCOL/ INTERNET PROTOCOL
FSF : FREE SOFTWARE FOUNDATION.
ASCII: AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE.
NRCFOSS : National Resource Centre for Free and Open Source Software.

OPENSOURCE CONCEPTS 3
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
ODF : Open Document format
ICT: INFORMATION AND COMMUNICATION TOOLS
BOSS Bharat Operating Systems Solutions
URL: Uniform Resource Locator
MAC (Media Access Control)
SMTP: Simple mail transfer protocol) is used to send e-mail.
POP (post office protocol) is used to access or receive e-mail from servers.
UDP: User datagram protocol is used to send data like IP.
FTP: File transfer protocol is used to upload and download files
NIC: Network Interface Card / Unit
WIFI: WIRELESS FIDELITY

OPENSOURCE CONCEPTS 4
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
ASSIGNMENTS(OPENSOURCE)
1) Which one is not the feature of free software

a) Freedom to run the program for any purpose.


b) Freedom to redistribute copies.
c) Freedom to study how the program works only and will not to modified.
d) Freedom to improve the program and release your improvements to the public
2) Which software is free of cost but its source code is not available?
a) FSF b) GNU c) Freeware d) Proprietary software
3) Which software is neither open nor freely available?
a) FSF b) Shareware c) Freeware d) Proprietary software
4) In which software after a certain period of time,license fee should be paid?
a) LINUX b) Freeware c) Shareware d) FSF
5) Which software is a freeware and a free internet software suite that include a web browser, Email/IRC
clientand HTML editor as well?
a) Mozilla b) LINUX c) Apache server d) Netscape navigator
6) Which is the most popular open source database system and is part of world’s popular set of LAMP
program?
a) PostgreSQL b) MySQL c) Pango d) LINUX
7) Open source softwares are modifiable because
a) They are freely available
b) Source code is freely available
c) They are free to run
d) License is available
8) Standards for which users have to buy license to use them are?
a) Open standards (ODF) b) OGG Vorbis c) Proprietary software d) PDF
9) When we type Indian language words in Phonetically in English script and tool will convert them into
corresponding language words is called as:
a) Transliteration b) Keymap based entry c) phonetic based entry d) Both a and c
10) _________ provides a unique number for every character, no matter what the platforms, no matter
what the program, no matter what the language?
a) OGG Vorbis b) Unicode c)ASCII d)ISCII
11) Unicode can represent ______ characters?
a) 65536 b)94999 c)94140 d) 90000
12) __________ is a new audio compression format which is open format and is completely free?
a) OGG Vorbis b) APE c) MP3 d) WMA
13) ________ refers to unauthorized access to someone else’s data, email, or computer activity?
a) Snooping b) Eavesdropping c) Hacking d) Cracking
14) ASCII stands for :
a) American standard code for information interchanging
b) American standard code for information interchange
c) American suitable code for information interchanging
d) American suitable code for information interchange.
15) The Indian script included in Unicode
a. Devnagri b. Telguc. Kannada d. All
16) A programming language primarily for server side applications and developing dynamic web content.
a. MySQL b. LAMP c. PHP d. Linux
17) It refers to freely available file format for saving and exchanging office document such as spreadsheets,
database charts & presentation:
a. MS Office b. PDF c. ODF d. DBMS
18)”Free Libre Open Source Software” is the full form of
a) FLOSS b)FOSS c) OSS d) FSF

OPENSOURCE CONCEPTS 5
XII-IP-NOTES GAJENDRA S DHAMI,PGT(CS),LPS ,SOUTH-CITY
19) Which of following is used as freely available operating system,which we can use it, modify it &
redistribute it.
a) Tom cat b) LINUX c) OSS d) Window 7
20)SDLC stands for
a) System Development Life Cycle
b) Software Development Life Cycle
c) Software Developers Life Cycle
d) System Developers Life Cycle
21) Open Type Font is a _______ bits font.
a) 8 b) 16 c) 32 d) 64
22)The features that differentiate free software with freeware is/ are:
a) Modification in program
b) Availability of source code
c) Study how the program works
d) all of the above
23) In freeware the word “FREE” denotes:
a) Free Availability through internet
b) Freedom to use, study, redistribute, and modify the software
c) Both a and b
d) None of the above
24) Example of shareware are :
a) MS-office b) Avast antivirus c) Adobe Photoshop d) ALL
25) Which of them is not a freeware/ OSS :
a) Open Office b) MS Office c) Linux c) MySQL
Q26. Expand the following terms:-
(i) SDLC (ii) FlOSS (iii) DDLC (iv). GUI (v) GNU
Q27. Which is not a Web Browser:-
(i) Mozilla (ii) Google Chrome (iii) Windows Explorer (iv) Netscape Navigator
Q28. Which is a proprietary software:-

(i) Open Office (ii) Fire Fox (iii) MS Office (iv) GNU

1) Define Open source software. Give at least two examples of OSS. Justify that free software is not open
source software.
2) Give examples of two OSS in each of the following categories :
(a) OS (b) Graphics and animation (c) Office software (d) Internet related software
(e) Programming related software.
3) What is a character encoding system?
4) Differentiate between true type font and open type font.
5) What do you understand by ODF?
6) What is Ogg Vorbis?
7) Expand the following terms:
OSS, FLOSS, ISCII, ASCII, BOSS, NRCFOSS,FSF,GSM,GPRS
8) What is UNICODE?
9) Write short notes on GNU, BOSS, ISCII
10) What is the difference between static and dynamic fonts?
11) Give difference between proprietary and open source software
12)list disadvantage of using open source software.
13)List advantages of using proprietary software

OPENSOURCE CONCEPTS 6
Notes By :
Md. GHAYAS
PGT(IP) ,LPS,GOMTINAGAR
Chapter-13
MySQL Revision Tour
Database: A database is an organized collection of data, generally stored and
accessed electronically from a computer system.

Advantages of database:
i) It reduces data redundancy (duplication of data).
ii) It controls data inconsistency.
iii) It provides global sharing of data.
iv) It provides integrity of data.
---------------------------------------------------------------------------------------------------
Data Models
Data model is a set of concepts to describe the structure of database and constraints
that database should obey.
Note: Basically it is a type of some rules for database which should have to be
followed by database.
Database models are of four types:
1- The Relational Data Model
In relational data model, the data is organized into tables.
2-The Network Data Model
In a network database, the collections of records are connected to one another by
means of links. Links means that it is an association between precisely two records.
3-The Hierarchical Data Model
In this model, data records are organized in tree structure format.
4-Object Oriented Data model
Object oriented data model is based upon real world situations. These situations are
represented as objects, with different attributes. All these objects have multiple
relationships between them.
----------------------------------------------------------------------------------------------------
Some important terminologies:-
Relation: Relation is sometimes used to refer to a table in database but is more
commonly used to describe the relationships that can be created between those
tables in a relational database.

Domain: A domain is defined as the set of all unique values permitted for an
attribute.
Example- A domain of date is the set of all possible valid dates, a domain of day-
of-week is Sunday, Monday….Saturday.

XII-IP-NOTES/MYSQL REVISION TOUR 1


Tuple: A row of a table in a database is also known as tuple.
Attribute: The headings of the column in a table are known as the attributes of the
table.

Degree: Number of attributes (Total numbers of columns present in a table) is


known as the degree of the table.

Cardinality: The number of tuples(rows) present in a table is known as cardinality


of the table.

Primary key: Primary key contains unique records and null value cannot be
inserted in the primary key column. There will be only one column as a primary
key in a table.

Candidate Key: A candidate key can be any column or a combination of columns


that can qualify as unique key in the database. There can be multiple candidate
keys in a table.

Alternate Key: If any table have more than one candidate key, then after choosing
primary key from those candidate key, rest of candidate keys are known as an
alternate key of that table.

Foreign key: Foreign key are those keys which is used to define relationship
between two tables. When we want to implement relationship between two tables
then we use concept of foreign key. It is also known as referential integrity.
Foreign key is generally a primary key from one table that appears as field in
another where the first table has a relationship to the second table.
In other words, if we had a table A with a primary key X that linked to a table B
where X was a field in B, then X would be a foreign key in B.
----------------------------------------------------------------------------------------------------

Different Types of SQL Statements:


The SQL statements have been categorized as follows:
1-Data Definition Language (DDL) - contains create, alter and drop commands.
2-Data Manipulation Language (DML) - contains insert, update and delete
commands
3-Transaction Control Language (TCL) – contains begin, commit, autocommit,
savepoint, rollback commands.
---------------------------------------------------------------------------------------------------

XII-IP-NOTES/MYSQL REVISION TOUR 2


Comments in MySQL:
Comments in mysql are used for documentation purpose which is not get executed.
Comments can be written in following three ways in MySQL-
i) It can be enclosed within /*…..*/ when we will have to assign multiline
comments.
ii) It can be begin with hyphens followed by space(-- ) for single line
comment.
iii) It can begin with # symbol, it is also a single line comment.
----------------------------------------------------------------------------------------------------

Working with database and tables and


executing various commands
Creating database:
Syntax: create database databaseName;
Eg: create database dept;

Using database Syntax: use databaseName;


Eg: use dept;

XII-IP-NOTES/MYSQL REVISION TOUR 3


Now after selecting or using a database , we can create table in that database as
follows:
Syntax for creating a table: create table tableName(column1 dataType,col2
dataType……..column N dataType);

Que: Create the table ‘emp’ as the structure given below in the table:-

Column_name Datatype(size) Constraint


sNo Int Primary key
Name Varchar(34)
Address Varchar(45) --
Salary Int --
DOB Date --

Ans:
create table emp
(
sno int primary key, name varchar(34),
address varchar(45), salary int, DOB date
);

Inserting records in a table:


Syntax: insert into tableName values(value1,value2,…..value n);
Note: The values should be passed as matching columns in the created table. You
cannot shuffle the values of different columns while inserting the records.
Eg: insert into emp values(1, ‘harish’, ‘gomtinagar’,55000, ‘1990-12-28’);

XII-IP-NOTES/MYSQL REVISION TOUR 4


Now in the similar way add few more records and display all records by using the
select query:

Displaying selected columns: Suppose if you want to display only the name and
salary columns then the sql query will be as follows-

XII-IP-NOTES/MYSQL REVISION TOUR 5


Distinct Keyword: This keyword removes all the duplicate entries present in the
column at the time of output. Example is given below:

Note: Earlier when we used select command without the distinct clause it
represented all seven records but this time it has removed all the duplicate entries
of salary which were similar and represented only distinct (unique) records
available in the salary column.

All Keyword: This will display all the records of a column whether it is repeated or
not.

Note: All the seven records are available now whether it is duplicate or not.

Displaying all ready created Databases and Tables:


In order to display already created databases and tables we will use ‘show’
command.
1) For displaying all databases available on your dbms use show databases;
command.
2) For displaying all tables in a particular database use show tables; command.

XII-IP-NOTES/MYSQL REVISION TOUR 6


Note: Here we had used dept database and then executed show tables command to
view all tables available in this database.

Describing table structure:


Table structure means how many columns are there in that table, what are the data
types and size assigned to them, what are the constraints and default values are
used with them.
For this we will use ‘desc’ or ‘describe’ command as follows:

Performing Simple calculation using select command on MYSQL:

We can done any simple calculation without selecting any database and table on
mySql prompt. Some of the examples are-

XII-IP-NOTES/MYSQL REVISION TOUR 7


‘/’ Symbol will return quotient

‘%’ symbol will return remainder

Note: In the above examples we had not used any table name as we did earlier
followed by ‘from’ clause.
Column aliases:
 Column aliases mean taking another name of a column at the time of output.
 We will use ‘as’ keyword to make column alias.
 Column aliases are the temporary name assigned to a column which will not
reflected any physical changes on the table.

Que. Now consider the above table ‘emp’ and display sNo as series, name
column’s heading should be changed as FirstName and salary as sal.

Ans: select sno as 'series', name as 'FirstName',salary as 'sal' from emp;

All the headings are temporary gets changed

XII-IP-NOTES/MYSQL REVISION TOUR 8


Inserting NULL values in the table:
Suppose you do not want to enter salary of certain employee then follow this
query-

Insert into emp(sno,name,address,DOB) values (8, ‘xyz’,‘abc’, ‘1991-2-2’);

Note: Here we break down the above query into two, firstly we have taken the entire columns
name where value has to be passed and secondly in a bracket we passed the values accordingly
to the columns taken in first bracket. The salary column is not taken in the first bracket so the
value of salary had not been passed where we will see NULL automatically appear in that place
for this record.

IFNULL(columnName, ‘Value’):
IFNULL is a function which is used to write certain statements or words wherever
the null record is found in a column.

Que. Display all the records of emp table including name, salary and wherever null
record is found in the salary column, replace it with the text ‘Salary not assigned’.
Ans:
select name, ifnull(salary,'Salary not assigned') from emp;
or
select name, ifnull(salary,'Salary not assigned') as 'sal' from emp;

Text has been changed

Note: Observe the column’s heading by both queries too.

XII-IP-NOTES/MYSQL REVISION TOUR 9


‘Where’ clause: In MySQL ‘where’ clause is used to filter the record. We can use
relational operators according to our need to filter the records from table.

 Display all the records from emp table whose address is ‘gomtinagar’.

 Display the name of those employees whose salary is less than 30000;

 Display the name and salary of those employees whose address either is
gomtinagar or nishatganj.

Range Based searching:


There are ‘Between’ and ‘Not Between’ clause used for ranged based searching.
a) Between clause: It will search the range including starting and endpoint.
b) Not Between clause: It will search the range excluding starting and
ending point passed in the query.
Q. Display name and salary of those employees whose salary are greater than
or equals to 10000 and less than or equals to 30000.

XII-IP-NOTES/MYSQL REVISION TOUR 10


Note: the above query can also be solved by using the logical operator ‘and’ in the
following way:

Q. Display name and salary of those employees whose salary should not be in
the range of 10000 to 30000.

Pattern Searching:
Pattern searching is used to search several texts with starting or ending characters
of words. There are two special characters use in pattern searching, ‘%’( modulo
sign) and ‘_’ (underscore symbol).
% sign search for the sub string whereas _ symbol is used for exact searching of
characters. Let’s have an example for this:-

Q. Display the name of those employees who are having the character ‘u’ at
the end of their name.

XII-IP-NOTES/MYSQL REVISION TOUR 11


Q. Display the name and salary of those employees whose name starts with
‘h’.

Q. Display the name of those employees who are having character ‘a’ as their
fourth character.

Note: In the above query for searching fourth character as ‘a’ , we had used 3
underscores symbol ‘_’ and after that any characters can be there in the name so
‘%’ symbol has been used.

Conditional Searching:
We will use ‘IN’ and ‘NOT IN’ clause for conditional searching. Conditional
searching search just like ‘OR’ logical operator, means any of the condition holds
true it will return some output. Let’s have an example-
Q. Display name and address of those employees who either belongs to
alambagh, gomtinagar or rajajipuram.

XII-IP-NOTES/MYSQL REVISION TOUR 12


Q. Display name and address of those employees whose address is not
alambagh, gomtinagar or rajajipuram.

IS NULL CLAUSE:
This clause is used to search NULL records in a table.
 As we had already inserted a null record in the original table as given below:

Now we will have a demonstration of ‘is null’ clause on this table:-


Q. Display name, salary and address of those employees where salary is blank
or not given.

IS NOT NULL CLAUSE:


It will search all those values where NULL record is not found, means all the value
will be filled in that column.
Q. Display name, salary and address of those employees where salary is not
blank.

Note: In salary column there is no blank or NULL record has been extracted this time.

XII-IP-NOTES/MYSQL REVISION TOUR 13


ORDER BY CLAUSE:
‘Order by’ clause is used to arrange a column’s record either in ascending or in
descending order. By default it will arrange the records in ascending order.
Q. Display name and salary of the employees according to their name in
ascending order.

Q. Display name and salary of the employees according to their name in


descending order.

Note: ‘desc’ keyword is used after column name in order to arrange the records of name
column in descending order.

Modifying Data in Table:


We will use ‘update’ command with ‘set’ keyword before the column name whose
(column’s value) value has to be updated or edited.
Q. Change the name of serial number 4 to ‘james’.
Updating record

Observe changes on original table

XII-IP-NOTES/MYSQL REVISION TOUR 14


Deleting record(s) in Table:
Delete command is used for deleing records in a table.
Q. Delete the record of those employees whose address starts with the letter
‘a’.

2 Records have been deleted from table

Q. Delete the record of that employee whose name is ‘harish’.

Q. Delete all the records of the table emp.

Note: When select command has been fired then no output has been extracted as all of the
record got deleted from emp table.

Altering record(s) in Table:


Alteration of a table means we are going to change physical structure of a already created table.
We can make changes on a table on the following points:
 To add a column to already created table.
 To remove a column from already created table
 To change the data type of column
 To change the permanent name of a column with a new name.
 To shuffle a column
 To add constraint to a column.

XII-IP-NOTES/MYSQL REVISION TOUR 15


Note: As we had deleted all the rows of ‘emp’ table, so now no output will be
shown by ‘select’ command. ‘Alter’ command will reflect the changes on ‘emp’
table’s physical structure, so we will use ‘describe’ or ‘desc’ command to view the
physical structure of table for any changes done with the help of ‘alter’ command.

 Before Using alter command the ‘desc’ command has shown the following
details of the table:

1) To add a column to already created table:

Q. Write a query to add ‘city’ column to the table ‘emp’.


Query to add column ‘city’

City column has been added

2) To remove a column from already created table:


Q. Write a query to remove column ‘city’ from the table ‘emp’.
Query to remove column ‘city’

XII-IP-NOTES/MYSQL REVISION TOUR 16


3) To change data type of a column:

Q. Write a query to change column address data type from varchar to char.

Query to change data type

Now observe the changes made on address data type. We had used ‘modify’ keyword while
changing the data type.

4) To change the permanent name of a column with a new name:

Q. Write a query to change the column name ‘sno’ to ‘EmpId’ of ‘emp’ table.

Note: In the above alter query we had used change command in order to change the old name of
column (sno) to new name (EmpId).

5) To shuffle a column:
Note: modify clause is used to shuffle the columns in a table.
Q. Write a query to shuffle ‘DOB’ column which is present at the last position
in the table after ‘name’ column.

XII-IP-NOTES/MYSQL REVISION TOUR 17


Observe the changes in the ‘emp’ table structure, ‘DOB’ column has been shuffled.

Q. Write a query to shuffle salary column at the starting position of the table
‘emp’.

6) To add constraint to a column:

Q. Write a query to add NOT NULL constraint to the name column.

Constraint added

XII-IP-NOTES/MYSQL REVISION TOUR 18


MySQL Functions
MySQL functions are basically categorized into three:-
1) String Functions
2) Numeric Functions
3) Date and Time Functions
1) String Functions
a) Char() : It returns the character for each integer according to its ASCII
value.

b) Concat(): It returns concatenated string.

c) Lcase(): It returns the argument in lowercase.

d) ucase(): It returns the argument in UPPERcase.

XII-IP-NOTES/MYSQL REVISION TOUR 19


e) substr() : It returns the subpart of the string as specified in the argument list.

f) Ltrim(): Removes leading spaces from the string.

g) Rtrim(): Removes trailing spaces from the string.

h) Trim(): Removes space from both sides.

i) Instr(): It returns the index of the first occurrence of substring.

XII-IP-NOTES/MYSQL REVISION TOUR 20


j) Length(): It returns the length of string by counting it’s all characters.

k) Left(): It returns the leftmost number of characters as specified.

l) Right(): It returns the specified rightmost number of characters.

m) Mid(): It is just like substr() function and do the same thing.

2) Numeric Functions
a) Mod(): It returns the remainder of one expression by dividing by another
number.

XII-IP-NOTES/MYSQL REVISION TOUR 21


b) Pow(): It returns the value of one expression raised to the power of another
expression.

c) Round(): It returns numeric expression rounded to an integer. Can be used


to round an expression to a number of decimal points.

d) Truncate(): It returns numeric exp1 truncated to exp2 decimal places. If


exp2 is 0, then the result will have no decimal point.

XII-IP-NOTES/MYSQL REVISION TOUR 22


Error due to second expression is missing

e) Sign(): It will return sign of a given number either in ‘+’ or in ‘-’.

f) Sqrt(): It returns the non-negative square root of numeric expression.

3) Date and Time Functions


a) Curdate(): It returns the current date of your system.

XII-IP-NOTES/MYSQL REVISION TOUR 23


b) Date(): It Extracts the part of a date-time expression.

c) Month(): It returns the month part from the date passed.

d) Year(): It returns the year part from the date passed.

e) DayName(): It returns the name of the weekday.

f) DayOfMonth(): It returns the day of month between 1 to 31.

XII-IP-NOTES/MYSQL REVISION TOUR 24


g) DayOfWeek(): It returns the number position of weekday from 1
to 7. It starts counting from Sunday as 1,Monday as 2….and so on.

h) DayOfYear(): It returns the number between 1 to 366 for the date passed
and tells the exact the number of day of that year.

i) Now(): It returns the current date and time of the system.

j) Sysdate(): It returns the time at which the function executes.

XII-IP-NOTES/MYSQL REVISION TOUR 25


Difference between now() and sysdate():
There is a function known as sleep(), which takes integer argument as the
number of seconds, so if we pass the both functions using sleep() , we can
find out the exact difference between them. Here is the example-

From the above query, we can observe that now() function returns the time
when query has been started or we can say that current time when query is
fired but after that 4 seconds of pause, it can clearly observe from the above
query that sysdate() has showing the time delay of 4 seconds i.e 08:40:40 ,
when it is executed.

Constraints: Constraints are used to validate the value of a column. They are as
follows:-
1. Unique key: Ensures that all values in a column are different.
2. Primary key: Used to uniquely identify a row in the table.
3. Default: Provides a default value for a column when none is
specified.
4. Check: Makes sure that all values in a column satisfy certain criteria.
5. Foreign key: Used to ensure referential integrity of the data.
6. Not Null: Ensures that a column cannot have NULL value

Q. Write a query to create a ‘shop’ with the following detail.


ColumnName Data type Size Constraint
Code Int 5 Primary key
Item Varchar 25 Not null
Company Varchar 30 Unique
Qty Int - Qty>10
City Varchar 35 Default ‘Lucknow’
Price Int - -
Ans:

XII-IP-NOTES/MYSQL REVISION TOUR 26


Dropping Table and database:

We will use drop command to delete a table or database permanently.

Note: After dropping the table or database, desc and use command are not
executing respectively, as the table and the database after drop query has been
deleted successfully.

Multiple choice questions


Q1. Which of the following are not valid data types of MySQL?
a) char b) String c) char d) DOB
Ans: b and d

Q2. Identify the DDL command from the following?


a) commit b) insert c) select d) create
Ans: d

Q3. Which of the following functions returns the name of the weekday?
a) dayname() b)dayofweek() c)dayofyear() d)now()
Ans: a

XII-IP-NOTES/MYSQL REVISION TOUR 27


Q4. Which functions returns the index position of the first occurrence of
substring?
a) substr() b) mid() c) instr() d) char()
Ans: c

Q5. Which symbol is used for exact pattern searching of a string?


a) % b) _ c) $ d) @
Ans: b

Q6. Which clause is used to edit text where ever NULL record is found?
a) NULL b) NOT NULL c) IS NULL d) IFNULL
Ans: d

Q7. Which is the valid comment according to MySQL platform?


a) comment b)<!--> c) /*….*/ d) //
Ans: c

Q8. Degree of the table means number of ____ of the table?


a) rows b) columns c) rows*column d) rows+columns
Ans: b

Q9. Which clause is used to change the old data type of a column in MYSQL?
a) change b) modify d) add d) drop
Ans: b

Q10. Which of the following functions takes more than one arguments in their
parameter part?
a) length() b)substr() c) sign() d) concat()
Ans: b and d

Assignment for students


Q1. Differentiate between char and varchar data types.
Q2. Differentiate between DDL and DML commands.
Q3. Differentiate between drop and delete command.
Q4. Write SQL query to create a table ‘Inventory’ with the following structure:

XII-IP-NOTES/MYSQL REVISION TOUR 28


Q5. Consider the following table ‘Furniture’. Write SQL commands for the

statements (i) to (vi) and write output for SQL queries (vii) to (x).
Table : Furniture

i) To display FCODE ,NAME and PRICE of items that have PRICE less than ₹
5,000.
ii) To display NAMES and PRICE of those Furniture Items that have ‘table’
anywhere in their names.
iii)To display WCODE of Furniture Items. There should be no duplicate values.
iv)To display the NAMES and PRICE increased by 500.00 of all the furniture
items. (Price should only be displayed as increased; there should be no increase in
the data in the table)
v) To display FCODE and NAME of each Furniture Item in descending order of
FCODE.
vi) To display the details of all the Furniture Items which have Manufacturing
date( MANUFDATE ) between 01-JAN-2016 and 15-JUN-2017 (inclusive of
both the dates).
vii) Select count(distinct price) from furniture;
viii) Select substr(Name,2,3) from furniture;
ix) Select length(Name) from furniture;
x) Select name from furniture where name like ‘_ _ _ i%’;

Q6. A table ‘Gym’ has 7 rows and 17 columns.5 rows added to this table and 5
columns were deleted from this table. What is the cardinality and degree of this
table now?
xxxxxxx

XII-IP-NOTES/MYSQL REVISION TOUR 29


Notes by:
AMIT PATHAK,PGT(IP),
LPS,RAE-BARELI
CHAPTER NO. :- 14
CHAPTER NAME :- DATABASE TRANSACTION

Brief Summary of the Chapter:


Reliability is a quality, which we seek for in everything that we get. The same is
applicable to software and to database. A reliable database system is that which
retains our database in a consistent state despite occurrence of many failures.
Database Transaction is the field which requires utmost consistency. This chapter
describes fundamentals of database transactions and its reliable implementation. A
database can be called consistent when it follows ACID properties. A transactions
can be called reliable when it either COMMITED i.e. successfully all its steps are
carried out and changes are permanently reflected in the database or be
ROLLBACKed i.e. in case of failures, if transaction cannot be successfully completed
then any data changes made by the transaction are brought back to the state that
earlier was prior to the execution of this transaction.

KEY POINTS OF THE CHAPTER

TRANSACTION-A set of successive statements that succeed or fail as a group so


that all effected statements of the group are retained or all are discarded are called
transactions. When a transaction is done on the database is called database
transaction.

TCL Commands:- These are the used to control the transaction. TCL Commands
are given below.
1. BEGIN / START TRANSACTION:- This statement marks the start of a
transaction.
Every transaction should be started with BEGIN or START TRANSACTION
command, but if these commands have not been used then all SQL
statements are considered to be wrapped in one transaction which is called
implicit start of the transaction.
A transaction ends with a COMMIT or ROLLBACK command.

2. COMMIT-This statement is used to end a transaction and make all changes


permanent. Until a transaction is committed, other users cannot see the
changes made to the database.
Committing a transaction means all the steps of a transaction are carried out
successfully and all done changes are permanently saved in the database.

3. ROLLBACK- The ROLLBACK statement is used to end a transaction and


undo the work done by that transaction. After ROLLBACK, it looks like that
transaction had never begun.
Rollback means transaction has not been finished completely and discards
the done changes in database.

4. SAVEPOINT- It is point in a transaction, up till which all changes have been


saved permanently. It is used to divide the work of a transaction into different
segments. In case of failure, transaction can be rollbacked to the mentioned
savepoints only, leaving prior changes intact.
5. SET autocommit:-
 To enable the autocommit, the value of autocommit must be set as 1.
XII-IP-NOTES/DATABASE TRANSACTION 1
Set autocommit = 1;
 To disable the autocommit, the value of autocommit must be set as 0.
Set autocommit = 0;
By default, My SQL has autocommit on means it is set as 1.

Modes to manage the transactions:-

1. Autocommit On:- It is default mode. In this mode, every single SQL


statement is a new transaction because all the done changes will be
committed at the end of the statement execution by pressing semi colon (;)
after each SQL statement.

2. Autocommit Off:- In this mode multiple SQL statement can be grouped into
a single transaction. If autocommit is off then commit keyword should be
used manually by typing the COMMIT keyword.

SOLVED QUESTIONS
1. Define a transaction.
Ans. -A transaction is a logical unit of a work that must succeed or fail in its entirely.
It is an atomic operation which can be divided unto smaller operations.

2. What are the two ways in which multiple transactions can be executed?
Ans. - Multiple transactions can be executed in one of the following two ways:
(i) Serially (ii) Concurrently

3. What is a savepoint?
Ans. - Savepoints are special operations that allow you to divide the work of a
transaction into different segments. In case of a failure, you can execute rollbacks to
the savepoint only, leaving prior changes intact.

4. What to you understand by a database transaction?


Ans. - A database transaction is a logical unit of work that must succeed or fail in its
entirely.

5. Why do understand by transaction COMMIT and ROLLBACK?


Ans-COMMITing a transaction means all the steps of a transaction are carried out
successfully
and all data changes are made permanent in the database. Transaction ROLLBACK
means transaction has not been finished completely and hence all data changes
made by the transaction in the database if any, are undone and the database returns
to the state as it was before this transaction execution started.

6. What do you understand by ACID properties of database transaction?


Ans. -To ensure the data-integrity, the database system maintains the following
properties of transaction. The properties given below are termed as ACID properties-
an acronym derived from the first letter of each of the properties.

(i) Atomicity-This property ensures that either all operations of the transactions are
reflected properly in the database, none are. Atomicity ensures either all-or-none
operations of a transaction are carried out.

(ii) Consistency-This property ensures that database remains in a consistent state


before the start of transaction and after the transaction is over.

XII-IP-NOTES/DATABASE TRANSACTION 2
(iii) Isolation-Isolation ensures that executing transaction execution in isolation i.e.
is unaware of other transactions executing concurrently in the system.

(iv) Durability-This property ensures that after the successful completion of a


transaction i.e. when a transaction commits, the changes made by it to the database
persist i.e. remain in the database irrespective of other failures.

7. What the function is of redo and undo logs?


Ans. -Every database has a set of redo log files. It records all change in data
including both committed and uncommitted changes. Undo logs stored roll backed
data.

8. What TCL commands are supported by SQL?


Ans. -SQL supports following TCL commands
_ BEGIN |START TRANSACTION-Marks the beginning of a transaction
_ COMMIT-Ends the current transaction by saving database changes and starts a
new transaction.
_ ROLLBACK-Ends the current transaction by discarding changes and starts a new
transaction.
_ SAVEPOINT-Defines breakpoints for the transactions to allow partial rollbacks.
_ SET AUTOCOMMIT-Enables or disable the default autocommit mode.

9. Which two statements complete a transaction?


A. DELETE employees;
B. DESCRIBE employees;
C. ROLLBACK TO SAVEPOINT C;
D. GRANT SELECT ON employees TO SCOTT;
E. ALTER TABLE employees
MODIFY COLUMN sal;
F. Select MAX(sal) FROM employees WHERE department_id=20;
Ans. - C, E
UNSOLVED QUESTIONS
1. What is the benefit of transaction?
2. What are the five states of the transactions?
3. What will happen when COMMIT statement is issued?
4. What will happen when ROLLBACK statement is issued?
5. How can you start a new transaction?
6. What happens to the current transaction if a DDL statement is executed?
State your answer.

XII-IP-NOTES/DATABASE TRANSACTION 3
Notes by:
AMIT PATHAK,PGT(IP),
LPS,RAE-BARELI
CHAPTER NO. :- 15
CHAPTER NAME :- GROUPING RECORDS & TABLE JOINS.

Functions in My Sql:- MySql provides 2 types of functions which are listed


below.

1. Scalar/ Single row functions:- functions which work on a single row at a


time, called Single Row Functions. It returns result for every row of a
queried table. Example: length(), upper(), left(), instr() etc.
2. Aggregate/ Multiple row functions:- functions which work on more
than one row at a time, called Multiple Row Functions. It returns
aggregated values. Example: count(), max(), min(), average(), sum().
NOTE: While performing aggregate operations no other columns can
be selected except the column on which the operation is being
performed.
Table :Marks

SRNo Maths Hindi English


5439 85 70 93
77 60 67
3645 83 80 87
7553 69 60 84
3439 87 70 89
The above given table will be used in following Sql Statement.

a. AVG():- It returns average of the given data as numeric parameter.


Example :- Select avg (hindi) from marks;
Output : 66

b. MAX():- It returns maximum value from a given column of a table.


Example :- Select max (english) from marks;
Output : 93

c. MIN():- It returns minimum value from a given column of a table.


Example :- Select max (maths) from marks;
Output : 69

d. SUM():- It returns the sum of values in given column.


Example :- Select sum (hindi) from marks;
XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 1
Output : 330

e. COUNT():- It counts the number of rows in a given column or of


the given table..
Example :-
i. Select count (*) from marks;
The above mentioned query returns the total number of
row or tupples of table.
Output : 5

ii. Select count (srno) from marks;


The above mentioned query returns the total number of
values presented in column SRNO. It does not count the
null.
Output : 4

iii. Select count (distinct hindi) from marks;


The above mentioned query returns 3 as output because
distinct keyword ensures that multiple entries of the same
marks are ignored.
Output : 3

Distinct :- it is used to eliminate the redundant data of mentioned


column/ field of a table.

Example:- Select distinct (hindi) from marks;

Output :- Hindi
70
80
60

GROUPING RESULT – GROYP BY

Group by clause combines all those records that have identical


values in a particular field or a group of fields.

When we use any aggregate function on a table, it returns a single row


and column containing the result of used aggregate function. Many a
times we need to calculate some values in groups based on some
columns i.e. we want to create groups based on some column values
and then to perform aggregate operations separately on each group.
XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 2
i.e. in a table Student(SRNo, Name, Class, FeesPaid) if we need to find
out the total of fees paid by each class, we need to create groups on
columns class i.e. all records for a particular class will be kept in a single
group by using GROUP BY clause and then the total of this group will be
find out. As many groups will be used here as many class values are
there in table. So the result of this type of select statement will give us
as many rows in result as many class values are there in the table. Simply
we will find out the class wise total of Fees Paid column.

NOTE:

1. When using GROUP BY clause we can include the group column


with the select statement.

2. GROUP BY clause can only be used if any aggregate function is being


used in select statement.

Table 1.1 : - STUDENT


SRNo Roll No Name Class Feespaid

5439 12105 Ajay 12 5000

6345 12110 Bharat 12 2000

3645 11230 Nitin 11 5000

7553 10323 Manisha 10 2000

2434 9134 Rajesh 11 5000

Example 1:-
Find the total of fees paid by each class from STUDENT Table given
above.
Answer:
SELECT SUM (FEESPAID), CLASS FROM STUDENTS GROUP BY CLASS;
Output :-
Feespaid Class

2000 10

10000 11

7000 12

XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 3


Example 2:-
Give the output of the following query.
SELECT CLASS, COUNT (FEESPAID), NAME FROM STUDENTS
GROUP BY CLASS;
Output :-
Class Count(feespaid) Name

Example 3:-
Find the total no. Of students of each class from STUDENT Table given
above.
SELECT COUNT (*), CLASS FROM STUDENTS
GROUP BY CLASS;
Output :-
Count(*) Class

1 10

2 11

2 12

Unsolved Question:-

1. Find the maximum fees paid by each class from STUDENT Table
given above.
2. Find the minimum fees paid by each class from STUDENT Table
given above.
3. Find the paid average fees of each class from STUDENT Table given
above.
Having Clause:- It is used to place the condition on groups of values of a
column. Having clause can include the aggregate functions. Whereas WHERE
clause is used to restrict in a query i.e. it is used to place the conditions on
individual rows.
XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 4
NOTE: HAVING clause can only be used if a GROUP BY clause is used.
Example:
(if we want to find out the classes for which total fees collection is more than
Rs. 10000.00)
SELECT SUM(FEESPAID), CLASS FROM STUDENTS
Group By Class
Having SUM(FEESPAID)>10000;

DISPLAYING DATA FROM MULTIPLE TABLES


 In real world the data of an organisation is kept in different tables based
on its nature (that is studied under data modelling). When the data is
scattered around many tables one may need to select the data for a
particular query from more than one table so that a single table result
can be generated.
 Data from multiple tables can be selected after joining the tables. SQL
SELECT statement is also used for combining data from more than one
table. When we combine the data from more than one table, this is
called joining of tables.
 JOIN: A join is a query that combines rows from two or more tables. In a
join query, more than one table is listed in FROM clause.
TABLE - STUDENT

SRNo Roll No Name Class Section AvgMarks

5439 12105 Ajay 12 A 83.66

6345 12110 Bharat 12 A 69.67

3645 11230 Nitin 11 B 84

7553 10323 Manisha 10 C 73

2434 9134 Rajesh 9 A

Marks Table
SRNo Maths Hindi English

5439 85 73 93

6345 77 65 67

3645 83 82 87

7553 69 66 84

3439 87 76 89

XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 5


Suppose we run following query on these tables:
SELECT Student.*, Marks.* From Student, Marks;

The result will be a single tabular structure that will contain all the columns
from both the tables and all the possible combination of records from both the
tables (This is the Cross Join or unrestricted join or Cartesian product of
tables).
QUALIFIED NAMES:
Qualified name are useful in indentifying a field if the two joining tables have
fields with same name.
<tablename>.<fieldname>
Select dept.dno, empl.dno from dept, empl;
TABLE ALIASES:- A table Alias is a temporary label given along with table name
in FROM clause. It is used to cut down on the amount of typing required in the
SQL queries.

CROSS JOIN OR CARTESIAN PRODUCT:- It is a very basic type of join that


simply matches each row from one table to every row from another table. It
returns multiplied rows and added columns of both tables which specified in
from clause.
But when a record of SR No 5439 (Ajay) from Students table is combined with a
record of SR No 7553 (i.e. Manisha in students table),it makes no sense. Hence
some extra condition with SELECT statement using where clause is specified:
SELECT Student.*, Marks.*

From Students, Marks

Where Students.SRNO = Marks.SRNo;

 Give the output of the above query.


This will give only meaningful combinations of records from both tables.
XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 6
Here we can easily understand that when multiple tables are joined they must
have some column common in them and in select clause we can put an
equality check with where clause to filter only a meaningful combination of
records, called EQUI JOIN.

NON EQUI JOIN:- A non equi join is a query that specifies some relationship
other than equality between the columns.
SELECT Student.*, Marks.*

From Students, Marks

Where avgmarks > English -------> (NON EQUI JOIN)

Give the output of the above query.

NATURAL JOIN:- A non equi join is a query that gives the result as equi join but
one of the identical columns get removed from output.
SELECT Student.*, Marks.* From Students natural join Marks;

Give the output of the above query.

JOINING MORE THAN ONE TABLES USING JOIN CLAUSE:


JOIN CLAUSE: It gives Cartesian product of 2 tables.
Example:- select * from student join marks;
NOTE:- With the help of JOIN clause equi and natural join can be also
performed by using ON and USING sub clause.
 Select * from student join marks on (student.srno = marks.srno)

Above mentioned query produces EQUI JOIN.

 Select * from student join marks using(srno);


Above mentioned query produces NATURAL JOIN.
NOTE:- Always remember that name of the columns must be same in both
table when want to perform NATURAL JOIN with JOIN clause by using
“USING” sub clause.
LEFT JOIN: It returns all the rows from the first table whether there are
matches in the second table or not. Unmatched rows of first table, NULL is
shown in columns of second table.
XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 7
TABLE – EMPL

TABLE – DEPT

Example :-
select dept.*, ename, mgr from dept left join empl on
dept.deptno = emp.deptno;
OUTPUT :-

XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 8


RIGHT JOIN: It returns all the rows from the second table whether there are
matches in the first table or not. Unmatched rows of first table, NULL is shown
in columns of second table.

Example :-
select dept.*, ename, mgr from dept right join empl on
dept.deptno = emp.deptno;

XII-IP-NOTES/GROUPING RECORDS AND TABLE JOIN 9


Assignments by:
AMIT PATHAK,PGT(IP)
LPS,RAE-BARELI
Chapter 15
Database Transaction

Q1. A database transaction is a ……………… that must succeed or fail in its entirety.

(a) Logical unit of work


(b) Physical unit of work
(c) Computer Program
(d) Log based file

Q2. A transaction is executed in

(a) Serially
(b) Concurrently
(c) Serially & concurrently both
(d) Randomly

Q3. Which is not a property of a transaction?

(a) Atomicity
(b) Consistency
(c) Integrity
(d) Durability

Q4. …………………. property ensure that either all operations of the transaction are
reflected properly in the database or none are.

(a) Atomicity
(b) Consistency
(c) Isolation
(d) Durability

Q5. This property implies that each transaction is unaware of other transaction
executing concurrently in the system.

(a) Atomicity
(b) Consistency
(c) Isolation
(d) Durability

Q6. Consistency implies that database was in.

(a) Consistent before the start.


(b) Consistent upon the termination
1
(c) (a) & (b) both
(d) None

Q7. Which property of transaction ensure that after the completion of a transaction the
change made by it to the database persist, even if the system failures.

(a) Atomicity
(b) Consistency
(c) Isolation
(d) Durability

Q8. Which command is used as beginning of transaction?

(a) BEGIN
(b) START
(c) START TRANSACTION
(d) (a) & (c) both

Q9. Which command is used for saving database changes in transaction?

(a) SAVE
(b) COMMIT
(c) SAVE TRANSACTION
(d) ROLLBACK

Q10. ……………… command is used for discarding database changes.

(a) UNDO
(b) REDO
(c) ROLLBACK
(d) SAVE POINT

Q11. The command is used to define breakpoints for the transaction to allow partial
rollback.

(a) BREAKPOINT
(b) SAVEPOINT
(c) AUTOCOMMIT
(d) (a) & (b) both

Q12. ............ is a point to transaction up till which all changes have been saved
permanently.

(a) Commit
(b) Savepoint
(c) Milestone
(d) Atomicity

2
Chapter 16
More on SQL -Grouping Records & Table Joins

Consider a relation/table EMP and give the correct answer of following queries.
Relation EMP
Empno Ename Job department Hiredate Sal Comm Sex Deptno
1 Pankaj Clerk Sales 10/01/97 15000 20000 M 20
2 Shalini Salesman Sales 24/03/98 25000 200 F 20
3 Sanjay Salesman Personal 12/12/96 23000 300 M 30
4 Sudha Manager Sales 01/07/99 45000 400 F 20
5 Rakesh Analyst Operational 05/09/97 55000 NULL M 10
6 Shakeel Clerk Operational 27/06/98 15000 300 M 10
7 Surya Manager Operational 25/02/97 45000 210 M 10
8 Shikha Analyst Personal 31/07/97 55000 Null F 30
9 Ramesh President Personal 12/03/97 70000 230 M 30

Q1. Which is true in respect of Select Statement?

(a) By Select we can retrieve all the rows from table.


(b) By Where clause with select we can retrieved selected rows from table.
(c) We can retrieve unique rows from table with the use of Distinct key word.
(d) All of the above.

Q2. The clause which is used to group rows based on distinct values that exist for
specified
column.
(a) Group by clause
(b) Having clause
(c) Order by Clause
(d) Where Clause

Q3. For conditionally retrieval of row from groups which clause is used?

(a) Where clause


(b) Having Clause
(c) Order By Clause
(d) (a) & (b) both

Q4. Group functions are also known as.

(a) Aggregate functions


(b) Multiple row functions
(c) Single row functions
(d) (a) & (b) both

3
Q5. Which option cause a group function to consider only distinct values.

(a) All
(b) Distinct
(c) Unique
(d) Diverse

Q6. Which option cause a group function to consider all values including all duplicated.

(a) All
(b) Distinct
(c) Unique
(d) Diverse

Q7. Which is not a group function?

(a) AVG
(b) COUNT
(c) MAX
(d) MOD

Consider a relation/table EMP and DEPT and give the correct answer of following queries.
Relation EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
Relation DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Q8. SELECT AVG(SAL) FROM EMP WHERE JOB = ‘CLERK’;

(a) 1037.5
(b) 2073.21
(c) 1040
(d) 2074

4
Q9. SELECT COUNT(*) FROM EMP WHERE DEPTNO = 10;

(a) 14
(b) 3
(c) 4
(d) 5

Q10. SELECT COUNT(DISTINCT JOB ) FROM EMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q11. SELECT COUNT(ALL JOB ) FROM EMP;

(a) 14
(b) 5
(c) 4
(d) 6

Q12. SELECT MAX(SAL) FROM EMP WHERE JOB = ‘MANAGER’;

(a) 2975
(b) 5000
(c) 3000
(d) 2850

Q13. SELECT MIN(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d) None

Q14. SELECT MAX(HIREDATE) FROM EMP;

(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d) None

Q15. SELECT SUM(COMM) FROM EMP;

(a) Null
(b) 0
(c) 2200
(d) 1400
5
Q16. Which statement is used to display the total no. of employees in each department?
(a) SELECT COUNT(*) FROM EMP WHERE DEPTNO;
(b) SELECT COUNT(*) FROM EMP GROUP BY DEPTNO;
(c) SELECT COUNT(DEPTNO) FROM EMP GROUP BY DEPTNO;
(d) (b) & (c) both

Q17. To display the jobs where the number of employees is less than 3.
(a) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*) < 3;
(b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*) < 3 GROUP BY JOB;
(c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE COUNT(*) < 3;
(d) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB HAVING COUNT (*) <
3;

Q18. Which join is used for display all possible concatenations are formed of all rows of
two or more tables.

(a) Unrestricted join


(b) Cartesian Join
(c) Equi Join
(d) (a) & (b) both

Q19. How many row are returned when we execute ‘SELECT * FROM EMP, DEPT’;

(a) 14
(b) 4
(c) 18
(d) 56

Q20. To display the name of employee & department name the MySQL statement used:

(a) SELECT ENAME, DNAME FROM EMP, DEPT;


(b) SELECT ENAME, DNAME FROM EMP, DEPT WHERE DEPTNO=DEPTNO;
(c) SELECT ENAME, DNAME FROM EMP, DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO;
(d) None of the above

Q21. The join where columns are compared for equality is called ………………

(a) Equi Join


(b) Natural Join
(c) Cross Join
(d) Right Join

Q22. The join in which only one identical column exists is called ………

(a) Equi Join


(b) Natural Join

6
(c) Cross Join
(d) Right Join

Q23. Which statement represent Cartesian join?

(a) SELECT * FROM EMP, DEPT;


(b) SELECT * FROM EMP JOIN DEPT;
(c) SELECT * FROM EMP CROSS JOIN DEPT;
(d) All of the above

Q24. Using sub-clause with JOIN causes a ……………… join whereas on sub-clause with
JOIN produces ………… join.

(a) Natural &Equi


(b) Equi& Natural
(c) Cross &Equi
(d) Natural & Cross.

Q25. Using …………. all rows from the first table will be returned whether there are
matches in the second table or not.

(a) LEFT JOIN


(b) RIGHT JOIN
(c) EQUI JOIN
(d) CROSS JOIN

Q26. Using …………. all rows from the second table will be returned whether there are
matches in the first table or not.

(a) LEFT JOIN


(b) RIGHT JOIN
(c) EQUI JOIN
(d) CROSS JOIN

Q27. To display the name of employees who are getting more salary than the maximum
salary of clerks.

(a) SELECT ENAME FROM EMP WHERE SAL >(SELECT MAX(SAL) FROM EMP
WHERE JOB=’CLERK’);
(b) SELECT ENAME , MAX(SAL) FROM EMP WHERE JOB=’CLERK’;
(c) SELECT ENAME FROM EMP WHERE SAL >MAX(SAL);
(d) NONE

Q28. Scalar functions are also known as :

(a) Single row function


(b) Multiple row functions

7
(c) Group functions
(d) None

Solved Questions(MULTIPLE CHOICE QUESTIONS)

EXERCISES

1. Which of the following will give the same answer irrespective of the NULL
values in the specified column:
a. MIN() b. MAX()
c. SUM() d. None of the above
2. An aggregate
function:
a. Takes a column name as its arguments
b. May take an expression as its argument
c. Both (a) and (b)

d. None of (a) and (b)

3. HAVING is used in conjunction with

a. WHERE b. GROUP BY clause

c. Aggregate functions d. None of the above

4. In the FROM clause of a SELECT statement

a. Multiple Column Names are specified.

b. Multiple table names are specified.

c. Multiple Column Names may be specified.

d. Multiple table names may be specified.

5.

5. JOIN in RDBMS refers to

a. Combination of multiple columns b. Combination of multiple rows

c. Combination of multiple tables d. Combination of multiple databases

6. Equi-join is formed by equating

8
a. Foreign key with Primary key b. Each row with all other rows

c. Primary key with Primary key d. Two tables

7. Referential integrity

a. Must be
aintaine
d

b. Cannot be maintained

c. Is automatically maintained by databases


d. Should not be maintained

8. A Primary key column

a. Can have NULL values b. Can have duplicate values

c. Both (a) and (b) d. Neither (a) nor (b)

9. Primary Key of a table can be

a. Defined at the time of table creation only.

b. Defined after table creation only.

c. Can be changed after table creation

d. Cannot be changed after table creation

9
VERY SHORT QUESTION ANSWER

1. Why is it not allowed to give String and Date type arguments for SUM() and AVG() functions?
Can we give these type of arguments for other functions?
Answer : String and dates are not real numbers that we calculate so sum or avg functions
are not valid for them.
2. What is default, Autocommit mode in
MySQL ? Answer : By default, Autocommit
mode is on in MySQL.
3. Can where be added a savepoint in a
transaction ? Answer : We can add a savepoint
anywhere in a transaction.

4. How are NULL values treated by aggregate functions?


Answer : : None of the aggregate functions takes NULL into consideration.
NULL is simply ignored by all the aggregate functions.

5. There is a column C1 in a table T1. The following two statements: SELECT


COUNT(*) FROM T1; and SELECT COUNT(C1) from T1; are giving different
outputs. What may be the possible reason?
Answer : There may be a null value.

6. What is the purpose of GROUP BY clause?


Answer : GROUP BY: GROUP BY clause is used in a SELECT statement in
conjunction with aggregate functions to group the result based on distinct values in a
column.
7. What is the difference between HAVING and WHERE clauses? Explain with the
help of an example.

Answer : WHERE Vs HAVING: WHERE is used to put a condition on individual row


of a table whereas HAVING is used to put condition on individual group formed by
GROUP BY clause in a SELECT statement.

8. What is a Foreign key? What is its importance?


Answer : Foreign Key: It is a column of a table which is the primary key of another table
in the same database. It is used to enforce referential integrity of the data.
9. What are constraints? Are constraints useful or are they hindrances to effective
management of databases?
Answer : These are the rules which are applied on the columns of tables to ensure data integrity and
consistency. These play very important role for tables so are not hindrances.
10
10. In a database there is a table Cabinet. The data entry operator is not able to put
NULL in a column of Cabinet? What may be the possible reason(s)?
Ansewr : Not NULL or Primary key constraints used.

11. In a database there is a table Cabinet. The data entry operator is not able to put
duplicate values in a column of Cabinet? What may be the possible reason(s)?
12. Ansewr : Primary key constraint used.

13. Do Primary Key column(s) of a table accept


NULL values? Answer :No.

14. There is a table T1 with combination of columns C1, C2, and C3 as its primary
key? Is it possible to enter:

a. NULL values in any of these columns?

b. Duplicate values in any of


these columns? Answer : No.
15. What are the differences between DELETE and DROP commands of SQL?
Answer : Delete is used for row removing while drop is used for removing complete table.
16. What are Aggregate Functions ?
Answer : A multiple row function works on multiple values. These functions are
called aggregate functions or group functions.

17. for what Data Types aggregate functions : MIN(), MAX(), and COUNT() work?
Answer : on any type of values - Numeric, Date, or String. AVG(), and SUM() work on
only Numeric values (INT and DECIMAL).

18. What is HAVING clause ?


Answer : HAVING clause is used in conjunction with GROUP BY clause in a SELECT
statement to put condition on groups.
19. What is Referential Integrity ?
Answer : The property of a relational database which ensures that no entry in a foreign key
column of a table can be made unless it matches a primary key value in the corresponding
column of the related table.
20. What is Union used for ?
Answer : Union is an operation of combining the output of two SELECT statements.

21. What is ALTER TABLE ?


Answer : ALTER TABLE command can be used to Add, Remove, and Modify columns
of a table. It can also be used to Add and Remove constraints.
22. What is DROP TABLE ?
11
Answer : DROP TABLE command is used to delete tables.
23. What function is used whenever a condition involves an aggregate function ?
Answer : whenever a condition involves an aggregate function, then we use HAVING
clause in conjunction with GROUP BY clause.
24. What is Difference between GROUP BY‟ and Having functions ?
Answer : WHERE function is used for individual records and HAVING for groups .
GROUP BY function is used for getting results based on some groups of data while a
condition on groups is applied by HAVING clause.

SHORT QUESTION & ANSWERS

25. Why are aggregate functions called so? Name some aggregate functions.
Answer : A multiple row function works on multiple values. These functions are called
aggregate functions or group functions. Some of the most frequently used. Aggregate
functions in MySQL are
: MIN(), MAX(), AVG(), SUM(), COUNT().

26. What is ALTER TABLE command ?Write all the commands that can be applied using alter
table.
Answer : A new column can be added to a table using ALTER TABLE command.
ALTER TABLE can be used:

• to add a constraint

• to remove a constraint

• to remove a column from a table

• to modify a table column

27. What is the Cartesian product of two table? Is it same as an Equi-join?


Answer : Cartesian Product (or Cross Join): Cartesian product of two tables is a table
obtained by pairing each row of one table with each row of the other. A cartesian product
of two tables contains all the columns of both the tables.
Equi-Join: An equi join of two tables is obtained by putting an equality condition on the
Cartesian product of two tables. This equality condition is put on the common column of
the tables. This common column is, generally, primary key of one table and foreign key
of the other.

12
LONG QUESTION-ANSWER

28. Name the Aggregate


Functions. Answer : These
functions are:

Name of the
S. No. Purpose
Function

Returns the MAXIMUM of the values under the specified


1 MAX()
column/expression.

Returns the MINIMUM of the values under the specified


2 MIN()
column/expression.

Returns the AVERAGE of the values under the specified


3 AVG()
column/expression.

Returns the SUM of the values under the specified


4 SUM()
column/expression.

Returns the COUNT of the number of values under the specified


5 COUNT()
column/expression.

29. What is Max Function ? Give few Examples.

Ans:- MAX() function is used to find the highest value of any column or any expression
based on a column. MAX() takes one argument which can be any column name or a
valid expression. involving a column name. e.g.,
To find the highest cost of any type of shoe in the factory.

SELECT MAX(cost) FROM shoes;

| MAX(cost) |
+-----------+
| 843.00 |
+-----------+

13
To find the highest cost of any shoe of type
'School'. SELECT MAX(cost) FROM shoes
WHERE type ='School';

+-----------+
| MAX(cost) |
+-----------+
| 320.75 |
+-----------+

To find the highest selling price of any type of shoe.


SELECT MAX(cost+cost*margin/ 100) FROM shoes;
+---------------------------+
| MAX(cost+cost*margin/100) |
+---------------------------+
| 828.517500000 |
+---------------------------+

To find the highest selling price of any type of shoe rounded to 2 decimal places.

SELECT ROUND(MAX(cost+cost*mar gin/100),2) AS "Max. SP" FROM shoes;


+---------+
| Max. SP |
+---------+
| 733.36 |
+---------+

To find the highest selling price of any type of shoe rounded to 2 decimal
places. SELECT ROUND(MAX(cost+cost*mar gin/100),2) AS "Max. SP"
FROM shoes;
+---------+
| Max. SP |
+---------+
| 733.36 |
+---------+

30. What is min() Function ? Give Some Examples.


Answer:- MIN() : MIN() function is used to find the lowest value of any column or an expression
based on a column. MIN() takes one argument which can be any column name or a valid expression
involving a column name. e.g.,
To find the lowest cost of any type of shoe in
the factory. SELECT MIN(cost) FROM

14
shoes;

+-----------+
| MIN(cost) |
+-----------+
| 843.00 |
+-----------+
To find the lowest cost of any shoe of type
'School'. SELECT MIN(cost) FROM shoes
WHERE type ='School';
+-----------+
| MIN(cost) |
+-----------+
| 320.75 |
+-----------+
To find the lowest selling price of any type of shoe rounded to 2 decimal
places. SELECT ROUND(MIN(cost+cost*mar gin/100),2) as "Min. SP"
FROM shoes;
+---------+
| Min. SP |
+---------+
| 135.15 |
+---------+

31. What is AVG() Function ? Give Some Examples.


Answer : AVG() function is used to find the average value of any column or an expression
based on a column. AVG() takes one argument which can be any column name or a valid
expression involving a column name. Here we have a limitation: the argument of AVG()
function can be of numeric (int/decimal) type only. Averages of String and Date type data
are not defined. E.g.,
To find the average margin from shoes table.
SELECT AVG(margin) FROM shoes;
+-------------+
| AVG(margin) |
+-------------+
| 2.600000 |
+-------------+
To find the average cost from the shoes
table. SELECT AVG(cost) FROM shoes;
+------------+
| AVG(cost) |

15
+------------+
| 491.750000 |
+------------+

To find the average quantity


in stock for the shoes of type
Sports.
SELECT AVG(qty) FROM shoes WHERE type ='Sports';
+----------+
| AVG(qty) |
+----------+
| 580.0000 |
+----------+
32. What is Sum() Function ? Give Some Examples.
Answer:- SUM() function is used to find the total value of any column or an expression
based on a column. SUM() also takes one argument which can be any column name or a
valid expression involving a column name. Like AVG(), the argument of SUM() function
can be of numeric (int/decimal) type only. Sums of String and Date type data are not
defined. e.g.,
To find the total quantity present
in the stock SELECT SUM(Qty)
FROM Shoes;
+----------+
| SUM(Qty) |
+----------+
| 10020 |
+----------+
To find the total order quantity
SELECT SUM(order_qty) FROM orders;
+----------------+
| SUM(order_qty) |
+----------------+
|2475 |
+----------------+
To find the the total value (Quanitity x Cost) of Shoes of type 'Office' present in the
inventory SELECT SUM(cost*qty) FROM shoes WHERE type = 'Office';
+---------------+
| SUM(cost*qty) |
+---------------+
| 772000.00 |
+---------------+
16
33. . What is COUNT() Function ? Give Some Examples.

COUNT() function is used to count the number of values in a column. COUNT() takes
one argument which can be any column name, an expression based on a column, or an
asterisk (*). When the argument is a column name or an expression based on a column,
COUNT() returns the number of non-NULL values in that column. If the argument is a *,
then COUNT() counts the total number of rows satisfying the condition, if any, in the
table. e.g.,
To count the total number of records in the
table Shoes. SELECT COUNT(*) FROM
shoes;
+----------+
| COUNT(*) |
+----------+
| 13 |
+----------+

To count the different types of shoes that the factory


produces SELECT COUNT(distinct type) FROM
shoes;
+----------------------+
| COUNT(distinct type) |
+----------------------+
| 3|
+----------------------+
To count the records for which the margin is greater
than 2.00 SELECT COUNT(margin) FROM shoes
WHERE margin > 2;
+---------------+
| COUNT(margin) |
+---------------+
| 5|
+---------------+

To count the number of customers in 'A' category

SELECT COUNT(*) FROM customers WHERE category ='A';


+----------+
| COUNT(*) |
+----------+
17
| 2|
+----------+
To count the number of orders of quantity more
than 300 SELECT COUNT(*) FROM orders
WHERE order_qty >300;
+----------+
| COUNT(*) |
+----------+
| 2|
+----------+
34. Does aggregate Functions consider Null values.Does NULLs play any role in
actual calculations ?
Answer : None of the aggregate functions takes NULL into consideration. NULL is
simply ignored by all the aggregate functions. For example, the statement:
SELECT COUNT(*) FROM shoes;
Produces the following output:
+----------+
| COUNT(*) |
+----------+
| 13 |
+----------+
Indicating that there are 13 records in the Shoes table. Whereas the
query: SELECT COUNT(margin) FROM shoes;
produces the output:
+---------------+
| COUNT(margin) |
+---------------+
| 10 |
+---------------+
This output indicates that there are 10 values in the margin column of Shoes table. This
means there are 3 (13-10) NULLs in the margin column.

This feature of aggregate functions ensures that NULLs don't play any role in actual
calculations. the following statement:
SELECT AVG(margin) FROM shoes;

35. What is „GROUP BY‟ ? Give Examples.


Answer: GROUP BY function is used for getting results based on some
groups of data. For example,

o The management of the shoe factory may want to know what is the total
quantity of shoes of various types. i.e., what is the total quantity of shoes of
type School, Office, and Sports each.

18
o The management may also want to know what is the maximum, minimum,
and average margin of each type of shoes.
o It may also be required to find the total number of customers in each category.

There are many such requirements. SQL provides GROUP BY clause to handle all such
requirements. For the above three situations, the statements with GROUP BY clause are
given below:
In the first situation we want MySQL to divide all the records of shoes table into different
groups based on their type (GROUP BY type) and for each group it should display the
type and the corresponding total quantity (SELECT type, SUM(qty)). So the complete
statement to do this is:
SELECT type, SUM(qty) FROM shoes GROUP
BY type; G1 and the corresponding output is:
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| Office | 1100 |
| School | 7180 |
| Sports | 1740 |
+--------+----------+
Similarly, for the second situation the statement is:
SELECT type, MIN(margin), MAX(margin), AVG(margin)
FROM shoes GROUP BY type; G2 and the corresponding output is:

+--------+-------------+-------------+-------------+
| type | MIN(margin) | MAX(margin) | AVG(margin) |
+--------+-------------+-------------+-------------+
| Office | 3.00 | 3.00 | 3.000000 |
| School | 2.00 | 2.00 | 2.000000 |
| Sports | 3.50 | 3.50 | 3.500000 |
+--------+-------------+-------------+-------------+
In the third situation we want MySQL to divide all the records of Customers table into
different groups based on the their Category (GROUP BY Category) and for each group
it should display the Category and the corresponding number of records (SELECT
Category, COUNT(*)). So the complete statement to do this is:

SELECT category, COUNT(*) FROM customers GROUP BY


category; G3
+----------+----------+
| category | COUNT(*) |
+----------+----------+
|A | 2|
|B | 2|
|C | 1|
+----------+----------+
19
Let us have some more examples. Consider the following
statement: SELECT cust_code, SUM(order_qty)
FROM orders GROUP BY cust_code;
This statement produces the following output. Try to explain this this output.
+-----------+----------------+
| cust_code | SUM(order_qty) |
+-----------+----------------+
| C001 | 1025 |
| C002 | 750 |
| C003 | 150 |
| C004 | 200 |
| C005 | 350 |
+-----------+----------------+
Do the same for the following statement also:
SELECT shoe_code, SUM(order_qty) FROM orders GROUP BY shoe_code;

+-----------+----------------+

| shoe_code | SUM(order_qty) |
+-----------+----------------+
| 1001 | 200 |
| 1002 | 200 |
| 1011 | 550 |
| 1012 | 250 |
| 1101 | 300 |
| 1102 | 350 |
| 1103 | 225 |
| 1201 | 200 |
| 1203 | 200 |
+-----------+----------------+
If you carefully observe these examples, you will find that GROUP BY is always used in
conjunction with some aggregate function(s). A SELECT command with GROUP BY
clause has a column name and one or more aggregate functions which are applied on that
column and grouping is also done on this column only.
36. What is Role of HAVING in SQL.Give Examples. How it is related with Group by ?

Answer:- Sometimes we do not want to see the whole output produced by a statement
with GROUP BY clause. We want to see the output only for those groups which satisfy
some condition. It means we want to put some condition on individual groups (and not on
individual records). A condition on groups is applied by HAVING clause. As an example
reconsider the

statement G1 discussed above. The statement produced three records in the output - one
for each group. Suppose, we are interested in viewing only those groups' output for
which the total quantity is more than 1500 (SUM(Qty) > 1500). As this condition is
20
applicable to groups and not to individual rows, we use HAVING clause as shown
below:
SELECT type, SUM(qty) FROM shoes GROUP BY type HAVING
SUM(qty) > 1500;

+--------+----------+
| type | SUM(qty) |
+--------+----------+
| School | 7180 |
| Sports | 1740 |
+--------+----------+

Now suppose for G2 we want the report only for those types for which the average
margin is more than 2. For this, following is the statement and the corresponding output:
SELECT type, SUM(qty) FROM shoes GROUP BY type HAVING
AVG(margin) >2;
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| Office | 1100 |
| Sports | 1740 |
+--------+----------+

In these statements if we try to put the condition using WHERE instead of HAVING, we
shall get an error. Another way of remembering this is that whenever a condition
involves an aggregate function, then we use HAVING clause in conjunction with
GROUP BY clause.

37. What Functions are used for conditions on individual records as well as on groups.
Give Examples.

Answer : Situations may also arise when we want to put the conditions on individual
records as well as on groups. In such situations we use both WHERE (for individual
records) and HAVING (for groups) clauses. This can be explained with the help of the
following examples:

a. The management of the shoe factory may want to know what is the total
quantity of shoes, of sizes other than 6, of various types. i.e., what is the
total
quantity of shoes (of sizes other than 6) of type School, Office, and Sports each.

21
Moreover, the report is required only for those groups for which the total
quantity is more than 1500.

i. The management may also want to know what is the maximum,


minimum, and average margin of each type of shoes. But in this reports
shoes of sizes 6 and 7 only should be included. Report is required only
for those groups for which the
minimum margin is more than 2.

The statements and their outputs corresponding to above requirements are


given below: SELECT type, SUM(qty) FROM shoes
WHERE size <> 6 Checks individual row
GROUP BY type HAVING sum (qty) > 1500; Checks individual group

+--------+----------+
| type | SUM(qty) |
+--------+----------+
| School | 3780 |
+--------+----------+
SELECT type, MIN(margin), MAX(margin), AVG(margin) FROM shoes

WHERE size in (6,7)

GROUP BY type having MIN(margin) > 2;

+--------+-------------+-------------+-------------+
| type | MIN(margin) | MAX(margin) | AVG(margin) |
+--------+-------------+-------------+-------------+
| Office | 3.00 | 3.00 | 3.000000 |
| Sports | 3.50 | 3.50 | 3.500000 |
+--------+-------------+-------------+-------------+

38. In a database there are two tables “ITEM” and “CUSTOMER” as shown below:

22
Write the command in SQL queries for the following:
(i) To display the details of Items whose Price is in the range of 40 and 95(Both values
included)
(ii) To display the CustomerName, City from table Customer and ItemName and
Price from table Item, with their corresponding matching ID.
(iii) To increase the price of all the products by 50.

39. In a database School there are two tables Employee and Dept as show below.

(i) Identify the foreign key in the table Employee.


(ii) What output, will you get, when an equi‐ join query is executed to get the NAME from
Employee Table and corresponding DNAME from Dept table?

23
40. In a database there are two tables: Table ITEM:

Table BRAND:

Write MySql queries for the following:


(i) To display ICode,IName and corresponding Brand of those Items, whose price is
between 20000 and 45000 (both values inclusive).
(ii) To display ICode, Price and BName of the item which has IName as “Television”?
(iii) To increase the price of all the Items by 15%.
41. In a database BANK, there are two tables with a sample data given below:

Note: - ENAME refers to Employee Name


‐ DNAME refers to Department Name
‐ DEPT refers to Department Code
‐ HOD refers to Employee number (ENO) of the Head of the Department.
Write SQL queries for the following:
(i) To display ENO, ENAME, SALARY and corresponding DNAME of all
the employees whose age is between 25 and 35 (both values inclusive).
(ii) To display DNAME and corresponding ENAME from the tables DEPARTMENT and
EMPLOYEE.
Hint: HOD of the DEPARTMENT table should be matched with ENO of the
EMPLOYEE table for getting the desired result.
(iii) To display ENAME, SALARY, ZONE and INCOME TAX (Note: Income Tax to be
calculated as 30% of salary) of all the employees with appropriate column headings.

24
42. In the Database –SAMS and VENDOR are two tables with the following information. Write
MySQL queries for (i) to (iii), based on the tables SAMS and VENDORS.

(i) To display ICode, IName and VName of all the Vendors, who manufacture “Refrigerator”
(ii) To display IName, ICode, VName and Price of all the products whose price is more than
20000
(iii) To display vendor names and names of all items manufactured by vendor whose code is
“P03”

25
Chapter 16
TABLES AND INTEGRITY CONSTRAINTS

INTEGRITY CONSTRAINTS
1. In MySQL CONSTRAINT is used to define rules to allow or restrict what values can
be stored in columns (fields). The purpose of inducing constraints is to enforce the
integrity of a database.

2. MySQL CONSTRAINTS can be classified into two types –


 Column Level Constraints
The column level constraints can apply only to one column. E.g. CHECK, NOT
NULL, UNIQUE.
 Table Level Constraints
The table level constraints are applied to the entire table.

Syntax :

CREATE TABLE [table name]


([column name] [data type]([size]) [column constraint],
[column name] [data type]([size]) [column constraint],
.
.
[table constraint] ( [column name1], [column name1]……)
);

Example:
CREATE TABLE book_details
(book_id varchar(15) Primary key,
book_name varchar(50) NOT NULL,
isbn_no varchar(15) UNIQUE,
cate_id varchar(8),
aut_id varchar(8),
pub_id varchar(8),
dt_of_pub date,
pub_lang varchar(15) CHECK(pub_lang IN(‘HINDI’,’ENG’)),
no_page decimal(5,0) CHECK(no_page>0),
book_price decimal(8,2),
);
3. MySQL CONSTRAINTs are :
a. PRIMARY KEY
 A PRIMARY KEY constraint for a table enforces the table to accept unique data and
NOT NULL for a specific column.
 It can be applied only once in a table.

Example 1: When table has single field primary key it can be defined at Column level.
CREATE TABLE author
(aut_id varchar(8) PRIMARY KEY,
aut_name varchar(50) NOT NULL,
country varchar(25) NOT NULL);

Example 2: when table has multiple field primary key(composite key)


CREATE TABLE author
(aut_name varchar(50) NOT NULL,
mobile_no int(10) NOT NULL,
country varchar(25) NOT NULL,
PRIMARY KEY(auth_name, mobile_no));

b. NOT NULL
NOT NULL constraint allows to specify that a column can not contain any NULL value
(cannot be left blank/entry in the field is must).

c. UNIQUE
 The UNIQUE constraint does not allow inserting a duplicate value in a column.
 More than one UNIQUE column may be defined in a table.

d. FOREIGN KEY
 A FOREIGN KEY in MySQL creates a link between two tables by one specific column
of both tables.
 The specified column in one table must be a PRIMARY KEY and referred by the
column of another table known as FOREIGN KEY.

Example 1:
CREATE TABLE book_master
( book_id varchar(15) PRIMARY KEY,
book_name varchar(50) UNIQUE,

Prepared by : ANSUMAN KHARE CLASS XII


L.P.S., JANKIPURAM Page 2
isbn_no varchar(15) UNIQUE,
cate_id varchar(8),
aut_id varchar(8),
pub_id varchar(8),
FOREIGNKEY(aut_id) REFERENCES author(aut_id));

e. DEFAULT
 In a MySQL table, while inserting data into a table, if no value is supplied to a
column, then the column gets the value set as DEFAULT.
f. CHECK
 Adding a CHECK CONSTRAINT on a column of a table, you can limit the range of
values allowed to be stored in that column.

Using IN operator
IN operator only accepts a value from a given list.
Using LIKE operator
LIKE operator allows entering a value matching with given
pattern.
Using AND(&) and OR operator
AND and OR operators allow us to join two or more conditions
and returns true or false.
Example :
CREATE TABLE author
(aut_id varchar(8) PRIMARYKEY,
aut_name varchar(50) NOT NULL,
country varchar(25) NOT NULL CHECK(country IN('USA','UK','India')),
home_city varchar(25) DEFAULT 'New Delhi',
Amt_paid decimal(7,2) CHECK(Amt_paid>5000 AND Amt_paid<50000),
DOB date NOT NULL CHECK(dojoin LIKE '_ _ - _ _ - _ _ _ _'),
CHECK(home_city = 'New Delhi' OR home_city='Mumbai')
);

Prepared by : ANSUMAN KHARE CLASS XII


L.P.S., JANKIPURAM Page 3
4. Alter table command
Sometimes we need to make changes in the definitions of existing
table, and then we use ALTER TABLE command.

ALTER TABLE command can be used many things, such as :


 Adding columns to the table
 Modifying column definitions of a table(changing data types of
existing fields of table)
 Deleting columns of a table
 Adding constraints to table
 Enabling/disabling constraints
 Deleting table from database

4.1. Adding columns to table


It is used to add a new field in an existing table.

ALTER TABLE empl ADD local_addr varchar(50) not null; //adds 1 field
ALTER TABLE empl ADD( city varchar(30) not null, inc_name varchar(20) ); // adds 2 fields

4.2. Modifying column definition with MODIFY and CHANGE


Using MODIFY clause we can only change data type or constraint of
column but not the name of column.
Example 1: change the size of field ename from 30 to 40 and
apply not null.
ALTER TABLE empl
MODIFY ename varchar(40) NOT NULL;

Using CHANGE/RENAME clause column name need to be written twice, it


can be used to rename column.
Example 2: change the size of ename from 30 to 40.
ALTER TABLE empl
CHANGE ename ename varchar(40) NOT NULL;
Example 3: change the size of ename from 30 to 40 and rename
ename to ename1.
ALTER TABLE empl
CHANGE ename ename1 varchar(40) NOT NULL;

Prepared by : ANSUMAN KHARE CLASS XII


L.P.S., JANKIPURAM Page 4
4.3. Deleting columns of table
DROP COLUMN clause is used to remove a field from table definition
along with its data.
ALTER TABLE empl
DROP COLUMN ename; // this will remove ename field from table empl
4.4. Adding constraints in table
ADD CONSTRAINT/ADD clause is used to add a constraint on
field/table.
Example 1:
ALTER TABLE empl
ADD PRIMARY KEY(EMPNO); // this will make EMPNO field primary key
Example 2:
ALTER TABLE empl
ADD CONSTRAINT pk1 PRIMARY KEY(EMPNO);
4.5. Removing constraints from table
DROP clause is used to remove a constraint from field/table.
Example 1:
ALTER TABLE empl
DROP PRIMARY KEY(EMPNO); // this will remove primary key from EMPNO field
Example 2:
ALTER TABLE empl
DROP PRIMARY KEY pk1; // this will remove primary key from EMPNO field

4.6. Enabling/Disabling constraints of table


In MySQL primary key cannot be disabled, but foreign key constraint
can be enabled or disabled.
Example 1: To disable foreign key
SET FOREIGN_KEY_CHECKS=0;

Example 2: To enable foreign key


SET FOREIGN_KEY_CHECKS=1;
4.7. Deleting table from database
DROP TABLE command is used for this purpose; it deletes table
structure as well as data both.
Example :
DROP TABLE empl;

Prepared by : ANSUMAN KHARE CLASS XII


L.P.S., JANKIPURAM Page 5
MySQL CREATE TABLE with CASCADE and RESTRICT

MySQL allows creating a table with CASCADE and RESTRICT options. CASCADE option
deletes or updates the row from the parent table (containing PRIMARY KEYs), and
automatically delete or update the matching rows in the child table (containing FOREIGN
KEYs).

RESTRICT option bars the removal (i.e. using delete) or modification (i.e. using an update)
of rows from the parent table.

Example
CREATE TABLE purchase
(invoice_no varchar(12) NOT NULL PRIMARYKEY,
invoice_dt date,
FOREIGNKEY(ord_no,book_id) REFERENCES
neworder(ord_no,book_id)
ON UPDATE CASCADE ON DELETE RESTRICT
);

Assignment
Very Short solved questions
Write SQL command for following:
1. To view the constraints of EMP table.
Ans. Show create table EMP;
2. To display the structure of table EMP.
Ans. Desc EMP;
3. To delete table emp_sal_detail
Ans. Drop table emp_sal_detail;
4. To delete a field contact2 from table EMP.
Ans. ALTER TABLE EMP DROP COLUMN CONTACT2;
5. To change size of field ENAME from varchar(10) to varchar(30).
Ans. ALTER TABLE EMP MODIFY ENAME VARCHAR(30);
6. Name the Integrity term that following constraint implement-
(A) NOT NULL (B) PRIMARY KEY (C) FOREIGN KEY
Ans. (A) NOT NULL implements Domain Integrity.
(B) PRIMARY KEY implements Entity Integrity.
(C) FOREIGN KEY implements Referential Integrity.

Prepared by : ANSUMAN KHARE CLASS XII


L.P.S., JANKIPURAM Page 6
Short questions
1. What do you mean by Integrity constraint?
2. Differentiate between PRIMARY KEY and FOREIGN KEY.
3. Differentiate between PRIMARY KEY and UNIQUE constraint.
4. Differentiate between PRIMARY KEY and NOT NULL constraint.
5. What do you call a multi-field PRIMARY KEY?
6. Differentiate between ALTER and DELETE commands in MySQL.
7. Differentiate between CASCADE and RESTRICT used in MySQL.
Long questions
1. Write a SQL statement to create a simple table countries including columns
country_id, country_name and region_id where entry in all fields is compulsory and
country_id should be unique and not null.
Ans. CREATE TABLE countries(
COUNTRY_ID varchar(2) primary key,
COUNTRY_NAME varchar(40) not null,
REGION_ID decimal(10,0) not null);
2. Write SQL commands to create given tables and also answer the given questions-
Table : TEST
TESTID TESTNAME COST
T101 Platelet count 200
T102 Hemoglobin 190
T301 Malaria 350
T502 Blood sugar 150
Table : PATIENT
PCODE NAME PHONE TDATE TESTID
i. 6425 THAKUR 9425695566 19-06-2016 T102
ii.7546 JAY 8885654566 18-07-2015 T101
iii.5789 BEERU 9415094150 20-09-2016 T102
iv.7766 KALIA 8111456365 31-01-2017 T502
v.7489 GABBAR 9839012546 12-02-2016 T301
vi.
i. Name primary key fields of both tables.
ii. Which one is foreign key in the given table?
iii. Write datatypes of COST and TDATE.
iv. What check can be applied on field COST?
v. What should be the size and type of PCODE and TESTID?
vi. Write SQL query to increase the COST of all tests by 50%.
vii. Write SQL query to display patient name got tested for “HEMOGLOBIN”.
viii. DELETE record of all patients got testes before year 2016.
Prepared by : ANSUMAN KHARE CLASS XII
L.P.S., JANKIPURAM Page 7