44 INTRODUCTION
en we speak about an organization,
ee This data handling is performed
a large amount of data
n 's Tequired to be processed and
by arranging data in the form of tables and databases,
HI
quickly and ea;
‘labase objects. Database;
organization will be treated as the dat
ered as a repository of stored data,
vs the users to enter, access
"Container which may contain
il as shared. For
example, all files belonging to
‘abase of that organization. A database, therefore, is
Wewill now discuss some components like f
les, tables, records, fields,
base.
part ofa datal
etc, that are an important
lI <—— Application <——>
Fig. 8.1: Database and Database Management System sath
it Database is an organized collection of interrelated data that serves many applications, :
it to student
‘onsider the example of a “School” database. This database shall oe z
‘cher, result, etc, The data is arranged inside a database as per
shown in Fig. 8,2.
3 Database
—> Tebleffile — —
PalGharacter. —> Data-item/field —> Record
Fig. 8.2: File Organizationallest unit of file o
Cedar 1. Eight bits
>/ Data/character is th
“EB thetnay
a computer.
> Afield is a set of characters
It is also termed as 4 data ite!
wn as a field. 1
= Je, roll number, name, age and marks are the fields in a student's re
example, a
fe ec of fields is termed as a Record. For example, a student record
\ > Aco
which are used together to represent specifi
‘m. A specific or an individual data item with
fields Roll No, Name, Age and Marks as shown in Fig. 8.3.
RollNo. Name ‘
20 Sonia 14 90 ae
Data
Fig. 8.3: Student Table
[Link] of logically related records is called a file. A file is also termed as a tableor
a relation. A table has rows and columns, where rows represent records or tuples an
columns represent the attributes or fields. For example, the entire information aboutall
the students (in the form of records) in a class is kept in a file or table named “student
(Fig. 83).
Database is, therefore, a place where related information is stored and various operation
| can be performed on it. It is the highest unit of file organization
¥
Vv
Table 8.1: Use of Database in Real-life Applications
Eee Database to maintain data about
1. Banking . Customer information, Account details, Loan details, Transaction deaie@e)
2. Crop Loan . Kisan credit card data, Farmer's personal data, Land area and Cultivation #2
Loan history, Repayment data, etc.
3. Inventory Management 3. Product details, Customer information, Order details, Dever dat
4. ;
Organization Resource 4. Employee records, Salary details, Department information, Branch locations
vo
Management etc.
5. Online Shoppir sa
. 'e Shopping 5. Item description, User login details, User preference —
ese di
atabases are generally managed by a special software known as Database Manage!
System (DBMS).
8.2 DATABASE MANAGEMENT SYSTEM (DBMs)
Database Management Systems ar
Program, and store data in an o}
user to create,
€ specially-designed applications that connect tH ty
: ganized m; js to allow
Benbaley andl concola datahage ee oe °F DEMS sora is oaler
pas stores datain sucha manner that it becomes”
sien and highly efficient to Tetrieve, manipulate
roduce information. Thus, a DBMS is aus ian
ane gonic oF computerized record.
maintains the various pieces of j information Te mationvin an
rated and summarized form instead open
id Of kc epi
en in separate independent files, « Seplng
amples of Database Management Systems are
ys access, MySQL, PostgreSQL, SQLite, Microsoft
GaL Server Oracle, SAP, dBase, FoxPro, etc,
ew customized DBMSs are computerized library
gystems, automated teller” machines, — fight
reservation systems, computerized parts, inventory Fig. 8.4: Role of Database Management System
ystems, etc:
A DBMS gives us tools to:
> Store data in.a structured way.
Query the database (i.e., ask questions about the data).
Sort and manipulate the data in the database,
Validate the data entered and check for inconsistencies,
Produce flexible reports, both on screen and on paper, that make it easy to comprehend the
information stored in the database.
vvvvy
also, it maintains data consistency in the case of multiple users,
CTM:A DBMS is a general purpose software system that facilitates the pi
manipulating databases for various applications,
8.2.1 Need for DBMS
The database system is used to eliminate the problems of data redundancy and data
inconsistency. It does not maintain separate files for different applications, Rather, it works on
the centrally maintained database, which means that the data is kept at one place and alll the
applications that require the data may refer to t
database. Whenever any file gets updated,
the updated version of the file is available to all applications using the database system, as
shown in Fig. 8.5. So, data redundancy and data inconsistency are controlled to a large extent.
However, at times, there might be data redundancy due to some technical requirements in
business applications. In such cases, we are required to maintain same data for different files
but this is not recommended.
Need for DBMS go <
feases Competency
) Need
(Betintrnaton
Fig. 8.5: Purpose of a Centralized Database sane
a8.2.2 Components of a Database System
The various components of a database system are described in Fig. 8.6 below,
Database Applications
Database Management System
Fig. 8.6: Components of a Database System
Let us discuss these components.
1. Users: Users can be of varied types, usually a DB administrator, System or Application
developers and End-users. DBMS provides the following critical services to the user:
(a) Database Creation: A DBMS helps the user in creating and defining the required data
or, in turn, a database. It manages and organizes the required data and databases,
(b) Database Maintenance: It helps in maintenance of data and database by addition,
deletion, modification and regular updation of the tables and its records.
(c)_ Database Processing: A DBMS performs one of the major tasks of query processing—
it processes the queries or the information requirement of users and retrieves
necessary information from the database.
2. Database Application: Database application may be Personal, Departmental, Enterprise
and Internal. It may be general-purpose or customized as per the needs of a user
3. DBMS: Software thatallows users to define, create, access and manage database(s) isterm#!
as a DBMS. For example, MySQL, Oracle, etc.
4. Database: It is a collection of logical data.
8.2.3 Advantages of a DBMS
| advantages
Apart from providing various salient features described above, a DBMS has several
over traditional data processing techniques.
1. Elimination of Data Redundancy: Duplication of data leads to wastage in s
A DBMS eliminates data redundancy (duplication of data) by integrating the
multiple copies of the same data are not stored.
storage spa
files 0
—ta consistency: A DBMS provides data consiste;
isten
L e place are reflected
one P) at all other Places or to cy toa larger extent as the. changes mad
at
sharing of Data: By using a DBs all the users,
Y can existing ay
js , but new applicati » Not on}
gatabase PPlications can :
also be developed to op PPlications share data in the
erate against the same stored
y checks for th
e ;
the user in the correct format. It consists of varia information to be entered by
constraints,
3, Privacy and Security: Data security refers to
intentional disclosure to unauthorized persons.
js protected. ‘
ecu ol data against accidental or
ince there is centralized control, the data
mical: Combining :
eine 3 set poe all the organization's operational data int
creating a set of applications that work on this single soure of pada
szvings. The overall maintenance cost of data is reduced 4 al
9, Improved Backup and Recovery System: A data
Aas aceon
from hardware or software failures. pedi
{0. Meeting Enterprise Requirements than Individual Requirements: Since many types of
users with varying levels of technical knowledge use a database, a DBMS should provide
avariety of user interfaces.
CIM: The repetition (duplication) of same data at multiple places in a database is known 2s data
|
redundancy.
8.3 DBMS MODELS
Data models define how the logical structure of a dat
integrated collection of conceptual tools that can be uses
database along with the appropriate data types, relationship:
applied on the data.
abase is modelled. A data model is an
d to describe the structure of the
s and constraints required to be
on in a DBMS, They are a communication tool.
d how it is processed and stored inside the
data model should be able to give best data
Data models are used to implement abstracti
Data models define how data is connected an
‘ystem. They organize data for various users. A
following desirable characteristics:
diagrams and symbols.
no data redundancy.
2 Data representation in a data model should have
4 by various applications.
& Adata model should be made available and share
valid in all aspects.
4.
Data represented should be consistent, stable and8.3.1 Types of Data Models
Data models are categorized into three different categories:
_ DATAMODELS,
‘Object based Record-based Physical
> itd thodel data model data model
:
ent ody bude asnn
Hierarchical mode! Network model Relational model
(Tree structures) (irected graphs) (Files/Tables/Relations)
Fig.8.7: Classification of Data Models
[Link] Hierarchical Data Model
Ina hierarchical model, records are organized as trees rather than graphs, ie, hierg Rs
ical
represents a hierarchy of parent and child data segments. Itis represented by an upside. i =
Hierarchical model depicts one-to-many (1:M) relationships between a parent ac Child sep
Each parent can have many children, but vice versa does not hold true, ie, each child has Only one
parent.
STUDENT (Parent)
Rollnumber [Name [Address _ |
LIBRARY EXAM
(Child) (Child)
Roll [Ticket No. [Book issued Roll) First_term]Halt_yaly [Annual
number number
FEES [Roll Tuition_fee [Dev_fee peel
(Child) [number
Fig. 8.8: Hierarchical Model
From Fig. 8.8, we can see that the student d:
this kind of arrangement, a file higher in th
inside it. Here, Student is a parent of the
model represents a one-to-many relations|
a hierarchical (upside-down) tre
fatabase contains various files related to a student In
e hierarchy is known as parent of the files contained
Library, Fees and Exam files respectively. Thus, this
hip between a parent and its children in the formol
e. The advantages of this model are:
1. Itis simple in operation and in concept,
2. It promotes data sharing,
3. Parent-child relationship promotes data integrity,
7
It is efficient and can be naturally mapped for 1:M (one-to-many) relationships.
The limitations of this model are as follows:
; ; fica
1. Itis suitable for hierarchical relationships only; otherwise, itis inflexible for non-hierat™
relationship mapping,ae
pependency on parent node, which is the root node, and its deletion can cause deletion of
+ ui child nodes and, in turn, the entire model,
changes in the structure require changes in all the applications.
spa's IMS (Information Management System) ang
anagement system. system2000 are examples of hierarchical
tabase Mm: ‘
da
‘etwork Data Model
om
— unlike the hierarchical model, the network mi
: ‘odel provides the capabilit dl
many-to-many (M:M) relationships. Thus, a child ean have more than one aaa Loe
LIBRARY (Child)
Roll [Ticket No
number
STUDENT (Parent)
EXAM (Child)
Roll First_term] Half. [Annual
number es
FEES (Child)
Roll |Tuition_fee [Dev_fee | Total fees
number, se
: Network Model
From Fig. 8.9, it is cle:
observed that the file
r that this model represents many-to-many relationships. It can be
is associated with three tables, viz. LIBRARY, FEES and STUDENT.
Thus, the figure shows that a child can have more than one parent. This model is an improved
version of hierarchical model having records along with pointers. These pointers establish
many-to-many relationships and are termed as Links. Each record has its respective pointer
orlink with which it is associated
The advantages of network model are:
1. Itcan handle more relationship types, ie, M:M (many-to-many) multi-parent relationships.
2
3
4,
Data access is easy and more flexible.
|tincludes DDL (Data Definition Language) as well as DML (Data Manipulation Language).
It promotes better data integrity.
The limitations of this model are:
'\ The system is quite complicated in structure since there are several number of links which
also limits efficiency.
2
Structural changes require changes to be made in all application programs.
—3. A high-level language interface is required to interact with the
4, Extra memory is consumed for holding links (pointers).
UNIVAC's DMS 1100 and DBMS 10-20 from DEC are examples of network day
system.
[Link] Relational Data Model
The most popular data model in DBMS is the relational model. Itis a more sq
model than hierarchical or network model since there are no pointers iy
and in case of any fault or error these pointers may result in incon:
and can lead to reduced data integrity.
In this model, data is organized in two-dimensional tables called
relations are related to each other. A relational database
developed by E.R. Codd. In this type of database, the dai
Organized into tables, having logically related records cont:
of a table or relation can be permanently
has all the properties and capabilities req
sistency,
is based on this
ta and relations
ining the same fj
saved for future use. Thus, this mode) ete,
luired to process data with storage efficiengy
A elational model consists of a collection of tables, each of which is assigned a
te, itrepresents the database as a collection of relations or tables. Characteristics of.
database are: 7
1. Data is conceptually represented as an orderly arrangement of data into rows and,
termed as a relation.
2. Each relation is represented as a table.
Eh
Columns described in a table are the attributes th:
asa table.
at belong to an entity whichis:
4. Every row ina table repre:
5. All the values ina relation
and only one value.
sents a single entity.
are scalar, ie., at any given row or column position, theme
6. All operations are performed on the entire relation and the result is an entire relation:
Advantages of a relational model are as follows:
1. A relational model provides structural indeper
ndence by using independent tables
Changes made
in the table structure do not affect the data access or other application pRs==
Itis represented in the form of tables; So, it is simple and easier to understand
Tabular view also provides easier database design, use, implementation and manage
Built-in query support based on SQL. is Provided by RDBMS (Relational Database!
System).
ye wn
and faster. peels
lgning and processing capabilities of RDBMS isolate igi
Data organization and manipulation is easy, flexible
Powerful structure desi
from physical-
8
The limitations of relational model are:
1. RDBMS incurs hardware and system software overheads.
2. The size of database becomes very large.{ONAL DATABASE
| database is a type of database that stores and
des access £0 data points that are related to one another.
“| databases are based on the relational model, an
neat
yationa!
ov
festion
saves straightforward way of representing data in tables, In
it ional database, each row in the table is a record with a
slat called the key. The columns ofthe table hold attributes
wnt data and each record usually has a value for each attribute,
en it easy to establish the relationships among data points.
ften, data in
_ Terminologies related to a Relational Database:
relational database is organized into tables.
Basi
1, Entity: An entity is something that exists and about which we can store some information. i
itis an object which can be distinctly identified. For example, student entity, employee
sntty, item entity, etc. Entity becomes the name of the table,
Attribute: In a relational table, an attribute is a set of values ofa particular type. The term attribute
icalso used to represent a column. A table consists of several records (row); each record ean be
veral smaller entities known as fields or attributes or columns. A set of attributes
teristics or properties of an entity. In the given table, Student relation
‘our fields or attributes—Roll number, Name, Address and Gender.
nas tuple, It is also called a row/record. A single entry
broken into se’
defines the charac
(Fig. 8.11) consists of f
3, Tuple: Each row ina table is know
in s table is called a record or row. A record in a table represents a set of related data:
For example, the Student table given below has 10 records.
Each tuple (row) in a relation (table) corresponds to data of areal world entity (for example,
Student, Employee and Attendance)
4, Cardinality of Relation: It is the number of records or tuples in the relation. Thus, the
cardinality of Student relation is 10.
known as degree ofa relation. Thus,
Degree of Relation: Number of columns or attribute
ation is 4.
the degree of Student
& Domain of Relation: It defines the kind of data represented byte aes taaga stoke
al possible values that an atribute may contain, For example ie Gives as SU
domain for the field Gender is two since fé ean have exter MAE Iain possible and
avallabl
vailable values that it may contain.
Body of the Relation: It consists of an unordered set of 0 or more tuples.
A fa
[-\
Actributes, By) |e
Primary key —
eee eas
rae
serie rama | RNA
Zh
S| reas [Fae
a4 10 TAkanksha Tiwari Ashok-Vihar
‘degree
. Fig. 8.11: R
padres ‘| Gender
2| =| >|
Cardinality
if
lational Model (Student Relation)a ference to Hig O11, in the given Mtudent relation; ‘
open nane (ie, cardinality=10) and 4 attributes (Le, degregsay,
* Roll number, Name, Address and Gender are the attribute names,
+ The first tuple containg the values (1, “Hinku Sharma’Vilak Nagar'yny),
+ The domain of the attribute Gender ts (M,F),
> Keys are @ very Important part of relational database, ‘They allow us to MMentity an 9
OFA Not oF attributes on the basis of which a table Is identified, They are sa
entity relation among two or more tables, They also ensure that each ve, ing
\dontitied by a combination of one or more folds within a table,
The different types of ke
Primary Koy
follow:
tribute or a group of attributes 1
hat can uniquely: "Geni ups ig
“apable of becoming the primary key es Candidateforpimyy
Candidate A candidate key is one that is
Key key position),
Alternate Key A candidate key that is not the primary key is called an alternate key,
Forelgn Key A non-key attribute whose value is derived from the primary key of some other table jg
known as. foreign key in its current table,
Let us discus:
1
these keys in detail
Primary Key: A primary key i
Identifies a tuple/row in a table. The salient featur 5
(a) Itis always unique in nature, ie,
a relation,
et of one or more
'ttributes/fields which uniquly
of a primary key are as follows:
non-redundant. It does not have duplicate valuesin
(b)
NCarranges the table in its own order
(©) Ieeannot be re-declared or left null
(d)_ One table can have only one primary key; however, primary key can be a combination
Cxample, roll_number along with admission_no can Be
and can be declare, mary key in the relation Student. In
Item given be! Primary key while Supp_id (supplier id)is
the primary ke
of more than one field. For
combined together
the table
dasap
low, Item id is the
yin the table Supplier,
‘Table: Item
CI Peles
no} oma a
02 sor Ashok-Vihar
200 $02 Noida
N04 150 a
105, 300
N03
Punjabi Bagh
S04
S05
rceeall
[candidate Keys |
“| [terate Ker
a
fescaveala didate key refers to all th il ;
ey: A candid : all the attributes in a relation
conti ble of becoming a primary key. We mark it virte =
: /.
orate" n item table, Itemid and Item name are the candidate
inte Fie primary key and Item_name becomes the alternate
ire er relation, Supp_id and Area are the candidate keys,
a plapecomes the alternate key. Thus, the equation becon
f
4
Supp id is the
ecomes;
Candidate Keys - Primary Key = Alternate Key
. didate key that is not the pri '
ate Key! A canc Primary key is called an alternate.
ers, any attribute that is a candidate for the primary key, Le, which copie
coming a primary Key but is not a primary key, is an alternate key. For example, in
Peso? table, cust_name is the alternate key. Similarly, in the given table Item, Item
2 ne becomes the alternate key.
1a
an Key: A foreign key is a non-key attribute whose value is derived from the primary
en fanother table; in other words, a primary key in some other table having relationship
key :
wp the current or original table.
wi
Foreign Key
Table: Employee Table: Department
Ey ‘Ankur Mehta = Mgr Mar Manager
£02 Deepika Gupta Dir Dir Director
E04 Amav Bansal Asst_mgr Acc Accountant
£03 Harshit Singh ‘Acc Asst_mgr Assistant Manager
505 Kirti Dubey Mgr
Inthe above table, Desig_code is the primary key in the table Department which, when
related with the table Employee, becomes a foreign key to it.
Thiswas all about the database concepts. Now, we will be moving on to their implementation,
Using SQL.
46 INTRODUCTION TO SaL
cattanagement Systems (DBMS) are not a
9 Ait were first implemented in the
alot while aa database technologies evolved
al and expected functionalities of
opin immensely. These days, there cae
recon, i pn which does not manage its data _y,jephone Directory
“ephone USiB Some type of DBMS. An online
a, uses DBMS to store data
‘ Dye
mat ie oPle, phone numbers and other AN ste
i ;
aie sia, Apart from this, your electricity
naa fetes # DBMS to manage billing
" Stes, to handle fault data, etc, not
Mie pet Pac
it fy, ace
Tieng COk—it needs to store, manipulate and oe ee
sand a 2
data related to its members,
Membe 7
mber activities, messages, advertisementsAll these real
DBMS requires
Query Language
ire a DBMS to manipulate and handle this enormous
vpandle and manipulate its data, which is known ag ¢'9 a,
eals exclusively with relational Aatabases tt
» hej
life applications re
ome language to ha oy
(SQL). The following topic
tables and retrieving data using SQL
8.7 OVERVIEW OF SQL AND MySQL
SQL (Structured
fe accessing and
create,
Ratna Datisne Management Stems and ar aso used
to create interface between a user and database. By using SQI
commands, one can search for any data in the database and
perform other functions like creating tables, adding records, ———— =
modifying data, removing rows, dropping tables, etc. ig. 8.13: re Query Language
Query Language) is a standard language
manipulating databases. SQL commands
transform and retrieve information from
a
MySQL is an open-source and freely-available Relational Database
Management System (RDBMS) that uses Structured
Query
Language (SQL). It provides excellent features for creating,
storing
MySQL maintaining and accessing data, stored in the form of databases
and their respective tables. A single MySQL database can store
several tables at a time and can store thousands of records init,
Being an open-source software, it can be freely and easily downloaded from the site
“wrwmysglors, MySQL is developed and supported by Sweden-based company, MySQL AR
{tis fully secured, reliable and fast, and possesses far better functionalities than many other
commercial RDBMSs available in the market.
8.8 FEATURES OF SQL
SQL is the most common language used to create, 0
with a database.
In 1970, SQL was developed by Donald D. Ch
is a fourth generation non-procedural |
the databases (relations). In other words, these |
inserted and updated or deleted from a datab.
Ithas the following salient features and stron,
CCTM: SQL (Structured Query La
perate, update, manipulate and communicate
hamberlin and Raymond F. Boyce at IBM. Thus, Sh
‘anguage that is used to create, manipulate and process
languages describe what data is to be retrieved,
ase.
8 processing capabilities
It can retrieve data from a database through Query processing,
Tecan insert records in a database.
{can update records in a database.
can create new databases
and modify the existing o1
nes.
It can create new tables ina :
database,
It can create views in a database,
It allows modifying the Security Settings of the system.
n9uage) is a unified,
ling and managing data in relational database:
non-procedural language used for
S.3 :
sowing advantages ”
, It is very easy to learn ;
ib work upon it.
e of databases can be handled q,
i
, yolum
aa quired: Itis non-procedural anda
'; to accomplish a task but only need
pe linked to most of the other high-level
base programmers.
sItis compatible with other database
his SQL Server, Oracle, Sybase, etc,
32
D isnot @ case-sensitive language, i.e,, both cap
_ 3d
cuAssiFICATION OF SQL STATEMENTS
ql
“sc the language used to interact with the database. The $0
M ethe statements that are regarded as the ins
ve rovides different types of statements or commands
e sents aFe classified into the following categories:
SQL statements
Data Definition Data Manipulation Data Control
Language (DDL) Language (DML) Language (DCL)
Fig. 8.14: Classification of SQL Statements
Diband TCL are beyond the scope of this book. So, we shall be dis
commands in detail.
410.1 Data D ommands
TieDDL part of SQL permits database tables to be created or deleted. It also
(it), specifies links between tables and imposes constraints on tables: [Econ
‘ements for creating, manipulating, altering and deleting the table.
sat
DROPaa
» USE command: to select and open an already existing database.
Examples of DDL commands in SQL are:
> CREATE DATABASE: creates a new database.
> CREATE TABLE: creates a new table in an existing database.
» ALTER TABLE: modifies the structure of a table.
> DROP TABLE: deletes a table.
CCTM: The DDL command lets us define the database structure and its related operations, Ra
The DDL provides a set of definitions to specify the storage structure and access iene
by the database system and also defines proper and relevant data types, oe
8.10.2 Data Manipulation Language (DML) Commands
A Data Manipulation Language (DML) is a part of SQL that helps a user access or manipulate
data. The DML statements are executed in the form of queries which are handled by the DML
compiler. It contains the set of statements to:
1. Retrieve data from the tables of the database.
2. Insert data into the tables of the database.
3. Delete data from the tables of the database.
4. Update data among the rows/records in the tables of the database.
DML commands carry out query-processing operations and manipulate data in the database
objects. Several DML commands available are:
1. SELECT statement: To extract information from the
table; may or may not be on the basis of certain
conditions/criteria.
2. INSERT INTO statement: To insert new data
(record) into a table.
Learning Tip: The query and update
commands form the DML part of SQL.
They enable the user to access or
manipulate data stored in a database.
3. UPDATE statement: To modify or change the data (tuple) in a table (not modifying the
data type of column).
4. DELETE: To delete data (tuple) from a table (not deleting a column).
Table 8.2: Difference between DDL and DML commands.
a
1. DDL stands for Data Definition Language. 1. DML stands for Data Manipulation Language.
2. These commands allow us to perform tasks 2. These commands are used to manipulate data, ie,
related to data definition, ie, related to the records or rows in a table or relation.
structure of the database objects (relations/
databases).
3. The examples of DDL commands are Create, 3, The examples of DML commands are Insert into,
Alter, Drop, Grant, Revoke, etc. Update, Delete, Select, etc.
4, DDLis not further classified. 4, DML commands are further classified into two
types:
(a) Procedural DMLs
(b) Non-Procedural DMLset implementing SQL using Mysqi, 28 the plat
rm,
ca
it mst nd free!
on-source and freely avail;
ueoren eaten ik aa cea Relational Data
we" structured “anguage (SQL). It pry), ‘ase Mana,
se -cessing ‘i ide: igement
jf Beg and accessing data, stored in the form Of lent Features “stem (RDBMS)
ysl database can store several} tables at a tj ‘atabases and their
ge MY" ‘ime
wit
ad
ait
n
eis
wit
wo2 and 5
iy secu Possesses fa,
is ful | RDBMS available in the market,
open-source software, it can be f
org: MySQL is developed and suppo
ured, reliable, and fast,
onmercial
aaguaatabase system works upon Client/Server architecture
4 constit
ich runs on machine containing the databases and MySQL datab;
ie latabase:
nected to these Server machines over a network
+ Advantages of MySQL: MySQL.
tutes a MySQL server
s (clients), which are
1, Reliability and Performance: MysQl. is a ver
2, Modifiable: Being an open-source software, M
SQL comes with its source code; so, it
is easily modifiable and we c
‘an recompile its associated source code.
3, Multi-Platform Support: My:
‘SQL supports several different platforms like UNIX,
Linux, Mac OS
X and Microsoft Windows,
Powerful Processing Capabilities: MySQL is a powerful, easy, compatible and fast
Relational Database Management System. It can handle complicated corporate
applications and processing requirements.
Integrity (Checks): MySQL provides various integrity checks in order to restrict the
user input and processing,
6. Authorization:
authorization by restricting access to relations and views.
Powerful Language: All SQL operations are perfor med at a prescribed and ciation
ie, one SELECT command can retrieve data from multiple rows and one :
ata time. These features make SQL a very powerful
: command can process only a
lySQL provides DDL commands to check for user authentication and
Command can edit multiple rows
language as compared to other langu
Single record at a time.
ages where one
et of c that provides the
8 Reliable: SQ1 provides a high level of well-defined set of commands that p!
desirable results without any ambiguity.
Freedom of Data Abs QL provid
©ompared to any other procedural language: oa
Complete Language for a Database: Apart fom a
Tanguage, it can also be used to create, insert: d6
‘atabases, f
‘ Jesa greater degree of abstraction freedom
a strong query processing
l 'd control access to data in
Fy
&
Hy
FS
|
8
CornYou can download and install it gj
rt working with MySQL by followin, rect)
the given Me
MysQl Server
|__, mysaL Command Line Client
indows 7 and above) |
|
|
Alternatively, (for Wi
start > Apps by name
_y MySQL Command Line Client
eee
msn cne rine Cees
feted ee eatretald $a
ao
ee
a
ee
Satie
ee
| Crete
®
to Start MySQL
Fig. 8.16: Step:
here you need !9
After opening MySQL, the screen of the MySQL command prompt appears W
specify a password to work with it
ing the SQ
After entering the password, the MySQL prompt appears, where you start EYP! oa
commands, as shown in Fig. 8.17. In order to come out of MySQL application, you can
quit in front of the mysql> command prompt, as shown in Fig. 8.18
‘Progiam Files G@6)\MySQL\MySQL Server 5.1\bin\mysqlexe
Fig. 8.17: MySQL Prompta
positive whole numbers up to 11 digits
INTEGER or
integer umbers up to 10 digits The renge of mntegeris
=e SMALLINT
NUMERIC(x.y) stored in the given format, where xis the total number
‘the number of places to the right of the decimal,
places
bilace for the decimal point Numeric holds up to 20 significant igies.
tive number holds one place for the san. te. (>)DECIMAL,
CHARACTER
(fixed length)
CHARACTER
(variable length)
DATE
TIME
BOOLEAN (logical)
BLOB/RAW/ LONG
RAW
MEMO/LONG
DECIMAL(x,y)
or
DECIMAL(size,
precision)
decimal point
CHAR(x)
or
CHAR(size)
VARCHAR(x)
or
VARCHAR2(x)
DATE
TIME
BOOLEAN
BLOB
or RAW
or
LONG RAW
MEMO
or LONG
e DECIMAL format, wl we
i y is precision, Le, it Tine te tl ay
the right of the decimal point. Shaye
Forexample, Decimal(8,2)
,, decimal data type stores
ae reas var and aight ater tia dere that hay
Decimal holds up to 19 significant digits. A negative
one place for its sign (-) number,
6 digits 1 2
ses
B digits
This data type stores’x’ number of characters in the
afixed ferta maximum of 254 characters, can bestia
Ifyou store strings that are not as long as the size’ or x
value,the remaining spaces are left unused. For example, if you specg
CHAR(10), strings such as “ram” and “technology” are each stored
10 characters. However, a student admission_no is 6 digits long ing
school, s0 CHAR(6) would be appropriate to store the admission ,
of all the students. This data type is suitable where the number of
characters to store is fixed. The value for CHAR data type has to be
enclosed in single or double quotation marks. :
This data type is used to store variable length alphanumeric data
For example, address of a student can be declared as VE
to store the address up to 25 characters long. The advantage of
Using this data type is that VARCHAR will not leave unused spaces
It releases the unused memory spaces. The value for VARCHAR data
type has to be enclosed in single or double quotation marks.
This data type is used to store a date in ‘yyyy/mm/dd format Itstores
year, month and date values. DATE values can be compared with each
other only. The date values to be entered are to be enclosed in {Jor
with single quotation marks.
This data type is used to store time in hh:mm:ss format. Itstoreshour
minute and second values. For example, a time of day can betakenas
[Link]p.m. where 12 means hours, 30 means minutes and 45 refers
to seconds.
This data type is used for storing logical values, either true orf:
In both upper and lower case, T or Y stands for logical true and For
N stands for logical false. The fields with Boolean (logical) data P=
can be compared only with other logical columns or: a
This data type can store data up to a maximum length of 65535
characters. BLOBS are “Binary Large Objects” and used to store?
amount of data such as images, animations, clips ‘or other type
files, For example, image raw(2000);
This data type allows storing characters or remarks upto 2
record,Sa
e ‘able 8.3: Difference between CHAR and VARCHAR datatype
eri
; TET
provides fied length memory 1. VARCHA\ alc
cq data 1¥Pe Raa se
i on sinspecifesa fixed length characterstring. memory stor a
; string (changeable),
f ar data tYPE can store amaximum of 0to 2, The VARCHAR data He a
1 arate: aimee : number up to 65,535,
riarypetsusedwmen the data entries na 3, VARCHAR data
3 we ae expected to be ofthe same size, inacamn ar
ake x characters of storage even if 4.
will t
x characters to that column.
RD
4 one! Jess than
is shorter than its length x,then 5.
entered is
; ae added.
‘ cuardata type takes memory space of 1 byte per 6. VARCHAR takes up memo
ee per character, +2 bytes to hold
information.
7. search operation is faster with CHAR data type 7. Search of i :
eu type columnas com
1 Forexample,name char(10);
name="anu";
same field occupies 10 bytes, withthe first three then name occupies only 342s
bytes with values and the rest with blank data, three bytes for value and the oth
variable length information.
columns or attributes in a relation, two points should be ke
umber area code, use character d
ddress, designation, use varchard
CINeWhile defining data type for
1, When using fixed length data in columns like phone n
2. When using variable length data in columns like name, a
8.13 SQL COMMANDS
SQL provides a predefined set of c
Before discussing these commands,
terminologies related to SQL. Throughout this chapter,
have been used.
we refers to an individual SQL element that has a special ‘meaning in SQL, Fore
bagn ‘Tand FROM are keywords. A clause is a distinct logical part ofan a ss
thane a keyword for which they are named and consist of arguments as °
anny empno, ename FROM employee WHERE salary>45000, are clauses in
ments complete or modify the meaning of a clause, whlel Is salary in the
1 more clauses. Statements
any task. For exal mple, S
member here is that all the stat
ase sensitive: we:
-ommands that help us to work with relational
we must be familiar with the conventions
the words keyword, clause and sti
A
con or command is a combination of two 0!
moyen, aes given to SQL database for executing
180 term ‘an SQL statement. An important point to rel
cee with a semi-colon (;) Also, SQuits mung
in either upper case or lower case.Let us now learn how a database and tables in a database are created in SQL. A data,
used to house data in the form of tables. Therefore, before creating a table, it is mandatory ‘
to
Database: School
[ese
create a database first.
We shall create a sample database School and then create a table Student in it.
Student
Fees
Table: Student Table: Fees
1 Raj Kumar M 93 17-Nov-2000 1. Raj Kumar 8000
Zz Deep Singh M 98 22-Aug-1996 2. Deep Singh 9000
3; Ankit Sharma M 76 02-Feb-2000 = Payal Goel 7500
4 Radhika Gupta F 78 03-Dec-1999 6. Diksha Sharma 8000
= Payal Goel * 82 21-April-1998 Ls Shreya Anand 8020
6 Diksha Sharma F 80 17-Dec-1999 10. Prateek Mittal 9200
7 Gurpreet Kaur F 65 04-Jan-2000
8 Akshay Dureja M 90 05-May-1997
9 Shreya Anand F 70 08-Oct-1999
10 Prateek Mittal M 75 25-Dec-2000
To get started on our own database, we can first check which databases currently exist in MySQL
server. Use the SHOW DATABASES statement to find out which databases currently exist by default
on the server:
mysql> SHOW DATABA
+
+
|Database |
2 rows in set (0.01 sec)
1. Creating Databases
‘The CREATE DATABASE command i
Syntax for creating a database:
CREATE DATABASE
;
For example,
s used to create a database in RDBMS.
School.
<__— Creates database with the name _
me school will PP
gets executed, a database with the nal
mysql> CREATE DATABASE School;
When the above-mentioned command
created on the system.pases
g Data
n8
sw ‘ab has been created, we need to open it to work
Ca pening 4 database:
a peabase name>;
amples
wai o
ase changed
sp school;
patab
oving Databases
cally’ remove/delete a database along with all its tab
removing @ database:
Mm jpoP DATABASE ;
forexample,
mysql> DROP DATABASE School;
Database deleted
4,creating a Table
theCREATE TABLE statement is used to create a table ina databa
‘ovsand columns, and each table must have a name. It is the most
Atable must have at least one column.
Syntax for creating a table:
CREATE TABLE
(
[(size)],
[(size)],
[(size)].
i
forecample,
ra CREATE TABLE Student
Rollno integer NOT NULL PRIMARY
= varchar (20) NOTNULby
se char (1),
Marks
integer (11)
Ee date );
Query, i
to, Pras OK, O rows affected (0.04 sec)
thew, ana
a name and a data type must be
the
Ke ‘able definition column definitions ae EPH
te send ifference in column names: the only
ng comparisons.5. Viewing a Table
‘To verify that the table has been created in the database, SHOW TABLES command jg Used,
mysql> SHOW TABLES;
+
2 rows in set (0.01 sec)
6. Viewing a Table Structure
To view a table structure, DESCRIBE or DESC command is used. It shows the structure of
table along with the name of the columns, data type of the columns and constraints a
the columns.
Syntax: DESCRIBE ; or DESC ;
PPlied oy
For example,
mysql> DE: Student;
-
| Field | Type | Null [Key |Default | Extra |
|RollIno | integer(11) | YES | | NULL i |
| Name |varchar(20) | YES | | NULL | I
|Gender | char(1) | YES | | NULL | I
|Marks | number(11)_| YES | | NULL | I
| DOB | date | YES | | NULL 1 |
~ +
5 rows in set (0.02 sec)
7. Inserting Data into a Table
The INSERT INTO command is used to insert a new record/row/tuple in a table.
Itis possible to write the INSERT INTO statement in the following different forms:
(a) Inserting data (for all the columns) into a table: In the first method, it does not specify
the column names where the data will be inserted, only their values.
Syntax for SQL INSERT is:
INSERT INTO VALUES (value1, value2, value3...);
For example, mysql> INS
RT INTO Student VALU
19
5 (1,"Raj Kumar", "M's 93i ,, if we are addin,
Pe ceva TOW we a 8 Value for al]
woile inl column(s) name in the SQL que
columns =
TY. But We need tg pn te table, We need not
«peel ggisinthe same order as the colum
make sure
NS represented j that the order of
eM ng points should be kept in mind while inserting qos st Uc ofthe tabi
plowine inputted 8 data in a relation ms
. when values are inputte using INSERT | :
; INTO command, it;
insert since it adds one tuple ata time into the er itis termed as single row
The INTO clause specifies the target table and the VAI :
tobe added to the new record ofthe table, LUES clause specifies the data
‘The argument/values of character and date data
or single quotation marks, ‘ype are always enclosed in double
Column values for the data type of a column are provi x AG
Provided within
single quotes. curly braces {} or
+ NULL values are stored and displayed as NULL only without
any quotes.
+ Ifthe data is not available forall the columns, then the column-list mustbe
following the table name included
“qaninSQl, we can repeat or re-execute the last command typed at SOL by
sronkeysand pressing Enter e PromPLEy!
{)) Inserting data directly into a table: The second form specifies both the column names
and the values to be inserted.
Syntax: INSERT INTO (column1,column2,columnN,,...)
VALUES (value1,value2,valueN,
Here, column1, column2, ...columnN—the names of the columns in the table for which you
want to insert data.
For example, mysql> t (Rol1No, Name, Gender, Marks, DOB)
98, '1996-08-22");
{hen adding a row, only the characters or date values should be enclosed within sr
(9 Inserting data into specific columns ofa table:
Syntax for SQL INSER’
'NSERT INTO [(columnt, column2, ...columnN)]
VALUES [(val :
wet, value?,... valueN)];
: : jumns Rolino, Name and
‘or example, to insert a record into the student table for the columns Relino, Na
arks only, the SQL insert query is: ;
4, "Radhika
"Yb INSERT INTO student (Rollno, Name, Marks) VALUES. {
wpta",78) ;
i ns—Rolino,
ie above statement shall insert the values for specific colum
“Pectively,
Name and Marks(a) Inserting NULL values into a table: Ifa column in a row has no value or missin
then the column is said to be null or holding NULL value, Null value can be given yt”
column other than being assigned as primary Key or Not Null constraint Its agyi.”
to use Null when the actual value is not defined or unavailable. NULL values are Se)
differently from other values as they represent missing unknown data, By default, a cq
ina table can hold NULL values, ‘mn
Ifa column ina table is optional, we can insert a new record or can modify an, existing ty
. without adding values to this column In other words, the values in every record for ine
is
column/field shall be stored as NULL. We can insert NULL value into any column in a tay
Itcan be done by typing NULL without quotes. “
Nullis not equivalent to 0, ce, NULL ¢ 0. Itacts as a placeholder for unknown or inapplicable
values.
For example, mysql> INSERT INTO Student (Rollno, Name, Gender, Marks, Dog)
VALU! , "P', NULL, NULL);
12, 'Swati Mehra
After the execution of the above command, NULL value shall be inserted for the fields
Marks and DOB respectively.
evaluates to null |
8. Modifying Data in a Table
To modify data in a table or to make changes for some or all of the values in the existing records in
a table, we use the UPDATE statement. The UPDATE command specifies the rows to be modified
using the WHERE clause and the new data is written into the respective record using the SET
(TM: Null means unavailable or undefined value. Any arithmetic expression containing a NULL always _
keyword.
Syntax for UPDATE:
UPDATE
SET = , = ,
WHERE
Marks = 90
jon>;
DATE Student
WHERE Rollno 8;
‘The above statement shall change the value of Marks field to 90 for the student whose roll number is8.
(a) Updating multiple columns
Modifying the values in more than one column can be done by separating the columns along
with the new values using SET clause, separated by commas.
For example, mysql> UPDATE Student
SET Marks = 70, DOB
WHERE Nam
1998-08-11!
Payal";
‘l
The above statement shall change the values for both the fields Marks and DOB to 70"
‘1998-08-11’ respectively for the student whose name is Payal.
—updating to NULL values
)
the values for the attributes in a relation can also be entered as NUI
?
For example, mysql> UPDATE Student LL-using UPDATE command,
T Marks = NULL.
WHERE Rollno = 9;
‘The above statement shall change the
value of the feld Marks to Null for the student whose
roll number is 9.
Updating using an expression or formula q
For example, mysql> UPDATE Student
! Marks = Marks + 10 |
WHERE (Rollno = 5 or Rollno =10);
‘The above statement shall increment the value of Marks by 10 for all the records with Roll
number 5 or 10
The DELETE statement is used to delete rows from a table.
Syntax for DELETE Statement:
DELETE FROM WHERE ;
here is the table whose records are to be deleted.
Ie)
The WHERE clause in the SQL delete command is optional and it identifies the rows in the column:
Celeted.f you do not include the WHERE clause, all the rows in the table are deleted.
4,Removing Data from a Table
foreample, mysql> DELETE FROM Student WHERE Rollno = 10;
“eabove statement shall delete the record only for roll number 10.
To delete all the rows from the student table, the DELETE statement will be: DELETE FROM
student;
SQLTRUNCATE Statement
QL TRUNCATE command is used to delete all the rows from the table and free the spasss
ining the table |
»yne
ee ‘0 TRUNCATE a table:
UNCATE TABLE ;
Conta
delete ain : |
iy the rows from student table, the statement will be:
als sh
iter SP TRUNCATE TABLE Student
ence
Ubypae PCtWeen DELETE and TRUNCATE Statements
i le based on the on
Bren iy ttements This command deletes only the rows from ay we a
ry fia here clause or deletes all the rows from the table if n 4
‘he space containing the table.
his command is used to dele
table and free
te all the rows from the>
10. ALTER TABLE Command tates ues meee
‘ ed to modify the definition
dates SHAE a nee TABLA, hint is used to perform the towne
» To add a column to an existing table,
» ‘To rename any existing column,
» To change the data type of any column or to modify its size,
» To remove or physically delete a column,
(a) Adding a column to an existing table
Once a table has been created, new columns can be added later on, if required, ‘The n
column is added with NULL values for all the records/rows in the table, Itis POSSible tp
add, delete and modify columns with ALTER TABLE statement,
Syntax for adding a new column:
A
For example, to add a new column Mobile_no of type integer in the table student:
mysql> ALTER TABLE Stud
TABLE ADD( [size});
nt ADD (Mobile no integer);
‘Thus, the above si
NULL value in it.
tement shall add 4 new column Mobile_no into the table student with
We have just added a column and there will be no d,
be used to supply values/data to this column,
ata (NULL) under this attribute, UPDATE command can
(b) Adding a column with default value
ALTER TABLE command can be
values.
used to add a new column to an existing table with default
Syntax for adding a column with a default value:
ALTER TABLE
ADD ([column_namet}default data);
For example, mysql> nit ER ‘YAR
The above command will
student table,
tudent ADD (City (6) default "DELHI");
It value as “DELHI” to the
add a new column City with d
Resultant table: student
A Te Ty
1 Raj Kumar mM 93 17-Nov-2000 NULL DELHI"
2 Deep Singh M 98 22-Aug-1996 NULL DELHI
3 Ankit Sharma ” 76 02-Feb-2000 NULL DELHI
7 me oe F 78 03-Dec-1999 NULL DELHI
- sie : _ fi 82 21-April-1998 NULL DELHI
aaa y 80 17-Dec-1999 NULL DELHI
8 Akshay Dureja M a NU ae
oka sae res : 90. 05-May-1997 NULL DELHI :
10 Prateek Mittal M on aaa aa al
75 25-Dec-2000 NULL DELHIPa ail existing column definition
se can be used with ALTER TABLE ¢
posit!
Jated to any column of the table, mmand to change the data a
yoolF¥ lau!
HE pstraint TO :
se jor difying existing column data type:
ox
gs ‘ABLE
{column_namet] );
Al
yonlF¥(
forexarPl@ i
mysql> ALTER TABLE Student MODIFY (Name varchar (25); <
sre above command will modify the data type size for the Name field from 20 to 25
characters
genaming a column !
existing column in arelation can be renamed using ALTER TABLE command,
syntax for rel
ALTER TABLE
(HANGE [COLUMN] column_definition;
naming an existing column:
for example,
udent CHANGE City State varchar (10);
mysql> ALTEF
The above command shall rename the City column to State
1 Raj Kumar M 93 17-Nov-2000
2 Deep Singh M 98 22-Aug-1996
3° Ankit Sharma mM 76 02-Feb-2000
4 Radhika Gupta F 78 03-Dec-1999
5 Payal Goel F 82 21-Apri-1998
6 Diksha Sharma F 80 17-Dec-1999
7 Gurpreet Kaur F 65 04-Jan-2000
8 Akshay Dureja M 90 05-May-1997
9 Shreya Anand F 70 08-Oct-1999
; 10 Prateek Mittal M 75 25-Dec-2000
Removing a column
\d is used.
To
emove or drop a column in a table, ALTER TABLE commant
Syn
ie removing a column:
ERTABLE DROP i
* ample,
m ;
¥Sql> ALTER TABLE S nt DROP (State)?
ab, BLE Studen’ itt
Ove lent .
command will drop State column from the stuResultant table: student
CL
1 Raj Kumar mM 93 17-Nov-2000 = NULL
2 Deep Singh M 98 22-Aug-1996 NULL
3 Ankit Sharma M 76 02-Feb-2000 NULL
4 Radhika Gupta F 78 03-Dec-1999 NULL
5 Payal Goel F 82 21-April-1998 NULL
6 Diksha Sharma F 80 17-Dec-1999 NULL
7 Gurpreet Kaur F 65 04-Jan-2000 NULL
8 Akshay Dureja M 90 05-May-1997 NULL
9 Shreya Anand F 70 08-Oct-1999 NULL
10 Prateek Mittal M 75 25-Dec-2000 NULL
11. DROP TABLE Command
Sometimes, we may need to physically remove a table which is not in use. DROP Tagig
command is used to remove/delete a table permanently. If you drop a table, all th
‘© TOws in the
table are deleted along with its structure. Once a table is dropped, we cannot get it back and
all other references to the table become invalid. This command completely destroys the table
structure.
Syntax for removing a table:
DROP TABLE ctable-name>;
For example,
mysql> DROP TABLE student;
This command will Permanently remove the table student from the database school.
8.14 SOL QUERY PROCESSING