Object-Oriented Programming in C++
Object-Oriented Programming in C++
Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow,
and organizing these instructions for the computer to follow, and organizing these instructions into groups
known as functions.
In multi-function program, many important data items are placed as global as that they may be
accessed by all the functions. Each function may have its own local data. Above figure shows the relationship of
data and functions in a procedure-oriented program
Global data area more prone to an inadvertent change by a function. In large program it is very
difficult to identify what data is used by which function. This is one of the drawbacks of Procedure oriented
programming. Another drawback is that it does not model real world problem very well. This is because
functions are action oriented and do not really corresponding to the elements of the problem.
Characteristics of Procedure –Oriented Programming:
1. Emphases on non-living and non-real items i.e. have algorithmic approach (sequence of steps).
2. Large program are divided into smaller programs known as functions.
3. Most of the function share global data.
4. Data move openly around the system from function to function i.e. there is no control on data.
5. Function transforms data from form to another.
6. Employ top-down approach in program design.
Exemple: PASCAL,COBOL,C,FORTRAN etc.
Object Oriented Programming:
The major motivating factor in the invention of object-oriented approach is to remove the drawbacks of
procedure approach.OOP treats data as critical element in the program development and does not allow it to
flow freely around the system. It ties data more closely to the functions that operate on it and protects it from
accidental modification from outside functions. OOP allows us to decompose a problem into a number of
entities called objects and then builds data and function around these entities.
“Object-oriented is an approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating copies of such modules on
demand. “
Encapsulation
Encapsulation is an Object oriented programming base concept.
Encapsulation means protect important data inside the class which we do
not want to exposed outside the class. Encapsulation process means
binding data members (variable, properties) and member function
(Methods). It consist of separating the external aspects of an object from
the internal implementation details of the object which are hidden from
other objects i.e. data is not accessible to the outside world and only those function which are wrapped in the
class can access it .In other words the wrapping up of data and functions into a single unit (called Class) is
called Encapsulation. It prevents a program from becoming so interdependent that a small change has massive
ripple effects. Encapsulation is not unique to OOPs .It has a good ability to combine data structure and
behaviors in a single entity .e.g. in an organization different departments access and work with their data on
their own .One department cannot access data of another department directly .They can share their information
only when a special request is made for a required data and the data is handed over by the member of the
requested department
Data Abstraction:
Abstraction means displaying only essential information and hiding the details or
explanation. Data abstraction refers to providing only essential information about
the data to the outside world ,hiding the background details or implementation It
focuses on the outer view of object. Abstraction is the selective examination of
certain aspects of a problem. The goal of abstraction is to isolate those aspects
that are important for some purpose and suppose those aspects that are
unimportant.
To understand abstraction let us take an example we are driving a car. We only know the essential features to
drive a car e.g. a gear handling, steering handling, use of clutch, accelerator brakes etc. but while driving do we
get details of car like wiring, motor working etc ? We just change the gears or apply the brakes etc. What is
Polymorphism:
Polymorphism is key to the object oriented programming. It is most important that languages that don‟t support
polymorphism cannot advertises themselves as OO languages .Language that support classes but not
polymorphism are called object based language .Ada is such a language .
Polymorphism is the ability for a message or data to be processed in
more than one form. Polymorphism is the concept that supports the
capability of an object of a class to behave differently in response to a
message or action. e.g. „Human‟ is a subclass of Mammal. Similarly Dog,
Cat are also subclasses of Mammal .Mammals can see through day-light.
So if a message „see through daylight is passed to all mammals, they all will behave alike .Now if a message
„see through darkness is passed to all mammals, then human and dogs will not be able to view at night whereas
cats will be able to view during the night also. Here cats (mammals can behave differently than other mammals
in response to a message or action. This is Polymorphism.
Polymorphism is a property by which the same message can be sent to
objects of several differently classes and each object can respond in a
different way depending on its class.
The following figure shows that a single function name can be used to
handle different member and different types of arguments. This is
something similar to a particular word having several different meaning depending on the context.
Inheritance Concept
Base Class
The technique of deriving a new class from an existing class is called inheritance. A
class that is inherited is referred to as a base (super) class. The class that does the inheriting
is called the derived (sub) class. Further a, derived class can be used as a base class
Derived Class
for another derived class. The derived class inherits some or all the properties of the
base class. The relationship between base and derived class is known as inheritance Inheritance
hierarchy.
Function Overloading
Function overloading implements polymorphism. Function overloading can also be termed as compile –time
polymorphism as the required function gets determined at the compile time.
Function overloading is a logical method of calling several functions by the same name, with different
arguments and data types which basically perform identical things.
A function name having several definitions that are differentiable by the number or types of their
arguments is known as function overloading
Need for Function Overloading
Objects have certain characteristics and associated behavior. But an object may behave in a different manner in
diverse situations.
In order to simulate real-world objects in programming, function overloading becomes essential. For overloaded
functions, the compiler automatically decided the particular function to be executed. It not only reduces the
code by reducing the number of if-else statements but also makes the code execute faster as so many
comparisons are eliminated
Advantages of Function Overloading
The programs become easier to read.
The programmer need not waste time in searching for a new name for similar functions.
The programmer can devote more time on logic development and need not remember different names.
It is used in inheritance and abstraction.
It is possible to speed up the program by inlining the right function
It makes the language extensible.
IT Brainshapers 8 Sanjay -7889862407
12th Comp Science Unit 1:Object Oriented Programming in C++ Marks 15
Disadvantages of Function Overloading
1. Since the complier will copy the entire function body every time the function is called, if it is a large function
(more than three or four lines), inline function can increase the size of the executable program significantly.
Rules for function Overloading
1. Each overloaded function must differ either by number of its formal parameters or their data types.
2. The return type of overloaded functions may or may not be same.
3. The default arguments of overloaded are nor considered by the C++ complier as part of the parameter list.
4. Do not use the same function name for two unrelated functions
Declaration and Defining Overloaded Functions
int area(int); or int area( int s);
int area(int ,int); or int area(int b,int h);
int area( int s)
{
return s*s;
}
int area (int b ,int h)
{
return (0.5*b*h);
}
Calling Overloaded Functions
Overloaded functions can be called just like any other C++ function. The number and type of arguments
determine which function is called
e.g area(5);
area(4,3);
Example1 Example2
/* Different Number of Arguments*/ /* Different Types of arguments*/
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
int area(int); float inc(float);
int area(int ,int); char inc(char);
void main( ) void main( )
{ {
clrscr(); clrscr( );
cout<<area(5); cout<<inc(23.45);
cout<<"\n"<<area(4,3); cout<<inc(A);
getch( ); getch( );
} }
int area( int s) float inc(float x) // Overloaded function
{ {
return s*s; return(++x);
} }
int area (int b ,int h) char inc(char x)
{ {
return (0.5*b*h); return ++x;
} }
Default Constructor
The constructors which do not have no arguments (parameters) or have default arguments are known as Default
constructor. If a class has no explicit constructor defined, the complier will supply a default constructor
provided by the complier does not do anything specifies it initialize the data member by the dummy value. e.g.
class counter
{
private :
int value;
public:
counter( ) // this is default constructor
{
value=0;
}
};
When a class contains a constructor like the one defined above, it is guaranteed that an object created by the
class will be initialized automatically. For example, the declaration not only creates the object c1 of type
counter but also initializes its data member value to zero
counter c1 //object c1 is created
Parameterized Constructor
When parameters are specified but no default values of parameters in the definition of the Constructors, such
constructors are called as Parameterized constructors.
e.g
class counter
{
private :
int value;
public:
counter(int a) //parameterized constructor
{
value=a;
}
};
When a constructor has been parameterized ,the object declaration statement such as
counter c1; //
may not work. We must pass the initial values as arguments to the constructor function when as an object is
declared. This can be done in two ways:
By calling the constructor explicitly.
By calling the constructor implicitly.
Destructor
Destructors have reverse function as that of constructors. The space which is an allocated dynamically can be
freed by the destructor .So destructor can free the space which has been allocated by new operator only. The
destructor is a special member function whose name is the same as the class name but is preceded by
tilde (‘~’) For example destructor for the class Student will bear the name ~student( ) It has following
characteristics:
Destructor has the same name as the class of which is a part and proceeded by the symbol ~.
Destructor does not have return type as function of destructor is to free space.
Destructor is invoked automatically at the time of death of object.
Destructor cannot have arguments.
Destructor must be defined in the public part otherwise it will not be invoked.
Destructor can be virtual.
Destructor cannot be volatile.
Destructor cannot be static.
Destructor cannot be const.
Destructor cannot be overloaded
Need for Destructor
During construction of an object by the constructor, resources may be allocated for use. e.g.
a constructor may have opened a file and a memory area may be allotted to it.These allocated resources must
be deallocated before the object destroyed. A destructor as per name perform clean up task./Therefore, a
destructor is equally useful as a constructor is.
Declaration and Definition
A destructor is a member function and can be defined like any other member
function. However, it does not take any argument neither does it return any value.
A destructor being a member function follows the access rules for a member function i.e. if defined as
a private or protected member function, it becomes available for a member functions and only these can create,
Derived Class
Inheritance
In C++, a derived class can be obtained by adding some new data structure and functions
to a base class. The derived class inherits the members of its base class without the need
to redefine them.
The general syntax for defining a derived class is given below
class <derived class> : visibility mode <base class>
{
body of new class
};
where , class : is a reserved word
<derived class> : is the name of the subclass or new class being derived
visibility mode : is the mode of access to items from the base class.
The access mode is optional and can be either of the following type:
private ,public, protected
<base class> : is the name of the super class i.e. an existing class
//This program illustrates the inheritance int marks;
#include<iostream.h> public: void get_data()
#include<conio.h> {
class person read_data ( ); //read name & age from
{ base class
private: cout<<"\n RollNo: ";
char name[30]; //non-inheritable being private cin>>roll;
int age; cout<<"\nEnter marks: ";
public: cin>>marks;
void read_data() }
{ void show_data()
cout<<"\nEnter Name: "; {
cin>>name; display_data();
cout<<"\nEnter Age: "; cout<<"\nRoll No : "<<roll;
cin>>age; cout<<"\nMarks : "<<marks;
} }
void display_data() }; //end of class student
{ void main()
cout<<"\nName : "<<name; {
cout<<"\nAge : "<<age; clrscr();
} student stud; // create an object of student type
}; //end of class person stud.get_data(); //read data of a student
class student :public person stud.show_data();
{ getch();
private: }
int roll;
IT Brainshapers 1 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Y derived class
Multiple Inheritance
When a subclass inherit from multiple base classes. It is known as multiple inheritance.
X Y base classes
Z derived class
Multilevel Inheritance
When a subclass inherits from a class that itself inherit from another class. It is known as multilevel inheritance.
X base class of Y
Y
base class of Z
Z Sub class of Y
Hierarchical Inheritance
When many subclasses inherit from a single base class. It is known as hierarchical inheritance.
Z base class
W X Y Sub classes
Y derived class
//This program illustrates the inheritance void main()
#include<iostream.h> {
#include<conio.h> clrscr();
class person student stud; // create an object of student type
{
private: stud.get_data(); //read data of a student
char name[30]; //non-inheritable being private stud.show_data();
int age; getch();
public: }
void read_data()
{
cout<<"\nEnter Name: ";
cin>>name;
cout<<"\nEnter Age: ";
cin>>age;
}
void display_data()
{
cout<<"\nName : "<<name;
cout<<"\nAge : "<<age;
}
}; //end of class person
class student :public person
{
private:
int roll;
int marks
public:
void get_data()
{
read_data ( ) //read name & age from base class
cout<<"\n RollNo: ";
cin>>roll;
cout<<"\nEnter marks: ";
cin>>marks;
}
void show_data()
{
display_data()
cout<<"\nRoll No : "<<roll;
cout<<"\nMarks : "<<marks;
}
}; //end of class student
IT Brainshapers 7 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Multiple Inheritance
When a subclass inherit from multiple base classes. It is known as multiple inheritance.
X Y base classes
Z derived class
X base class of Y
Y
base class of Z
Z
Sub class of Y
The multilevel inheritance implements the transitive nature of real life objects. There can be any number of
classes in the inheritance hierarchy.
/This program illustrates the multilevel inheritance void grandFather::display_data()
#include<iostream.h> {
#include<conio.h> cout<<"\nName : "<<name;
class grandFather cout<<"\nAge : "<<age;
{ cout<<"\nColour : "<<color;
private : }
char name[30]; void father::read_data()
int age; {
public: get_data();
char color[15]; cout<<"\nEnter the qualification: ";
void get_data(); cin>>quali;
void display_data(); cout<<"\nEnter the salary : ";
}; cin>>salary;
class father: public grandFather //derived class:level1 }
{ void father::show_data()
private : {
char quali[25]; display_data();
public: cout<<"\nQualification : "<<quali;
float salary; cout<<"\nSalary : "<<salary;
void read_data(); }
void show_data(); void son::input()
}; {
class son:public father //derived class:level2 read_data();
{ cout<<"\nEnter the hobby: ";
private : cin>>hobby;
char hobby; }
public : void son::output()
void input(); {
void output(); show_data();
}; cout<<"\nHobby : "<<hobby;
void grandFather::get_data() }
{ void main()
cout<<"\nEnter the name : "; {
cin>>name; clrscr();
cout<<"\nEnter the age : "; son s;
cin>>age; s.input();
cout<<"\nEnter the colour : "; s.output();
cin>>color; getch();
} }
IT Brainshapers 9 Sanjay -7889862407
12th Comp Science Unit 3: Inheritance(Extending Class) Marks 05
Nested Class or Containership
Presence of one or more classes within an other class as its member or members constitutes a Nested Class, the
process being known as Nesting of classes.
When a class is defined inside the body of another class is called as nested class i.e. class within class
When a class contains another class in it as a member, this class obviously inherits the attributes of the
contained class, without inheriting the contained class explicitly.
Another technique of making A to inherit the properties of another class B is to incorporate the object or objects
belonging to the class B as members of the class A.
The relationship of a class containing the objects belonging to the other class or classes is known as
containership or nesting.
e.g
class B
{
….
};
class A
{
B b; //object of class A
};
//This program illustrates use of nested class class manager
#include<iostream.h> {
#include<conio.h> private :
class employee char desi[30];
{ employee emp; //object of class employee
private: public:
char name[20]; void get_details(void)
int salary; {
public: emp.get_data();
void get_data(void) cout<<"\n Enter designation :";
{ cin>>desi;
cout<<"\n Enter name of employee"; emp.show_data();
cin>>name; cout<<"\n Designation :"<<desi;
cout<<"\n Enter salary"; }
cin>>salary; }; // end of contained class manager
} //the main program start
void show_data(void) void main()
{ {
cout<<"\n Name : "<<name; clrscr();
cout<<"\n Salary: "<<salary; manager m;
} cout<<"Enter data for manager\n";
}; //end of class employee m.get_details();
getch();
}
The memory is allocated automatically by the compiler and operating system at runtime. But once the operating
system has assigned the address to available we have faculty to know its memory address with the help of
reference or address operator which is represented by ‘&’. Suppose x is the name of the variable then &x is
the address. The address of a variable is constant .It cannot be changed during the program execution.
The memory address of the operator is accessed by mean of address operator & e.g. to print the value of
statement is
cout<<&x;
The address operator & operates on the variable name to produce its address
Consider the following program
//This program illustrates the use of Address &
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a = 10;
cout<<"a = "<< a;
cout<<"\n\n Address of a"<<&a;
getch();
}
Concept of Pointer
A pointer, also known as a Pointer variable, is a special variable that holds the memory address, usually the
location of another variable in memory. If one variable contains the address of another variable, the first
variable is supposed to point to the second.
As a pointer stores the actual address of the memory location containing the data value of a variable, the
complier can locate that value in memory very easily.
Let us assume that y is such a variable .Now, the address of variable x can be assigned to y by the statement
y =&x;
2712 1232
int x =15;
x 15 y 2712
y = &x; ≡
From the illustration given above, it is clear that y is the variable that contains the address (i.e. 2712) of another
variable x whereas; the address of y itself is 1232(assumed value). In other words we can say that y is a pointer
to variable x
x y
y
15 *
The pointer variable must not remain uninitialized since uninitialized pointer causes the system crashing. Even
if you do not have any legal pointer value to initialize a pointer, you can initialize NULL pointer value.
Assigning NULL to a pointer initialize it to a value which is not a legal pointer but it saves you from the ‘Big’
Array
Another name of declaration of array which have fixed or constant value is defined as:
e.g the above said different values can be assigned to the array as :
static int number[5]={55,35,40,47,33};
ii) Non-linear Array:
Non-linear array are further subdivided into n categories as:
a) Two Dimensional Array
b) Three Dimensional Array
c) N Dimensional Array
a) Two Dimensional Array
These arrays are also called double dimensional array or two subscripted array. Another name of two
dimensional array is Tabular or Rectangular Array. These array are in row and column form. So it is called
Row-Column or Square Array. These arrays have two subscripts. We can write the double dimensional array in
tabular form as :
a00 a01 a02 … a0n
a10 a11 a02 … a0n
… … …
an0 an1 an2 … ann
The general syntax used for declaration of two dimensional array is as:
data-type array-name [row size] [column size];
e.g. Some valid declarations are :
int a[10][10];
float b[50][50];
char name [10][20];
Also we can declare two dimensional array in static form i.e. these types of array declarations have fixed or
constant values during declaration. The syntax used is as follows:
static data-type array-name [row size] [column size] ={list values};
e.g Suppose if we want to assign some constant or fixed values to array variables name table then it can be
represented as;
static int table[2] [3] ={5,7,12,2,20,8};
The above declared data be assigned to different array variables are as:
table [0][0] =5
table [0][1] =7
table [0][2] =12
table [1][0] =2
table [1][1] =20
table [1][2] =8
b) Three Dimensional Array
Three Dimensional Array is also called space array or xyz array. As it has three subscripts, so these are also
called triple dimensional array. The general syntax used for declaration of three dimensional array is as:
data-type array-name [space size][row size] [column size];
e.g. It can be declared as:
int st [5][2][3];
In order to insert a value 50 in the array SERIES at location 4, the value from 60 to 100 will have to be shifted
one step towards the right .This means SERIES [9] will get the contents of SERIES [8], SERIES [8] will get the
contents of SERIES [7] and so on till the contents of SERIES [4] are copied into SERIES [5].As soon as the
copying operation ends. SERIES [4] is available for storing the incoming value 50.The necessary shift
operations are:
SERIES [9] =SERIES [8]
SERIES [8] =SERIES [7]
…………..
SERIES [5]=SERIES[4]
When all elements have been shifted, the following assignment operation stakes place:
SERIES [4] =50
The array SERIES after the insertion operation is:
After deleting the values 45 from the array SERIES at location 4, the values from 50 to 100 will have to be
shifted one step towards left. This means SERIES [9] will get the contents of SERIES [10],SERIES[8] will get
the contents of SERIES [7] and so on till the contents of SERIES[5] are copied into SERIES [4].The various
shift operations required as:
SERIES [9]=SERIES[10]
SERIES [8]=SERIES[9]
…………..
SERIES [4]=SERIES[5]
The array SERIES after the deletion operation is as shown in the figure:
Searching
Searching is one of the common operations that is extensively used in data processing. The search may involve
large amount of data. The search algorithm accepts the key to be searched; the record where to search and the
number of items to be searched .Search can be performed on any of the data structure.
Linear Search (Sequential Search)
It is an operation in which a given array can be searched for a particular value. The location of the searched
element is informed. It is best used if the array we are searching is unsorted .This method of searching is usually
use on small arrays of less than 16 elements. The sequential search is started by first declaring a target to be
found. The search starts with comparing each element one by one with the given value of the element to be
located.
Algorithm
Linear Search (SERIES, ITEM, COUNT)
Here SERIES is an array with N elements, and ITEM is the value to be searched for. The algorithm given below
finds the location POS of ITEM in the array SERIES.
Steps: 1 COUNT =0; LOC= -1;
2 While(COUNT<N) repeat steps 3 to 4
3 IF (SERIES[COUNT]=ITEM) then LOC =COUNT
4 COUNT = COUNT +1
5 Display LOC
6 END
In the above algorithm, the variable COUNT is updated to keep record of the number of elements visited .Each
element of the array is compared with the given value of ITEM. If the match is found, then the location of the
element i.e. current value of COUNT is stored into a variable called LOC.
If there are duplicate values in the array SERIES, then the variable LOC containing the last duplicate value is
printed
Binary Search
Push Operation
Push is the operation of adding an element to the stack .In performing this operation; one must first test whether
there is a room in the stack for the new item. If there is no room, the stack is said to be in a condition of
overflow.
Top→ T
Top→ S S
Top→ R R R
Q Q Q
P P P
Applications of a Stack
The applications of stacks are as follows:
1. Conversion of expressions: The mathematical expression written in one form can be efficiently converted
to another form. Example: infix to postfix, infix, to prefix, postfix to infix, postfix to prefix.
2. Evaluation of expression: An arithmetic expression represented in the form of either postfix or prefix can
be easily evaluated.
3. Recursion: A function which calls it is called recursion function. Some of the problems such a tower of
Hanoi, a very important facility available in a variety of programming languages such as C, C++ etc.
4. Other applications: There are so many other applications where stacks can be used .To list a few: to find
whether the string is palindrome, to check whether a given expression is valid or not, topological sort etc.
Queue
A queue is a dynamic linear list in which deletion takes place only at one end called FRONT or HEAD and
insertions take place at the other end called REAR or TALL. Thus, in a queue, unlike stack, the data item
entered first is popped out first and the one entered last is popped out last. It is for this reason that the queue is
called FIRST IN FIRST OUT (FIFO). Thus logical a queue is a FIFO structure and physically it can be
implemented either as an array or linked list.
The railway reservation counter is also an example of queue where the people collect their tickets on the first
come ,first server basis also known as FIOFO i.e First IN First Out
Deletion ← ←Insertion
↑ ↑
Front Rear
Need for a Queue
A queue is a variable size ordered collection of similar objects. There are two main aspects of a queue that make
it attractive for verification purposes.
First, a queue can have variable length, including a length of zero. This makes a queue an ideal candidate
as a storage element that can shrink or grow as elements are deleted or added to it without fixing an
artificial upper limit on its size as a regular fixed size array.
The other advantage of having a queue is that it provides a way to emulate both Last in First Out (LIFO)
and First in First Out (FIFO) behavior that are required in so many order transactions.
IT Brainshapers 12 Sanjay -7889862407
12th Comp Science Unit 5: Data Structure Marks 10
Characteristics of a Queue
The first element inserted in the queue is the first element that can be taken off.
Insertions can be done at one end i.e. rear and deletions can be done at the other end i.e. front.
It looks like an open tube.
The insertion operation of the queue is called append /enqueue operation.
The deletion operation is called serve /dequeue operation.
Push operation on a full queue causes overflow.
Pop operation on an empty queue causes underflow.
The initial value of the front and rear pointer is always -1.
The front pointer points to the starting of the queue.
The rear pointer points to the rear of the queue.
Queue as an Array
When a queue is created as an array, its space required (no of elements) is declared before processing. The
beginning of the array becomes its “front” end and the end of the array becomes its “rear” end .The term “front”
and “rear” are used in describing a liner list only when it is implements as a queue.
“Front” stores the number of first element in the queue and “rear” stores the number of last element in the
queue. The number of elements in a queue at any given time can be calculated from the values of “front” and
“rear”.
If “front”=0 then no of elements =0 else “no-of-element”= front –rear =1
Size Capacity
0 1 2 3 4 5↓ 6 7 8 9 10↓
A B C D E
↑ ↑
FRONT=0 REAR=5 N-1
Operations of Queue
Array representation of a queue
There are two operations applied on queue .they are
Enqueue/Addition
Dequeue/Deletion
Enqueue or Insertion in an Array Queue
Enqueue operations are used to insert a new element into the queue. At the time of insertion first it is checked
whether the queue is full or not. If the queue is full, it generates an error message „queue overflow‟.
When an element is added to a queue, the position of the rear is increased by 1.This is done by the assignment
statement
REAR=REAR+1;
If we keep on adding elements to the queue, then the stage will be reached when the queue cannot hold any
more elements. It is a condition of
REAR = N-1.
This condition is called Queue-Full. Addition from the queue
0 1 2 3 4 5 6 -------------------------------- N-1
A B C D E F
↑ ↑ ↑
FRONT=0 REAR=6
0 1 2 3 4 5 6 -------------------------------- N-1
A B C D E F
↑ ↑ ↑
FRONT=1 REAR=6
If we keep on
deleting elements
to the queue, then the stage will be reached where there will be no item in the queue. It is condition of FRONT
= REAR. This condition is known as Queue Empty or Under Flow.
Initially, when the queue is empty, both FRONT and RAER are set to 0, i.e. FRONT = REAR =0
0 1 2 3 4 5 6 -------------------------------- N-1
↑↑ ↑
FRONT=REAR=0 REAR=6
INFO NEXT
Two pointers FRONT and REAR keep count of the front end and rear end of the queue.
FRONT REAR
NULL
IT Brainshapers 1 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Control over Concurrency
In a computer file based system in updating, one may overwrite the values recorded by the others.
Better Data Security
Data security is the protection of database from an unauthorized access. DBMS allows to keep the data
confidential by providing different levels of security e.g. Manager can be allowed to access the salary of
an employee but the employee other than manager are not allows to access the salary of the employee
Better data accessibility
DBMS allows online access by user by providing query language that permits users particular non-
programming personal to ask question and obtain information as needed without the help of any
programmer
Standard can be enforced
With central control of the database, the DBA can ensured that all applicable standards are followed in the
representation of the data, such as format of data items, conventions on data names ,documentation
standards etc, which will result in uniformity of the entered database as well as its usage .
Interface with the past
Organizations which have been using data processing for some time having a major investment in their
existing programs, procedures and data. When an organization install new database software it is
important that it can work with the existing programs & procedures and that the existing date can be
converted .This need for compatibility can be major constraint in switching to a new database system
Better backup and recovery procedure
Automatically create the backup of data of data and restore if required. Whenever the database is
modified, a log entry is made .If the system fails, the tape and log is used to bring the database in original
state it was in before failure
Data Independence
Because of Physical data independence the file may migrate from one type of physical media to another or
the file structure
Disadvantages
Cost of hardware and Software Processor with high speed of data processing and memory of large size
is required .
Cost of Data Conversion Very difficult and costly method to convert data of data file into database.
Cost of Staff Training A lot of amount for the training of staff to run the DBMS
Appointing Technical Staff Trained technical persons such as DBMS Administrator ,application
programmer, data entry operators etc. are required to handle DBMS.
Database Damage All data is integrated into single database>if database is damaged due to electric
failure or corrupted on the storage media, then your valuable data may be lost forever.
Data Model
A data model is a collection of conceptual tool for describing data, data relationship, data semantics. Data
models describing the organization of different objects namely, records, data dictionary elements etc. Data
Models can be classified into following categories
1 Relational Model Normalize Structure
2 Network Model Plex Structure
3 Hierarchical Model Tree Structure
IT Brainshapers 2 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
1 Relational Model:
The relational model represents data and relationships among data by a collection of tables known as
relation each of which has a number of columns with unique name. Rows of the table are referred to as
tuples and the columns of a table are referred to as attributes.
Advantages: The advantages of this model are:
Since tabular structure is simple and familiar, it is easy to understand.
Data manipulation is easy.
We can apply mathematical operations on tables.
Built in query language support on RDBMS, is available.
Very flexible data organization..
Limitation : The major limitation of this model is that size of database becomes large
Example : Oracle ,Ingres, Sql Server 2000,Unity,My Sql
St_Code St_Name St_Age St_Class
S101 Raj 16 5th
S102 Neha 17 4th
2 Network Model :
The network model represents data by collection of records and relationship among data is
represented by links which can be viewed as pointers. The records in the database are organized as
collection of arbitrary graphs.
School
Fee
IT Brainshapers 3 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Advantages: The advantages of this model are:
Many to many relationship can be implemented.
Easier access compared to hierarchical model.
Limitations: The limitations of this model are as under
1. Number of links tends to be extremely large as the complexity increase.
2. New queries cannot be implemented.
3. Extra storage is required for pointers.
4. A high level language is needed to program the database.
5. General purpose Query facility not available .
Examples : UNIVAC‟s ,DMS 1100 and DBMS 10-20 from DEC
3 Hierarchical Model :
Hierarchical model is similar to the network model in the sense that data and relationship among data are
represented by records and links respectively. It differ from the network model is that the records are
organized as collection of trees rather than arbitrary graph. The restriction being that a child can have only
one parent.
School
Internal
Stored-Item Length(40)
Item_Number Type=Byte(6), offset=0,Index=Ix
Item_Name Type=Byte(20),offset=6
Price Type=Byte(8), offset=26
Numeric(5+2) Type=Byte(4), offtset=34
Reorder_quantity Numeric(4)
IT Brainshapers 5 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
External Level (View Level)
This is the level closest to the users and is concerned with the way in which the data are viewed by
individual users. Only a part of the database relevant to the users is provided to them through this level.
Data Independence
The ability to modify a scheme definition in one level without affecting a scheme definition in the next
level is called data independence .Data Independence implies that the data and application programs
which use them are independent so that either may be changed without changing the other. There are two
types of data independence .They are
1. Logical Data Independence
2. Physical Data Independence
1. Logical Data Independence
Logical data independence means that the overall logical structure of the data may be changed without
changing the application programs. The change must not of course remove any of the data of the
application program‟s use.
2. Physical Data Independence
Physical data independence means that the physical layout and organization of the data may be changed
without changing either the overall structure of the data or application programs.
Conceptual
Model of a Database
Logical
Data Independence
Logical
Model of a Database
Physical
Data Independence
Physical
Model of a Database
Codd's Rules for Relational Databases.
E.F. Codd, the famous mathematician has introduce 12 rules for the relational model for databases
commonly known as Codd's rules. The rules mainly define what is required for a DBMS for it to be
considered relational , i.e., an RDBMS. There is also one more rule i.e. Rule00 which specifies the
relational model should use the relational way to manage the database. The rules and their description is as
follows:-
Rule 000: A RDBMS system should be capable of using its relational facilities (exclusively) to manage
the database.
Rule 1: The information rule : All information in the database is to be represented in one and only one
way. This is achieved by values in column positions within rows of tables.
Rule 2 : The guaranteed access rule : All data must be accessible with no ambiguity. This is achieved in
the RDBMS by using the primary key concept.
Rule 3: Systematic treatment of null values : The DBMS must allow each field to remain null. The null
can be stored in any field of any datatype.
Rule 4: Active online catalog based on the relational model : The authorized users can access the database
structure by using common language i.e. SQL.
IT Brainshapers 6 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Rule 5: The comprehensive data sublanguage rule : The system must support at least one relational
language that has simple syntax and transaction management facilities. It can be used in the application as
well as in the RDBMS systems.
Rule 6: The view updating rule : All views must be updatable by the system.
Rule 7: High-level insert, update, and delete : The system is able to insert, update and delete operations
fully. It can also perform the operations on multiple rows simultaneously.
Rule 8: Physical data independence : Changes to the physical storage structure must not require a change
to an application based on the structure.
Rule 9: Logical data independence : Changes to the logical level (tables, columns, rows, and so on) must
not require a change to an application based on the structure.
Rule 10: Integrity independence : All the Integrity constraints like primary key, unique key etc must be
specified separately from application programs and stored in the catalog.
Rule 11: Distribution independence : The distribution of portions of the database to various locations
should be invisible to users of the database.
Rule 12: The non subversion rule : If the system provides a low-level (record-at-a-time) interface, then
that interface cannot be used to subvert the system, for example, bypassing a relational security or
integrity constraint.
Note:- Any database management system which fulfills 6 or more than 6 rules can be considered as the
RDBMS.
Relational Data Structure
Entity:
Entity is an object that exists and is distinguishable from other objects.
e.g Employee
Entity Attribute Value
Name = Raj
Age = “27”
Entity Set: An entity set is a set of entities of the same type i.e. which share common properties or
attribute
Relation: All data and relationship are represented in a two dimensional table called relation. e.g. the table
shown in figure
A database constructed using relation is referred to as Relational database. Relational database is
constructed from flat arrangement of data items
In following fig there is Person Information. Relation that describe the Student by SNo, Name ,Class
Address
Student
Attribute SNo Name Class Address
1 Raj XI Udhampur
2 Sudha X Jammu
Tuple 3 Sudhir XII Kathua
4 Sita XI Jammu
5 Rahim X Udhampur
IT Brainshapers 7 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Properties of Relation
In a table ,the order of row is immaterial
Order of column is immaterial
In a table, there are no duplicate rows.
Each row of the table contains only one value
Each column is assigned with a distinct heading
Attribute: The column of table (relation) are called attributes.
Tuple : The rows of the table are called tuple .
Name: Name is represented by the title.
Cardinality: The no. of rows in the table is called cardinality.
Degree: The no. of column in the table is called degree.
Domain: A domain is a collection of all possible values from which for a given column or
attributes is drawn .e.g Class values (IX,X,XI,XII)
Student
SNo Name Class Address
6 Raj XI Udhampur
7 Sudha X Jammu
8 Sudhir XII Kathua
9 Sita XI Jammu
10 Rahim X Udhampur
Attribute: SNo,Name ,Class,Address.
Name: Student.
Cardinality: 5
Degree: 4
Types of Relation
There are two type of relation.
Base Relation
The base relations are those relations which are created prior to use. They are also called as „table‟ and
existing as Physical file.
Derived Relation
The derived relations are those relations which are derived from a base relation. They do not exist as
physical file .The derived relations are also called as Views.
Keys in DBMS
The key is defined as the column or attribute that exclusively identifies a record e.g. EmpNo, RollNo etc
are used as key fields because they identifies a record structure stored in a database of the database table.
For example if a table has id, name and address as the column names then each one is known as the key
for that table. We can also say that the table has 3 keys as id, name and address. The keys are also used to
identify each record in the database table. The following are the various types of keys available in the
DBMS system.
Consider a relation STUDENT, having column SRNo,RegNo,Name ,Class,City
SRNo RegNo Name Class City
S01 DSE101 X BCA Udhampur
S02 DSE102 Y BCA Reasi
S03 DSE103 Z BBA Jammu
S04 DSE104 W MCA Ramnagar
IT Brainshapers 8 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Primary Key
An attribute which recognizes tuple uniquely is called a primary key
e.g SRNo is a Primary key.
Primary key can have more than one attribute such as type of key is called Concatenate key
e.g FlightNumber + Date
Secondary Key
Secondary key recognize the tuple but not uniquely. So secondary key recognizes the set of records
(tuples) e.g. Name, Class and City are the Secondary keys in Student relation.
Candidate Key
There may be more than one attribute in a relation such that they recognize a tuple uniquely (i.e. each of
the attribute have the property of primary key).These attributes are called candidate key. In such case, one
of the candidate key is chosen to be Primary key. The remaining candidate keys are called a Alternate key.
There is one Primary key in a table e.g In STUDENT relation SRNo and RegNo are the candidate key.
Alternate Key
From the candidate keys, we choose one as the primary key. Now candidate key which do not primary key
is called alternate key.
e.g If we choose SRNo as a primary key, then RegNo is the alternate key.
Foreign Key
A foreign key is an attribute (or set of attributes) that appears (usually) as a non key attribute in one
relation and as a primary key attribute in another relation.
Employee
EmpNo Name Age DeptNo
E01 X 21 10
E02 U 22 20
E03 Z 26 30
E04 Y 23 10
Department
DeptNo DLocation
10 Jammu
20 Udhampur
30 Kathua
In the example DeptNo is a foreign key in Employee but it is Primary key in Department
Super Key
A set of attributes is called Super key, if it recognizes the tuple uniquely.
e.g. SRNo + Name + City is a super key.
Every relation has atleast one default superkey i.e. the set of all its attributes. A super key can have
redundant attributes. A primary key or a key is a minimal superkey i.e a super key from which we cannot
remove any attributes and still have the uniqueness property.
Relational Algebra
Relation Algebra uses a procedural query language which is collections of operations to manipulate
relations. It consist of a set of operations take one or more relations as input and produce new relation as
their result.
Relation algebra can be divided into two types of operations
Set Oriented Operation
a) Union b) Difference c) Intersection d) Cartesian Product
Relational Oriented Operation
a) Join b) Selection c) Projection d) Division
IT Brainshapers 9 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Set Operation
Set Union
The result of union operation is denoted by the symbol U.
e.g. X U Y(when X and Y are two compatible relations) is a relation that include all tuples that are either
in X or in Y or Both X and Y).Duplicate tuples would be eliminated by using set union
e.g if X and Y are two relation
X Y XUY
abc cif abc
def ghi def
ghi pqr ghi
ci f
pqr
We are able to eliminate the duplicate tuples namely ghi
Set Difference
The Set difference operation s is denoted by-.
e.g. X-Y is a relation which contains the tuples that are in one relation but are not in another relation
X Y X-Y
abc cif abc
def ghi def
ghi pqr
Set Intersection
The Set Intersection operations is denoted by ∩
e.g. X∩Y is a relation which contains the tuples that are present in both relations
X Y X-Y
abc cif ghi
def ghi
ghi pqr
Cartesian Product (Cross Product)
Cross Product is denoted by ×
e.g. X∩Y is a relation which contains the tuples that are present in both relations
X Y X×Y
abc cif abccif
def ghi abcghi
ghi pqr abcpqr
defc if
defghi
defpqr
ghic if
ghighi
ghipqr
Relation Oriented Operation
Select (σ)
The Select operation is denoted by Greek letters sigma (σ).It extracts specific tuples from a relation. One
can consider a Select operation to be filter that keeps only those tuple that satisfy a qualifying condition.
The general formula is
σ <selection condition>(relation name)
where σ denotes the Select operation.
<selection condition> is Boolean expression specified on the attribute.
IT Brainshapers 10 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Suppose we want to extract those tuples which have salary > 900 from Employee. This can be represented
as σ salary > 900 (Employee)
Project (π)
The Project operation is denoted by Greek letters Pi (π).It extracts attribute from a relation. We can use
project operation to be filter that keeps only those attribute that are required
The general formula is
π < attribute list> (relation name)
where π denotes the Project operation.
<attribute list> list of attribute to be needed.
Suppose we want to know the Name, Age from Employee relation. This can be represented as
π Name, Age (Employee)
Division
The division operation is denoted by ÷.The division of X by Y results in another relation table(say XY)
which has those records (tuples) whose domain(A1,A2,A3,A4…..) are appearing X and corresponding
domain(B1,B2,B3,B4…) are appearing in Y. The new relation would have domain A1, A2, A3….An
Language
Employee Language
English
Name Language
Punjabi
Sunil English
Jai Hindi
Sunil Punjabi
Rahim Oriya
The division of table Employee by table language means list of those employee who know both English,
Punjabi
Name Language
Sunil English
Sunil Punjabi
Normalization:
Normalization is step by step decomposition of complex record into simple records with no data loss.
Normalization is the name given to the process of simplifying the relationship among data elements in a
record .Normalization replaces a collection of data in a record structure by another record design which
is simpler more predictable and therefore more manageable .Data normalization is a set of rules and
techniques concerned with:
Identifying relationships among attributes.
Combining attributes to form relations.
Combining relations to form a database.
Need for Normalization: The normalization is required for the following reasons
1. It reduces and control data redundancies (duplication)
2. It improves the database design.
3. It helps to eliminate data anomalies where insertion, deletions and updates destroy the integrity of the
database.
4. It also helps to produce logically correct database.
IT Brainshapers 11 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
The first step towards Normalization is to convert E-R model into tables or Relations.
Normal Forms: A relation is said to be in a particular normal form if it satisfies the constraints set for the
form. There are various types of normal forms.
1. First Normal Form (1NF)
UNNORMALIZED
2. Second Normal Form (2NF) RELATION
3. Third Normal Form (3NF)
The 1NF, 2NF,3NF are originally defined by Dr EF Codd, Latter INF
Boyee and Cod introduced other normal forms called the Boyee 2NF
Codd Normal Form (BCNF).The other are 4NF and 5 NF
e.g Bill 3NF
Bill_No
Bill_Date
Cust_No
Cust_Name
Cust_Address
Item_No
Item _Name
Item_Qty as many Items can occur in the bill
Item_Rate
Item_Value
Total Bill_Value
1. First Normal Form (1NF) A relation is in 1NF if it does not contain repeating elements or group. In other
words all values in every column of the relation have to be atomic.
Bill Bill_Item
Bill_No Bill_No
Bill_Date Item_No
Cust_No Item_Name
Cust_Name Item_Qty
Cust_Address Item_Rate
Total Bill_Value Item_Value
2. Second Normal Form (2NF) : It‟s the first normal form where all non-key attribute are fully functionally
dependent on the whole primary key.e.g In the Bill file in the first normal form Cust_Name and Cust_Add
is only dependent on the Cust_Code and in the Bill_Item file the item_Name is just dependent on the
Item_Code and not on the Bill_No
Bill Cust Item Bill_Item
Bill_No Cust_No Item_No Bill_No
Bill_Date Cust_Name Item_Name Item_No
Cust_No Cust_Address Item_Rate Item_Qty
TotalBill_Value Item_Value
3. Third Normal Form (3NF):It‟s the second normal form where all non-key attribute are dependent on the
whole primary key and independent on each other.
e.g The TotalBill_Value in the Bill file and Item _Value of the Bill_Item can be computed from the
Item_Rate and Item_Qty.
Bill Cust Item Bill_Item
Bill_No Cust_No Item_No Bill_No
Bill_Date Cust_Name Item_Name Item_No
Cust_No Cust_Address Item_Rate Item_Qty
IT Brainshapers 12 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SQL
SQL (Structured Query Language) is a computer language aimed to store, manipulate, and query data
stored in relational databases. The first incarnation of SQL appeared in 1974, when a group in IBM
developed the first prototype of a relational database. The first commercial relational database was
released by Relational Software (later becoming Oracle).
SQL has been a command language for communication with the Oracle 9i Server from any tool or
application. Oracle SQL contains many extensions. When an SQL statement is entered, it is stored in a
part of memory called SQL buffer and remains there until a new SQL statement is entered
SQL *PLUS is an Oracle tool that recognizes and submits SQL statements to the Oracle9i Server for
execution. It contains its own command language.
Features of SQL
SQL can be used by a range of users, including those with little or no programming experience.
It is a non-procedural language.
It reduces the amount of time required for creating and maintaining systems.
It is English like language.
Advantages
High Speed
SQL queries are deigned to retrieve large amount of records from database quickly and efficiently, when
compared to non-SQL databases. The simple SQL queries can be used to retrieve even highly complicated
combination of data from the database.
Security
SQL provides security by using different constraints on the data, by providing logins and password, which
helps them to manage data efficiently.
Well-defined Standards Exists
SQL databases use the long-established SQL standard, which has been adopted by ANSI in 1986.Since
then, the standards have been continually evolving by the efforts of ANSI and ISO, the latest being SQL
2003.But the non-SQL databases do not have clear standards to adhere.
Compatibility
There are well-defined and established standards that exist, and if the databases adhere to them, then
portability from one SQL database to another is a trivial matter. An SQL database conforming to set
standards can be easily accesses by third party softwares and application tools. This will facilitate the
development of quantity applications and solutions around SQL databases
Non-requirement of Coding
Using standard SQL, it is easier to move applications between different database systems without the
necessity to rewrite a substantial amount of code.
Rules for SQL
SQL start with a verb (i.e. a SQL action word).Example SELECT statements. This verb may have
additional adjectives. Example: FROM.
Each verb is followed by number of clauses: Example FROM, WHERE, HAVING
A space separate clauses Example: DROP TABLE EMP;
A comma (,) separates parameters without a clause.
A; is used to end SQL statement.
Statement may be split across lines but keywords may not.
Lexical units such as identifiers, operator names, and literals are separated by one or more spaces or other
delimiters that will not confused with the lexical unit.
Reserved words cannot be used as identifier unless enclosed with double quotes.
IT Brainshapers 13 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Identifiers can contain up to 30 characters and must start with an alphabetic character.
Characters and date literal must be enclosed within single quotes.
Numeric literals can be represented by simple values such as 0.32,-34, 01991, and so on, scientific
notation as 2E5 meaning 2x10 to the power of 5=200,000.
Comments may be enclosed between /* and */ symbols and may be multiline. Single line comments may
be prefixed with a-symbol
SQL Delimiters
Delimiters are symbols or compound symbols which have special meaning with in SQL and PL/SQL
statement
+ Addition “ Quote identifier
- Subtraction : Host variable
* Multiplication ** Exponential
/ Division <>!= ^= Relational
=>< Relational <=>= Relational
() Expression or list := Assignment
; Terminator => Association
% Attribute indicator || Concatenation
, Item separator << Label
. Compound selector >> Label
@ Remote access selector -- Comment
„ Character string indicator /* */ Comane(Multiline)
Types of Database Language
There are three types of database languages .These are:
a) DDL(Data Definition Language)
b) DML(Data Manipulation Language)
c) DCL(Data Control Language)
DDL(Data Definition Language)
DDL is language used to define data and their relationship to other types of data. It is mainly used to
create files, databases, data dictionaries and tables within databases. In other word DDL defines the format
or schema of the database.
Functions The primary functions of DDL serves as to
Describes the schema and subschema of table.
Describes the fields in each records and record‟s logical name.
Describes the data type and name of the each field.
Indicate the key of the record
Provide means for associating related records or fields
Provide for logical and physical data interdependence.
Provide for data security restrictions
The SQL commands that are used to create database objects are known as Data Definition Language or
DDL. The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),
specify links between tables, and impose constraints between tables. The most important DDL statements
in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
IT Brainshapers 14 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
DML (Data Manipulation Language)
DML is a language which deals with the processing or manipulation of various database objects. It
provides for the program interface to open and close database, find records in files navigate through the
records, add new records, and change or delete existing records.
The SQL commands that are used to manipulate data within database objects are called data
manipulation Language or DML.
DML is used for performing the following operations:
Retrieving information stored in the database.
Inserting information into the database
Deleting the information from the database
Modifying information stored in the database
The two types of DML are:
Procedural DML
Procedural DMLs require a user to specify what data are needed and how to get those data
Declarative DML
Declarative DML require a user to specify what data are needed without specifying how to get
those data
Functions The primary functions of DDL serves as to
Provide techniques for data manipulation as deletion, replacement, retrieval ,sorting, or insertion of datat
on records
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
DCL (Data Control Language)
DCL is a language which is used to impose security features and thus prevents unauthorized access to data
in the database. Security is provided by granting or revoking privileges on a user. Privilege determines
whether or not a user can execute a given command or a command can be executed on specific groups of
data.
The SQL commands that are used to control the behaviour of database objects are called Data Control
Language or DCL.
Data types in SQL or SQL Data Type
Data type is a name or label for a set of values and some operations, which can be performed on set of
values .Data types restrict the kind of information that can be entered into fields
SQL recognizes four general types of data:
Character strings
Binary
Numerical
Decimal
Character Strings
The character string data type stores a sequence of bytes that represent alphanumeric data. It contains both
fixed length and variable length text (words or numbers).
Data Type Abbreviation Description Range
CHARACTER(n) CHAR(n) Character string, fixed length n. 1≤n≤15000
CHARACTER VARCHAR(n) Variable length character string, 1≤n≤15000
VARYING(n) maximum length n.
CHARACTER or CHAR
The CHARACTER (CHAR) data type stores string values of fixed length in a column.
The length of the CHAR data type can be specified as the length of the column when a table is created.
We can specify the length to be of any value between 1 and 15000
IT Brainshapers 15 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
CHARACTER VARYING or CHAR VARYING or VARCHAR
The CHARACTER VARYING abbreviated CHAR VARYING or VARCHAR data types, stores strings
of varying length.
The varying of the VARCHAR data type can be specified as the length of the column when a table is
created. We can specify the length to be of any value between 1 and 15000
Binary
The binary data types are for binary data (true /false).They store a sequence of bytes that do not represent
alphanumeric characters.
The binary data type category contains the following data types.
Data Type Abbreviation Description Range
BINARY(n) N/A Fixed length binary string, 1≤n≤15000
maximum length n.
BINARY(n) VARBINARY(n) Variable length binary string, 1≤n≤15000
VARYING(n) maximum length n.
NUMERICAL
Numerical data types includes integers and floating –point representations
The binary data type category contains the following data types.
Data Type Abbreviation Description Range
SMALLINT N/A Integral numerical, -32767 through 32767,
precision 5. Corresponds to a 2 bytes
,signed int.
INTEGER INT Integral numerical, -21473648 through
precision 10. 21473648, Corresponds to
a 4 bytes ,signed int.
BIGINT N/A Integral numerical, -9 223 372 036 854 775
precision 19. 808 through 21473648,
Corresponds to a 4 bytes
,signed int.
CREATE TABLE
The create command is used to create a new table and database. Using create command, any number of
columns can be created and the constraints are optional.
The SQL syntax for CREATE TABLE is
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... );
So, if we are to create the customer table specified as above, we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date) ;
IT Brainshapers 16 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Sometimes, we want to provide a default value for each column. A default value is used when you do not
specify a column's value when inserting data into the table. To specify a default value, add "Default
[value]" after the data type declaration. In the above example, if we want to default column "Address" to
"Unknown" and City to "Mumbai", we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50) default 'Unknown',
City char(50) default 'Mumbai',
Country char(25),
Birth_Date date)
DROP TABLE COMMAND
To remove the table physically we use DROP TABLE command. The form is as
Syntax Example
DROP TABLE table_name; DROP TABLE EMP;
Note: But before dropping a table it is necessary that all its rows must be deleted .A table with rows
cannot be deleted. We can delete the rows of a table using delete command
Alter Table
This command is used to change the table. We can add new column, change the data type of column or
drop any constraint using alter command.
Add clause Using ADD clause we can add new column into the table.
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
ADD( column_name datetype); ADD( EMP_AGE number(3,0);
Modify clause Using MODIFY keyword to modify the definition of an existing column..
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
MODIFY ( column_name datetype); MODIFY( EMP_AGE number(5,0);
Droping a Column To remove a column which is no longer required for your table ,you can use an
ALTER TABLE statement with the DROP COLUMN
Syntax Example
ALTER TABLE table_name ALTER TABLE EMP
DROP COLUMN column_name; DROP COLUMN EMP_AGE;
IT Brainshapers 17 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
The SQL SELECT Statement
The SELECT statement is used to select data from a database. The result is stored in a result table, called
the result-set.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
SELECT EMP_NO,EMP_NAME FROM EMP;
EMP_NO EMP_NAME
101 Raj
102 Vijay
103 Sudhir
104 Shekahar
SELECT * Example
Now we want to select all the columns from the "EMP" table.
We use the following SELECT statement:
SELECT * FROM EMP:
The asterisk (*) is a quick way of selecting all columns!
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
Where
The WHERE clause is used to extract only those records that fulfill a specified criterion
Next, we might want to conditionally select the data from a table. For example, we may want to only
retrieve emp_name with salary above 1500. To do this, we use the WHERE keyword. The syntax is as
follows:
SELECT "column_name"
FROM "table_name"
WHERE "condition"
IT Brainshapers 18 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
For example, to select all stores with sales above $1,000 in Table Store_Information,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
we key in,
SELECT EMP_NAME
FROM EMP
WHERE SALARY > 1500
Result:
EMP_NAME
Vijay
Sudhir
In
In SQL, there are two uses of the IN keyword, and this section introduces the one that is related to the
WHERE clause. When used in this context, we know exactly the value of the returned values we want to
see for at least one of the columns. The syntax for using the IN keyword is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
The number of values in the parenthesis can be one or more, with each values separated by comma.
Values can be numerical or characters. If there is only one value inside the parenthesis, this commend is
equivalent to
WHERE "column_name" = 'value1'
For example, we may wish to select all records for the Raj,Sudhir Table EMP,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we key in,
SELECT *
FROM EMP
WHERE EMP_NAME IN ('Raj', 'Sudhir')
IT Brainshapers 19 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
Result:
EMP_NO EMP_NAME Salary
101 Raj 1500
103 Sudhir 2000
105 Raj 1700
Between
Whereas the IN keyword help people to limit the selection criteria to one or more discrete values, the
BETWEEN keyword allows for selecting a range. The syntax for the BETWEEN clause is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
This will select all rows whose column has a value between 'value1' and 'value2'.
For example, we may wish to select view all salary information between 1500, and 2000, in Table EMP
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we key in,
SELECT *
FROM EMP
WHERE SALARY BETWEEN '1700' AND '2000';
Note that date may be stored in different formats in different databases.
Result:
EMP_NO EMP_NAME Salary
102 Vijay 1800
103 Sudhir 2000
105 Raj 1700
DISTINCT
The SELECT keyword allows us to grab all information from a column (or columns) on a table. This, of
course, necessarily means that there will be redundancies. What if we only want to select each DISTINCT
element? This is easy to accomplish in SQL. All we need to do is to add DISTINCT after SELECT. The
syntax is as follows:
SELECT DISTINCT "column_name" FROM "table_name"
For example, to select all distinct names in Table EMP,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
IT Brainshapers 20 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
we key in,
SELECT DISTINCT EMP_NAME FROM EMP
Result:
EMP_NAME
Raj
Vijay
Sudhir
Shekahar
Aggregate Functions
Since we have started dealing with numbers, the next natural question to ask is if it is possible to do math
on those numbers, such as summing them up or taking their average. The answer is yes! SQL has several
arithmetic functions, and they are:
AVG: Average of the column.
COUNT: Number of records.
MAX: Maximum of the column.
MIN: Minimum of the column.
SUM: Sum of the column.
The syntax for using functions is,
SELECT "function type" ("column_name") FROM "table_name"
MAX function
SQL uses the MAX function to find the maximum value in a column. The syntax for using the MAX
function is,
SELECT MAX("column_name") FROM "table_name"
For example, if we want to get the highest salary from the following table,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT MAX(Salary) FROM EMP
Result:
MAX(Salary)
2000
2000 represents the maximum value of all Salary entries: 1500, 1800, 2000, and 1000..
Min Function
SQL uses the MIN function to find the maximum value in a column. The syntax for using the MIN
function is,
IT Brainshapers 21 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SELECT MIN("column_name") FROM "table_name"
For example, if we want to get the lowest salary from the following table,
Table EMP
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT MIN(Salary) FROM EMP
MIN(Salary)
1000
1000 represents the minimum value of all Salary entries: 1500, 1800, 2000, and 1000.
AVG function
SQL uses the AVG() function to calculate the average of a column. The syntax for using this function is,
SELECT AVG("column_name") FROM "table_name"
For example, if we want to get the average of all salary from the following table,
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we would type in
SELECT AVG(Salary) FROM EMP
Result:
AVG(Salary)
1575
1575 represents the average of all Salary entries: (1500 + 1800 + 2000 + 1000) / 4.
COUNT Function
Another arithmetic function is COUNT. The COUNT ( ) function returns the number of rows that
matches a specified criteria. The syntax is,
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:
SELECT COUNT ("column_name") FROM "table_name"
For example, if we want to find the number of Emp_Name entries in our table,
EMP_NO EMP_NAME Salary
101 Raj 1500
102 Vijay 1800
103 Sudhir 2000
104 Shekahar 1000
105 Raj 1700
we'd key in
SELECT COUNT(EMP_NAME) FROM EMP
Result:
Count(EMP_NAME)
5
IT Brainshapers 22 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SQL COUNT (*) Syntax
The COUNT (*) function returns the number of records in a table:
SELECT COUNT (*) FROM table_name
SQL COUNT (DISTINCT column_name) Syntax
The COUNT (DISTINCT column_name) function returns the number of distinct values of the specified
column:
SELECT COUNT (DISTINCT column_name) FROM table_name
Note: COUNT (DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.
SELECT COUNT (DISTINCT EMP_NAME) FROM EMP
Result: Count(DISTINCT EMP_NAME)
3
Group By
Now we return to the aggregate functions. Remember we used the SUM keyword to calculate the total
sales for all stores? What if we want to calculate the total sales for each store? Well, we need to do two
things: First, we need to make sure we select the store name as well as total sales. Second, we need to
make sure that all the sales figures are grouped by stores. The corresponding SQL syntax is,
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Let's illustrate using the following table,
Table EMP
EMP_NAME Salary
Raj 1500
Vijay 1800
Sudhir 2000
Shekahar 1000
Raj 1700
We want to find total salary for each employee. To do so, we would key in,
SELECT EMP_NAME, SUM (Salary)
FROM EMP
GROUP BY EMP_NAME
EMP_NAME Salary
Raj 3200
Vijay 1800
Sudhir 2000
Shekahar 1000
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at
least one arithmetic operator appears in the SELECT statement. When that happens, we need to GROUP
BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithmetic
operator.
HAVING
Another thing people may want to do is to limit the output based on the corresponding sum (or any other
aggregate functions). For example, we might want to see only the stores with sales over $1,500. Instead of
using the WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is
reserved for aggregate functions. The HAVING clause is typically placed near the end of the SQL
statement, and a SQL statement with the HAVING clause may or may not include the GROUP BY
clause. The syntax for HAVING is,
IT Brainshapers 23 Sanjay-7889862407
12th Comp Science Unit 6: Databases and SQL Max Marks 10
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithmetic function condition)
Note: the GROUP BY clause is optional.
Let's illustrate using the following table,
Table EMP
EMP_NAME Salary
Raj 1500
Vijay 1800
Sudhir 2000
Shekahar 1000
Raj 1700
we would type,
SELECT EMP_NAME, SUM(SALARY)
FROM EMP
GROUP BY EMP_NAME
HAVING SUM(SALARY) > 2100
Result:
EMP_NAME SUM(Salary)
Raj 2300
IT Brainshapers 24 Sanjay-7889862407
12th Comp Science Unit 7 Boolean Logic Marks 10
Introduction to Boolean Algebra
Boolean Algebra was developed by a British mathematician, George Bool, for representing logical expressions
in a mathematical form. A logical expression that can have only two possible results, TRUE or FALSE. To
understand these expressions, let us look at some examples:
Do you know Boolean algebra?
Are you graduate?
All the above statement can have either TRUE or FALSE or YES/NO as possible answers. Boolean algebra is
based on this fact and hence the variables used here can have only one of the two values: either 0 or 1, where 0
denotes FALSE and 1 denotes TRUE.
As in mathematical expressions, the variables are combined with the help of certain mathematical operations
such as +,-,*, or /.Boolean algebra also uses operators, such as AND, OR, and NOT to form Boolean
expressions. Theses operators are called logical operators. The result of a Boolean expression is depicted in the
form of a table known as Boolean Variable and Constant
Boolean valued Quantities
When a variable is used in an algebraic formula, it is generally assumed that the variables may take any
numerical value .For example, in the formula 6A+ 6B= C, it is assumed that A, B, C may possess the value of
any of the real numbers.
But the binary values quantities can assume only one of the two possible values, i.e., true or false. These two
values may be represented by the symbols 0 and 1.
Example .In the equation A+B=C, each of the variables A, B and C can either have the values 0 or 1
Boolean Variables and Boolean Constants
Variable is a named container for data and this data can be changed .Boolean variables are binary values
quantities. Boolean variables can have any of the two vales: true (1) and false (0).
Constants are entries that have a specific fixed value. Boolean constants have affixed value i.e. either true (1)
or false (0)
As stated earlier, Boolean algebra is the algebra of statements .Statements are denoted by letters and referred
to as Boolean variables .A statement can have only two possible value T (signifies true) and F (signifies false)
Suppose A is a Boolean variable denoting ‘
The earth is not flat’, then most people wi
the value of A will be T but, Boolean algebra is not concerned with facts and reality. We define the facts ,and
boolean algebra helps in drawing conclusions from this facts .This means that Boolean algebra is a kind of
moths in which,when told that ‘the moon is squa
Truth Table
Truth table is a type of mathematical table used in logic, to determine whether an expression is true or false. A
logical statement, which contains a finite number of logical variables, can be analyzed using a table .The tables
that lists all possible values of the variables is called a truth table.
0 0 0 1 0 0 0 0
0 0 1 1 0 1 0 0
0 1 0 0 0 1 0 0
0 1 1 0 0 1 0 0
1 0 0 1 1 0 0 1
1 0 1 1 1 1 1 1
1 1 0 0 0 1 1 1
1 1 1 0 0 1 1 1
c) a b= a * b
d) (a b) * a * b =0
e) a+ a *b+ a * b =1
IT Brainshapers 5 Sanjay -7889862407
12th Comp Science Unit 7 Boolean Logic Marks 10
Laws of Boolean Algebra
The laws of Boolean algebra are very useful in simplifying logic at expressions or transforming them into other
useful equivalent expressions.
The different laws of Boolean algebra are
1. Closure Property
2. Commutative Law
3. Associative Law
4. Distributive Law
5. Identity Law
6. Inverse Law
7. Duality Theorem
8. Idempotent Law
9. Absorption Law
10. Involution Law
11. DeMorgan’s Law
Some of the basic operations to be considered in Boolean algebra are:
a+0 = a
a+1 = 1
a*0 = 0
a*1 = a
0`= 1
1`= 0
1. Closure Property
Closure property states that the operations (+) and (*) are closed; that is for all
X a,b Є
a + b ЄX
a * b ЄX
The Boolean system is closed with respect to a binary operator, for every pair of Boolean values, it produces a
boolean result.
For examples
1 + 0 = 1 ЄZ
1 * 0 = 0 ЄZ
Here the logical AND and OR is closed in the Boolean system: it accepts only Boolean operands and produces
only Boolean results.
Circuit Diagram
So, a * b = b * a
a+b=b+a
Proof using truth table
The statement a * b = b * a and a + b = b + a can be proved using the following truth table :
a b a*b b*a a+b b+a
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 0 1 1
1 1 1 1 1 1
As seen in the truth table, it is proved that
a+b = b+a
a*b = b*a
So, a + (b + c) = (a + b) + c
a * (b * c) =(a * b) * c
Proof using truth table
The statement a * (b * c) = (a * b) * c can be proved using the following truth table
a b c a*b b*c a * ( b * c) (a* b)*c
0 0 0 0 0 0 0
0 0 1 0 0 0 0
0 1 0 0 0 0 0
0 1 1 0 1 0 0
1 0 0 0 0 0 0
1 0 1 0 0 0 0
1 1 0 1 0 0 0
1 1 1 1 1 1 1
As seen in the truth table, it is proved that a * (b * c) = (a * b) * c
The statement a + (b + c) = (a + b) + c can be proved using the following truth table.
a b c a+b b +c a + ( b + c) (a+b)+c
0 0 0 0 0 0 0
0 0 1 0 1 1 1
0 1 0 1 1 1 1
0 1 1 1 1 1 1
1 0 0 1 0 1 1
As shown in the truth table, it is proved that a b = a * b and a * b = a + b since their values are equal.
A B A +B
0 0 0
0 1 1
1 0 1
1 1 1
The OR gate has two or more inputs .The output from the OR gate is 1 if any of the inputs is 1.The gate output
is 0 if only all inputs are 0.The output from the OR gate is written as A+B. A plus indicates OR operation.
The OR function can have any number of inputs to the AND gate. However, practical commercial OR gates are
mostly limited to 2,3 and 4 inputs .
NOT Gate
The NOT gate is similar to the NOT operation. This gate is unique, since it has only one input. The input to the
NOT gate A is inverted i.e., the binary input state of 0 gives an output of 1 ad the binary input state of 1 gives
an output of 0.
NOT gate is also known as an inverter because it changes the input to its opposite (inverts it).A common way of
using the NOT gate is to simplify attach the circle to the front of another gate.
The truth table and the circuit diagram for the NOT gate are as shown:
There is no limit to the number of inputs that may be applied to a NAND function, so there is no functional
limit to the number of inputs a NAND gate may have. However, for practical reasons, commercial NAND gates
are most commonly manufactured with 2, 3, or 4 inputs, to fit in a14-pin or 16-pin package
NOR Gate
The NOR gate is a combination of a NOT gate and an OR gate. In this, the output is 1 when all the inputs are 0
and in all other cases the output is 0.
The symbol is an OR gate with a small circle on the output. The small circle represents inversion.
The output from the AND gate is written as A B
The NOR function can have any number of inputs, but commercial NOR gates are mostly limited to 2, 3, and 4
inputs, as with other gates in this class, to fit in standard IC package.
XOR Gate
The exclusive –OR or XOR function is a useful variation on the basic OR function.Verbally, it can be stated as
either A or B, but not both. The XOR gate produces logic 1 output, only if its two inputs are different. If the
inputs are same, the output is logic 0.
The following illustration shows the circuit diagram and the truth table of the XOR gate. The XOR symbol is
variation on the standard OR symbol. The output from the XOR gate is represented by a symbol consisting of a
plus (+) sign with a circle around it i.e. A B
Unlike standard OR/NOR and AND/NAND functions, the XOR function always has exactly two inputs, and
commercially manufactured XOR gates are the same. Four XOR gates fit in a standard 14-pin IC package
Because of inversion on the output side, the truth table for a XNOR gate is the complement of the XOR truth
table. The output is 1 when the inputs are same. So the 2-input XNOR gate is immensely useful for bit
comparison, and it recognizes when the two input bits are identical.
The XNOR gate can have any number of inputs.