Академический Документы
Профессиональный Документы
Культура Документы
SESSION-2019-20
STUDY MATERIAL
FRAGMENT 1
CLASS-XII
CHAPTERS INCLUDED:
TEACHERS’ CONTRIBUTORS:
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.
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.
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.
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.
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.
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)
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.
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.
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.
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:
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.
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.
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
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.
AREA1 AREA2
AREA3 AREA4
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.
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.
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
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.
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.
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.
----------------------------------------------------------------------------------------------------
Que: Create the table ‘emp’ as the structure given below in the table:-
Ans:
create table emp
(
sno int primary key, name varchar(34),
address varchar(45), salary int, DOB date
);
Displaying selected columns: Suppose if you want to display only the name and
salary columns then the sql query will be as follows-
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.
We can done any simple calculation without selecting any database and table on
mySql prompt. Some of the examples are-
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.
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;
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.
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.
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.
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:
Note: In salary column there is no blank or NULL record has been extracted this time.
Note: ‘desc’ keyword is used after column name in order to arrange the records of name
column in descending order.
Note: When select command has been fired then no output has been extracted as all of the
record got deleted from emp table.
Before Using alter command the ‘desc’ command has shown the following
details of the table:
Q. Write a query to change column address data type from varchar to char.
Now observe the changes made on address data type. We had used ‘modify’ keyword while
changing the data type.
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.
Q. Write a query to shuffle salary column at the starting position of the table
‘emp’.
Constraint added
2) Numeric Functions
a) Mod(): It returns the remainder of one expression by dividing by another
number.
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.
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
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.
Q3. Which of the following functions returns the name of the weekday?
a) dayname() b)dayofweek() c)dayofyear() d)now()
Ans: a
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
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
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
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. 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.
(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.
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.
XII-IP-NOTES/DATABASE TRANSACTION 3
Notes by:
AMIT PATHAK,PGT(IP),
LPS,RAE-BARELI
CHAPTER NO. :- 15
CHAPTER NAME :- GROUPING RECORDS & TABLE JOINS.
Output :- Hindi
70
80
60
NOTE:
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
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;
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
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.
NON EQUI JOIN:- A non equi join is a query that specifies some relationship
other than equality between the columns.
SELECT Student.*, Marks.*
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;
TABLE – DEPT
Example :-
select dept.*, ename, mgr from dept left join empl on
dept.deptno = emp.deptno;
OUTPUT :-
Example :-
select dept.*, ename, mgr from dept right join empl on
dept.deptno = emp.deptno;
Q1. A database transaction is a ……………… that must succeed or fail in its entirety.
(a) Serially
(b) Concurrently
(c) Serially & concurrently both
(d) Randomly
(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
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
(a) BEGIN
(b) START
(c) START TRANSACTION
(d) (a) & (c) both
(a) SAVE
(b) COMMIT
(c) SAVE TRANSACTION
(d) ROLLBACK
(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
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?
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
(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
(a) 14
(b) 5
(c) 4
(d) 6
(a) 14
(b) 5
(c) 4
(d) 6
(a) 2975
(b) 5000
(c) 3000
(d) 2850
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d) None
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d) None
(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.
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:
Q21. The join where columns are compared for equality is called ………………
Q22. The join in which only one identical column exists is called ………
6
(c) Cross Join
(d) Right Join
Q24. Using sub-clause with JOIN causes a ……………… join whereas on sub-clause with
JOIN produces ………… join.
Q25. Using …………. all rows from the first table will be returned whether there are
matches in the second table or not.
Q26. Using …………. all rows from the second table will be returned whether there are
matches in the first table or not.
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
7
(c) Group functions
(d) None
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)
5.
8
a. Foreign key with Primary key b. Each row with all other rows
7. Referential integrity
a. Must be
aintaine
d
b. Cannot be maintained
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.
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.
14. There is a table T1 with combination of columns C1, C2, and C3 as its primary
key? Is it possible to enter:
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).
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
12
LONG QUESTION-ANSWER
Name of the
S. No. Purpose
Function
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.
| 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 rounded to 2 decimal places.
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 |
+---------+
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 |
+---------+
15
+------------+
| 491.750000 |
+------------+
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 |
+----------+
This feature of aggregate functions ensures that NULLs don't play any role in actual
calculations. the following statement:
SELECT AVG(margin) FROM shoes;
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:
+-----------+----------------+
| 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.
+--------+----------+
| type | SUM(qty) |
+--------+----------+
| School | 3780 |
+--------+----------+
SELECT type, MIN(margin), MAX(margin), AVG(margin) FROM shoes
+--------+-------------+-------------+-------------+
| 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.
23
40. In a database there are two tables: Table ITEM:
Table BRAND:
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.
Syntax :
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);
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,
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')
);
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
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.