Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
1. Introduction
2. Disadvantages of file oriented approach
3. Database
4. Why Database
5. Database Management System(DBMS)
6. Function of DBMS
7. Advantages of DBMS and disadvantage of DBMS
8. Database Basics
9. Three level architecture of DBMS
10. Database users
11. Database language
12. Database structure
Introduction:
What is data:
Data is the known facts or figures that have implicit meaning. It can also be defined as it
is the representation of facts ,concepts or instruction in a formal manner, which is suitable
for understanding and processing. Data can be represented in alphabets(A-Z, a-z),in
digits(0-9) and using special characters(+,-.#,$, etc) e.g: 25, “ajit” etc.
Information:
Information is the processed data on which decisions and actions are based. Information
can be defined as the organized and classified data to provide meaningful values.
File:
File is a collection of related data stored in secondary memory.
File Oriented approach:
The traditional file oriented approach to information processing has for each application a
separate master file and its own set of personal file. In file oriented approach the program
dependent on the files and files become dependent on the files and files become
dependents upon the programs
Disadvantages of file oriented approach:
1) Data redundancy and inconsistency:
The same information may be written in several files. This redundancy leads to
higher storage and access cost. It may lead data inconsistency that is the various
copies of the same data may longer agree for example a changed customer
address may be reflected in single file but not else where in the system.
3) Data isolation :
Because data are scattered in various file and files may be in different formats
with new application programs to retrieve the appropriate data is difficult.
4) Integrity Problems:
Developers enforce data validation in the system by adding appropriate code in
the various application program. How ever when new constraints are added, it is
difficult to change the programs to enforce them.
5) Atomicity:
Database:
A database is organized collection of related data of an organization stored in
formatted way which is shared by multiple users. The main feature of data in a
database are:
1. It must be well organized
2. it is related
3. It is accessible in a logical order without any difficulty
4. It is stored only once
for example:
consider the roll no, name, address of a student stored in a student file. It is collection of
related data with an implicit meaning.
Data in the database may be persistent, integrated and shared.
Persistent:
If data is removed from database due to some explicit request from user to remove.
Integrated:
A database can be a collection of data from different files and when any redundancy
among those files are removed from database is said to be integrated data.
Sharing Data:
The data stored in the database can be shared by multiple users simultaneously with out
affecting the correctness of data.
Why Database:
In order to overcome the limitation of a file system, a new approach was required.
Hence a database approach emerged. A database is a persistent collection of logically
related data. The initial attempts were to provide a centralized collection of data. A
database has a self describing nature. It contains not only the data sharing and integration
of data of an organization in a single database.
A small database can be handled manually but for a large database and having
multiple users it is difficult to maintain it, In that case a computerized database is useful.
The advantages of database system over traditional, paper based methods of record
keeping are:
compactness:
No need for large amount of paper files
speed:
The machine can retrieve and modify the data more faster way then human being
Less drudgery: Much of the maintenance of files by hand is eliminated
Accuracy: Accurate,up-to-date information is fetched as per requirement of the
user at any time.
Function of DBMS:
1. Defining database schema: it must give facility for defining the database
structure also specifies access rights to authorized users.
2. Manipulation of the database: The dbms must have functions like insertion of
record into database updation of data, deletion of data, retrieval of data
3. Sharing of database: The DBMS must share data items for multiple users by
maintaining consistency of data.
4. Protection of database: It must protect the database against unauthorized users.
5. Database recovery: If for any reason the system fails DBMS must facilitate data
base recovery.
Advantages of dbms:
Reduction of redundancies:
Centralized control of data by the DBA avoids unnecessary duplication of data and
effectively reduces the total amount of data storage required avoiding duplication in the
elimination of the inconsistencies that tend to be present in redundant data files.
Sharing of data:
A database allows the sharing of data under its control by any number of application
programs or users.
Data Integrity:
Data integrity means that the data contained in the database is both accurate and
consistent. Therefore data values being entered for storage could be checked to ensure
that they fall with in a specified range and are of the correct format.
Data Security:
The DBA who has the ultimate responsibility for the data in the dbms can ensure that
proper access procedures are followed including proper authentication schemas for access
to the DBS and additional check before permitting access to sensitive data.
Conflict resolution:
DBA resolve the conflict on requirements of various user and applications. The DBA
chooses the best file structure and access method to get optional performance for the
application.
Data Independence:
Data independence is usually considered from two points of views; physically data
independence and logical data independence.
Physical data Independence allows changes in the physical storage devices or
organization of the files to be made without requiring changes in the conceptual view or
any of the external views and hence in the application programs using the data base.
Logical data independence indicates that the conceptual schema can be changed without
affecting the existing external schema or any application program.
Disadvantage of DBMS:
1. DBMS software and hardware (networking installation) cost is high
2. The processing overhead by the dbms for implementation of security, integrity
and sharing of the data.
3. centralized database control
4. Setup of the database system requires more knowledge, money, skills, and time.
5. The complexity of the database may result in poor performance.
Database Basics:
Data item:
The data item is also called as field in data processing and is the smallest unit of data
that has meaning to its users.
Eg: “e101”,”sumit”
An entity is a thing or object in the real world that is distinguishable from all other
objects
Eg:
Bank,employee,student
Attributes are properties are properties of an entity.
Eg:
Empcode,ename,rolno,name
Logical data are the data for the table created by user in primary memory.
Physical data refers to the data stored in the secondary memory.
A subschema is derived schema derived from existing schema as per the user
requirement. There may be more then one subschema create for a single conceptual
schema.
Conceptual
level Mapping supplied by DBMS
Conceptual view
Internal level
A database management system that provides three level of data is said to follow three-
level architecture .
External level
Conceptual level
Internal level
External level :
The external level is at the highest level of database abstraction . At this level, there will
be many views define for different users requirement. A view will describe only a subset
of the database. Any number of user views may exist for a given global or subschema.
for example , each student has different view of the time table. the view of a student of
Btech (CSE) is different from the view of the student of Btech(ECE).Thus this level of
abstraction is concerned with different categories of users.
Each external view is described by means of a schema called schema or
schema.
Conceptual level :
At this level of database abstraction all the database entities and the
relationships among them are included . One conceptual view represents the entire
database . This conceptual view is defined by the conceptual schema.
The conceptual schema hides the details of physical storage structures and concentrate on
describing entities , data types, relationships, user operations and constraints.
It describes all the records and relationships included in the conceptual view
. There is only one conceptual schema per database . It includes feature that specify the
checks to relation data consistency and integrity.
Internal level :
It is the lowest level of abstraction closest to the physical storage method used . It
indicates how the data will be stored and describes the data structures and access methods
to be used by the database . The internal view is expressed by internal schema. The
following aspects are considered at this level:
1. Storage allocation e.g: B-tree,hashing
2. access paths eg. specification of primary and secondary keys,indexes etc
3. Miscellaneous eg. Data compression and encryption techniques,optimization of
the internal structures.
Database users :
Naive users :
Users who need not be aware of the presence of the database system or any other
system supporting their usage are considered naïve users . A user of an automatic teller
machine falls on this category.
Online users :
These are users who may communicate with the database directly via an online
terminal or indirectly via a user interface and application program. These users are aware
of the database system and also know the data manipulation language system.
Application programmers :
Database Administration :
A person who has central control over the system is called database administrator .
The function of DBA are :
1. creation and modification of conceptual Schema
definition
2. Implementation of storage structure and access method.
3. schema and physical organization modifications .
4. granting of authorization for data access.
5. Integrity constraints specification.
6. Execute immediate recovery procedure in case of failures
7. ensure physical security to database
Database language :
Elements of DBMS:
DML pre-compiler:
DDL compiler:
The DDL compiler converts the data definition statements into a set of tables. These
tables contains information concerning the database and are in a form that can be used by
other components of the dbms.
File manager:
File manager manages the allocation of space on disk storage and the data structure used
to represent information stored on disk.
Database manager:
A database manager is a program module which provides the interface between the low
level data stored in the database and the application programs and queries submitted to
the system.
The responsibilities of database manager are:
1. Interaction with file manager: The data is stored on the disk using the file
system which is provided by operating system. The database manager
translate the the different DML statements into low-level file system
commands. so The database manager is responsible for the actual
storing,retrieving and updating of data in the database.
2. Integrity enforcement:The data values stored in the database must satisfy
certain constraints(eg: the age of a person can't be less then zero).These
constraints are specified by DBA. Data manager checks the constraints and if
it satisfies then it stores the data in the database.
3. Security enforcement:Data manager checks the security measures for
database from unauthorized users.
4. Backup and recovery:Database manager detects the failures occurs due to
different causes (like disk failure, power failure,deadlock,s/w error) and
restores the database to original state of the database.
5. Concurrency control:When several users access the same database file
simultaneously, there may be possibilities of data inconsistency. It is
responsible of database manager to control the problems occurs for concurrent
transactions.
query processor:
The query processor used to interpret to online user’s query and convert it into an
efficient series of operations in a form capable of being sent to the data manager for
execution. The query processor uses the data dictionary to find the details of data file
and using this information it create query plan/access plan to execute the query.
Data Dictionary:
Data dictionary is the table which contains the information about database objects. It
contains information like
1. external, conceptual and internal database description
2. description of entities , attributes as well as meaning of data elements
3. synonyms, authorization and security codes
4. database authorization
The data stored in the data dictionary is called meta data.
DBMS STRUCTURE:
Database manager
File manager
DBMS
Data file
Data dictionary
Answer: Some main differences between a database management system and a file-
processing system are:
• Both systems contain a collection of data and a set of programs which access that
data. A database management system coordinates both the physical and the logical
access to the data, whereas a file-processing system coordinates only the physical
access.
• A database management system reduces the amount of data duplication by
ensuring that a physical piece of data is available to all programs authorized to
have access to it, where as data written by one program in a file-processing
system may not be readable by another program.
• A database management system is designed to allow flexible access to data (i.e.,
queries), whereas a file-processing system is designed to allow predetermined
access to data (i.e., compiled programs).
• A database management system is designed to coordinate multiple users accessing
the same data at the same time. A file-processing system is usually designed to
allow one or more programs to access different data files at the same time. In a
file-processing system, a file can be accessed by two programs concurrently only
if both programs have read-only access to the file.
Answer:
• Physical data independence is the ability to modify the physical scheme without
making it necessary to rewrite application programs. Such modifications include
changing from unblocked to blocked record storage, or from sequential to random
access files.
• Logical data independence is the ability to modify the conceptual scheme without
making it necessary to rewrite application programs. Such a modification might
be adding a field to a record; an application program’s view hides this change
from the program.
Q. List six major steps that you would take in setting up a database for a particular
enterprise.
Answer: Six major steps in setting up a database for a particular enterprise are:
• Define the high level requirements of the enterprise (this step generates a
document known as the system requirements specification.)
• Define a model containing all appropriate types of data and data
relationships.
• Define the integrity constraints on the data.
• Define the physical level.
• For each known problem to be solved on a regular basis (e.g., tasks to be
carried out by clerks or Web users) define a user interface to carry out the
task, and write the necessary application programs to implement the user
interface.
• Create/initialize the database.
EXERCISES:
This architecture has different usages with different applications. It can be used in
web applications and distributed applications. The strength in particular is when using
this architecture over distributed systems. In this course work, I will furthermore
invest this through the example of three-tier architecture in web applications.
Structure
Using this architecture the software is divided into 3 different tiers: Presentation
tier, Logic tier, and Data tier. Each tier is developed and maintained as an
independent tier.
1-Presentation tier
This is the topmost level of the application. The presentation layer provides the
application’s user interface (UI). Typically, this involves the use of Graphical User
Interface for smart client interaction, and Web based technologies for browser-based
interaction. The presentation tier displays information related to such services as
browsing merchandise, purchasing, and shopping cart contents. It communicates with
other tiers by outputting results to the browser/client tier and all other tiers in the
network.
2-Logic tier (called also business logic, data access tier, or middle tier)
The logic tier is pulled out from the presentation tier and, as its own layer; it
controls an application’s functionality by performing detailed processing. Logic tier is
where mission-critical business problems are solved. The components that make up
this layer can exist on a server machine, to assist in resource sharing. These
components can be used to enforce business rules, such as business algorithms and
legal or governmental regulations, and data rules, which are designed to keep the data
structures consistent within either specific or multiple databases. Because these
middle-tier components are not tied to a specific client, they can be used by all
applications and can be moved to different locations, as response time and other rules
require. For example, simple edits can be placed on the client side to minimize
network round-trips, or data rules can be placed in stored procedures.
3-Data tier
This tier consists of database servers, is the actual DBMS access layer. It can be
accessed through the business services layer and on occasion by the user services
layer. Here information is stored and retrieved. This tier keeps data neutral and
independent from application servers or business logic. Giving data its own tier also
improves scalability and performance. This layer consists of data access components
(rather than raw DBMS connections) to aid in resource sharing and to allow clients to
be configured without installing the DBMS libraries and ODBC drivers on each
client. An example would be a computer hosting a database management system
(DBMS), such as a Microsoft SQL Server database.
Components Interconnections:
Logic layer is moved outside the presentation layer and into the business layer as it
enhances reuse. As applications grow, applications often grow into other realms.
Applications may start out as a web application, but some of the functionality may
later be moved to a smart client application. Portions of an application may be split
between a web site and a web or windows service that runs on a server. In addition,
keeping logic helps aid in developing a good design (sometimes code can get sloppier
in the UI).
Consider the 3-tier architectural style if the processing requirements of the layers in
the application differ such that processing in one layer could absorb sufficient
resources to slow the processing in other layers, or if the security requirements of the
layers in the application differ. For example, the presentation layer should not store
sensitive data, while this may be stored in the business and data layers. The 3-tier
architectural style is also appropriate if you want to be able to share business logic
between applications, and you have sufficient hardware to allocate the required
number of servers to each tier.
The first client server architecture being developed is the file server architecture., all
processing will be done at the PC that requested the data that is client handles the
presentation logic, the processing logic and much of the storage logic. That means out
of t he hundred percent work that need to be done every logics that we have seen
application logics that we have seen like presentation ;logic, processing logic and
storage logic more than 80% of the job it will be carried out at the client side itself. So
that is what I am trying to say here. All processing is done at the PC that requested the
data that is client handles the presentation ;logic processing logic and much of the
storage logic. A file server is a device that manage sonly the file operation and shared
by each of the client PCs attached to the local area network. Each filer server acts as a
n additional hard disk so wherever I am talking about a file server every file server
will be ac5ring as an extra hard disk which will be present not only at the server level
and which will also be present at the client side. For each of the client PC. Each PC
maybe called a fat client because this client does an extensive work based on that I am
calling this client as a fat client so most of the processing since it happens at the client
side it is called fat client. Entire file are transferred from the server to the client for
processing. So anything that the client has requested that query will be taken by the
server and the server will respond all the possible states back to the server without any
processing and client after the client receives all the service or the files requested for
processing the client executes everything and it will be called a process.
So this is the complete architecture of a file se rver system where if you look at the
machine all the clients are connected by a local area network to a file server this file
server in turn manages all the data. So if you look at the major responsibility of a
client and the responsibilities of the server, client does processing and scanning of
tables, client does application program user interface not only that client does data
processing, client generates queries, handles integrity that means it checks of the
validation of the data and it also checks for the identification of from which node it
has come from so it also have to handle security aspects of it. So that means almost all
the processes taking at the client level so it maintains only a copy of DBMS that is
available in the server. At the same side, if you look at the file server architecture the
file server looks after the storage of all the files and locking of records acts like an
extra hard disk to the client and this will not be very busy because many a times I am
not transferring all the information from the server’s end I am transferring the
information to the client and I don’t process the information. So it is not very busy
and it has got significant LAN traffic. So when you look at the e ntire architecture
although many machines are connected to the server the responsibility of the serve r
will any request that I get form different client machine is push all the data from my
end to the client’s side. It is a responsibility of a client to take up all the data that is
available in the server p rocess whatever which is required for the client to execute
those will be done at the client by itself. So if you look at the networking system the
client can request for a data, request to log the data and from the server it will be
given back where the entire file of the data will be transferred to the client and the
lock status will also be given to the client. Say lock like read, write locks once the
client request it means it is trying to read from the server so it locks. so whatever
information that is to be read, maybe it could be put as a shared lock or a n exclusive
lock where in case of a shared lock many clients can request to a server, what are the
information that the client request to read from the server and if it is to be an exclusive
lock if it is from the client’s end it will be locked at the server then the client after
transferring all the information to the client then the lock will be released. So those
information will be handled at the server’s end. So as I have already told you this filer
server architecture since most of the work is carried out at the client end, that is out of
100% of the job 80% of the work is being done at the client’s end, so I call these type
of machine as fat client machines.
Every system will have its own drawbacks. There are a few drawbacks wherein case
because of transfer of information from the server to the client as requested there will
be a huge amount of data transfer on the network because when an client wants to
access a whole data table, in case a client wants a whole data table to processing a
simple information then the whole data will be transferred from the server to the
client. So this has to be transferred to the PC so the server is doing very little work
that means serve locate where the table is transfers the entire table to the entire table
to the client machine. So server does only little work, network is transferring large
blocks of data and the client is being busy processing all the data with an extensive
data manipulations. The second issue that raises because of the file server architecture,
each client is authorized to use database management system, when a DB program
runs particularly on that PC. Thus there is one database but many concurrently
running copies of DBMS. The DBMS copy I each client PC must manage the shared
database integrity. So programmers must be sophisticated to recognize various subtle
conditions that can arise in a multiple user database environment.
It is similar to data warehouse where the website store or maintain their data
and information. A Database Server is a computer in a LAN that is dedicated to
database storage and retrieval. The database server holds the Database Management
System (DBMS) and the databases. Upon requests from the client machines, it
searches the database for selected records and passes them back over the network.
A database server can be defined as a server dedicated to providing database
services. Such a server runs the database software. A database server can typically be
seen in a client-server environment where it provides information sought by the client
systems.
A database server is useful for organizations that have a lot of data to deal with on a
regular basis. If you have client-server architecture where the clients need process
data too frequently, it is better to work with a database server. Some organizations use
the file server to store and process data. A database server is much more efficient than
a file server.
In Database Network the client execute SQL requests to the database server. The
Network Database Server Process the client database request and the executed
answers of SQL command are come back over the network computer. In the whole
concept Database server serves its own power to process the request or search the
requested result. The Database server some time also known as SQL engine.
All database functions are controlled by the database server. Any type of computer
can be used as database server. It may be microcomputer, minicomputer or mainframe
computer. In large organization networks, the mainframe computers are used as
server.
Some people refer to the central DBMS functions as the back-end functions,
whereas the application programs on the client computer as front -end programs. You
can say that client is the application, which is used to interface with the DBMS, while
database server is a DBMS.
The Database server manages the recovery security services of the DBMS. It
enforces the constraints that are specified inside the DBMS. It controls and manages
all the clients that are connected to it. It handles all database access and control
functions.
It provides concurrent access control. It provides better security and server hides the
DBMS from clients. It provides the multi-user environment. Several users can access
the database simultaneously. All the data is stored on the data server therefore, the
DBA can easily create the backup of the database.
A standard called ODBC (Open Database Connectivity) provides an application
programming interface (API), which allows client side programs to call the DBMS on
the server side. For this purpose, necessary software should be installed on both sides
(i.e., client and server). Hence, a client program connects to the Database server and
sends requests (queries) using the ODBC Application Programming Interface (API).
The-server processes the queries and sends back the results of queries to the client
program, which are processed by the client computer
In the presentation layer the user interaction takes place as defined before. The user
enters the address in the web browser and in the browser the URL is decoded into
protocol/host/file, i.e. host name converted to IP address. Then an issue request is sent
to remote server using appropriate protocol (usually HTTP).
Also a returned HTML from the logic tier might be accepted. In the presentation
layer interaction with client side scripts (e.g. using DHTML) is supported and user
inputer of variety controls on the form are accepted.
2. Logic Tier
With Server (Apache or IIS) the appropriate action to be taken is identified, such as
fetching a file, or passing request to an interpreter. Also it sends an output back to
caller in MIME package. As such support for thousands for concurrent users,
multithreading (allow multiple processor to run concurrently) and caching (holding
results in a temporary store to reduce recalculation) is achieved).
With Server script (example in PHP) interacting with server such as accessing
input or generating input is done. It interprets the requests according to business rules
and past transactions from this client, and requests appropriate data from the
persistence layer. It also computes the derived data and creates HTML (or GIF…) for
the page.
3. Data Layer
This tier consists of database servers. The interaction with the database is done
using standard languages such as SQL queries using database specific protocol over
TCP/IP. The data structures (for example tables) are defined and modified themselves,
that insertion, updating and deleting of data for example. Data maintenance should be
maintained with backup and recovered. Access to compilation of queries should be
optimized, with indexing or replication of tables. An example of technology using this
would be .NET that is built into the .NET framework, as ADO.NET contains a
mechanism to query data out of the database and return it to the caller in a connected
or disconnected fashion.
Real life example of a web system explained above would be in Emails done using
3 Tier Architecture. Reading e-mail using a Web-based interface, such as Hotmail,
uses a three-tier architecture. The three tiers are:
1. Presentation Layer: The client’s web browser that sends HTTP requests to the
2. Logic Layer: The Web server:
a. sends HTTP responses to the Web client
b. Translates the client’s HTTP requests into SMTP packets which are then sent to
the Mail server.
3. Data Layer: The Mail server performs the following functionality, and when
performed it is transformed to the Logic Layer.
a. When completed, an e-mail message is sent by the sender’s e-mail client as
an SMTP packet to the local mail server.
b. The mail server’s message transfer agent next reads the packet’s destination
address and sends it over the Internet to the receiver’s mail server.
c. The destination mail transfer agent then stores the message in the receiver’s
mail box.
d. When the receiver next accesses e-mail, his or her user agent contacts the local
mail server which then downloads the message to the receiver ’s client computer.
ER-MODEL
Data model:
The data model describes the structure of a database. It is a collection of conceptual tools
for describing data, data relationships and consistency constraints and various types of
data model such as
1. Object based logical model
2. Record based logical model
3. Physical model
The entity-relationship data model perceives the real world as consisting of basic objects,
called entities and relationships among these objects. It was developed to facilitate data
base design by allowing specification of an enterprise schema which represents the
overall logical structure of a data base.
Main features of ER-MODEL:
• Entity relationship model is a high level conceptual model
• It allows us to describe the data involved in a real world enterprise in terms of
objects and their relationships.
• It is widely used to develop an initial design of a database
• It provides a set of useful concepts that make it convenient for a developer to
move from a baseid set of information to a detailed and description of information
that can be easily implemented in a database system
• It describes data as a collection of entities, relationships and attributes.
Basic concepts:
The E-R data model employs three basic notions : entity sets, relationship sets and
attributes.
Entity sets:
An entity is a “thing” or “object” in the real world that is distinguishable from all other
objects. For example, each person in an enterprise is an entity. An entity has a set
properties and the values for some set of properties may uniquely identify an entity.
BOOK is entity and its properties(calles as attributes) bookcode, booktitle, price etc .
An entity set is a set of entities of the same type that share the same properties, or
attributes. The set of all persons who are customers at a given bank, for example, can be
defined as the entity set customer.
Attributes:
Customer is an entity and its attributes are customerid, custmername, custaddress etc.
An attribute as used in the E-R model , can be characterized by the following attribute
types.
a) Simple and composite attribute:
simple attributes are the attributes which can’t be divided into sub parts
eg: customerid,empno
composite attributes are the attributes which can be divided into subparts.
eg: name consisting of first name, middle name, last name
address consisting of city,pincode,state
b) single-valued and multi-valued attribute:
The attribute having unique value is single –valued
attribute eg: empno,customerid,regdno etc.
The attribute having more than one value is multi-valued
attribute eg: phone-no, dependent name, vehicle
c) Derived Attribute:
The values for this type of attribute can be derived from the values of existing
attributes
eg: age which can be derived from (currentdate-birthdate)
experience_in_year can be calculated as (currentdate-joindate)
Consider the two entity sets customer and loan. We define the relationship set borrow to
denote the association between customers and the bank loans that the customers have.
Mapping Cardinalities:
Mapping cardinalities or cardinality ratios, express the number of entities to which
another entity can be associated via a relationship set.
Mapping cardinalities are most useful in describing binary relationship sets, although
they can contribute to the description of relationship sets that involve more than two
entity sets.
For a binary relationship set R between entity sets A and B, the mapping cardinalities
must be one of the following:
one to one:
One to many:
1 M
Course Teach Faculty
es
Many –to-many:
Entities in A and B are associated with any number of entities from each other.
1 M
Customer Depos Account
it
Keys:
Super key:
A super key is a set of one or more attributes that taken collectively, allow us to
identify uniquely an entity in the entity set.
For example , customer-id,(cname,customer-id),(cname,telno)
Candidate key:
In a relation R, a candidate key for R is a subset of the set of attributes of R, which
have the following properties:
• Uniqueness:no two distinct tuples in R have the same values for the
candidate key
• Irreducible:No proper subset of the candidate key has the uniqueness
property that is the candidate key.
Eg: (cname,telno)
Primary key:
The primary key is the candidate key that is chosen by the database designer as the
principal means of identifying entities with in an entity set. The remaining candidate
keys if any, are called alternate key.
ER-DIAGRAM:
The overall logical structure of a database using ER-model graphically with the help
of an ER-diagram.
Symbols use ER- diagram:
entity
Weak entity
composite attribute
attribute Relationship
1 1 1 m
One-to -one One-to -many
m 1 m n
many-to -one many-to -many
employee
Generalization Specialization
Is Is
degree degree
Is Is Is Is
EMPLOYEE(empno,name,dob) Faculty(empno,degree,intrest)
FULL_TIME_EMPLOYEE(empno,sala Staff(empno,hour-rate)
ry) Teaching (empno,stipend)
PART_TIME_EMPLOYEE(empno,type)
Aggregation:
Aggregation is the process of compiling information on an object, there by abstracting a
higher level object. In this manner, the entity person is derived by aggregating the
characteristics of name, address, ssn. Another form of the aggregation is abstracting a
relationship objects and viewing the relationship as an object.
Job
Branch
Employe Works
on
Manag
es
Manager
ER- Diagram For College Database
Head
name dnam of 1 name sal
1
addres relationship
Date
DEPARTMENT(D_NO,D_NAME,HEAD_ID,DATE_FROM)
• One-to-many relationship:
For each 1:n relationship type R involving two entities E1 and E2, we identify the
entity type (say E1) at the n-side of the relationship type R and include primary
key of the entity on the other side of the relation (say E2) as a foreign key
attribute in the table of E1. We include all simple attribute(or simple components
of a composite attribute of R(if any) in he table E1) For example:
The works in relationship between the DEPARTMENT and FACULTY. For this
relationship choose the entity at N side, i.e, FACULTY and add primary key
attribute of another entity DEPARTMENT, ie, DNO as a foreign key attribute in
FACULTY.
• Many-to-many relationship:
For each m:n relationship type R, we create a new table (say S) to represent R,
We also include the primary key attributes of both the participating entity types as
a foreign key attribute in s. Any simple attributes of the m:n relationship type(or
simple components as a composite attribute) is also included as attributes of S.
For example:
The M:n relationship taught-by between entities COURSE; and FACULTY shod
be represented as a new table. The structure of the table will include primary key
of COURSE and primary key of FACULTY entities.
TAUGHT-BY(ID (primary key of FACULTY table),course-id (primary key of
COURSE table)
• N-ary relationship:
For each n-anry relationship type R where n>2, we create a new table S to
represent R, We include as foreign key attributes in s the primary keys of the
relations that represent the participating entity types. We also include any simple
attributes of the n-ary relationship type(or simple components of complete
attribute) as attributes of S. The primary key of S is usually a combination of all
the foreign keys that reference the relations representing the participating entity
types.
Customer Loan
Loan -
sanctio
Employee
LOAN-SANCTION(cusomet-id,loanno,empno,sancdate,loan_amount)
• Multi-valued attributes:
For each multivalued attribute ‘A’, we create a new relation R that includes an
attribute corresponding to plus the primary key attributes k of the relation that
represents the entity type or relationship that has as an attribute. The primary key
of R is then combination of A and k.
For example, if a STUDENT entity has rollno,name and phone number where
phone numer is a multivalued attribute the we will create table
PHONE(rollno,phoneno) where primary key is the combination,In the STUDENT
table we need not have phone number, instead if can be simply (rollno,name)
only.
PHONE(rollno,phoneno)
name
Account_n
Account branch
generalisation
specialisation
Is-a
intrest charges
Saving Current
Hierarchical Model:
Single Relationships:
Example E-R diagram with two entity sets, customer and account, related through
a binary, one-to-many relationship depositor.
Corresponding tree-structure diagram has
o the record type customer with three fields: customer-name, customer-
street, and customer-city.
o the record type account with two fields: account-number and balance
o the link depositor, with an arrow pointing to customer
If the relationship depositor is one to one, then the link depositor has two arrows.
Only one-to-many and one-to-one relationships can be directly represented in the
hierarchical mode.
Must consider the type of queries expected and the degree to which the database
schema fits the given E-R diagram.
In all versions of this transformation, the underlying database tree (or trees) will
have replicated records.
Create two tree-structure diagrams, T1, with the root customer, and T2, with
the root account.
In T1, create depositor, a many-to-one link from account to customer.
In T2, create account-customer, a many-to-one link from customer to account.
Virtual Records:
For many-to-many relationships, record replication is necessary to preserve the
tree-structure organization of the database.
o Data inconsistency may result when updating takes place
o Waste of space is unavoidable
Virtual record — contains no data value, only a logical pointer to a particular
physical record.
When a record is to be replicated in several database trees, a single copy of that
record is kept in one of the trees and all other records are replaced with a virtual
record.
Let R be a record type that is replicated in T1, T2, . . ., Tn. Create a new virtual
record type virtual-R and replace R in each of the n – 1 trees with a record of type
virtual-R.
Eliminate data replication in the diagram shown on page B.11; create virtual-
customer and virtual-account.
Replace account with virtual-account in the first tree, and replace customer with
virtual-customer in the second tree.
Add a dashed line from virtual-customer to customer, and from virtual-account to
account, to specify the association between a virtual record and its corresponding
physical record.
Network Model:
Data are represented by collections of records.
o similar to an entity in the E-R model
o Records and their fields are represented as record type
end end
Relationships among data are represented by links
o similar to a restricted (binary) form of an E-R relationship
o restrictions on links depend on whether the relationship is many-many,
many-to-one, or one-to-one.
1. Replace entity sets account, customer, and branch with record types account,
customer, and branch, respectively.
2. Create a new record type Rlink (referred to as a dummy record type).
3. Create the following many-to-one links:
o CustRlink from Rlink record type to customer record type o
AcctRlnk from Rlink record type to account record type
o BrncRlnk from Rlink record type to branch record type
The DBTG CODASYL Model:
o All links are treated as many-to-one relationships.
o To model many-to-many relationships, a record type is defined to represent the
relationship and two links are used.
DBTG Sets:
o The structure consisting of two record types that are linked together is referred
to in the DBTG model as a DBTG set
o In each DBTG set, one record type is designated as the owner, and the other is
designated as the member, of the set.
o Each DBTG set can have any number of set occurrences (actual instances of
linked records).
o Since many-to-many links are disallowed, each set occurrence has precisely
one owner, and has zero or more member records.
o No member record of a set can participate in more than one occurrence of the
set at any point.
o A member record can participate simultaneously in several set occurrences of
different DBTG sets.
RELATIONAL MODEL
Relational model is simple model is simple model in which database is represented as a
collection of “relations” where each relation is represented by two-dimensional table.
The relational model was founded by E.F.Codd of the IBM in 1972.The basic concept in
the relational model is that of a relation.
Properties:
o It is column homogeneous. In other words, in any given column of a table, all
items are of the same kind.
o Each item is a simple number or a character string. That is a table must be in first
normal form.
o All rows of a table are distinct.
p The ordering of rows with in a table is immaterial.
o The column of a table are assigned distinct names and the ordering of these
columns in immaterial.
Relational schema:
A relational schema specifies the relation’ name, its attributes and the domain of each
attribute. If R is the name of a relation and A1,A2,… and is a list of attributes
representing R then R(A1,A2,…,an) is called a relational schema. Each attribute in
this relational schema takes a value from some specific domain called domain(Ai).
Example:
PERSON(PERSON_IDinteger,NAME: STRING,AGE:INTEGER,ADDRESS:string)
Total number of attributes in a relation denotes the degree of a relation.since the
PERSON relation schemea contains four attributes ,so this relation is of degree 4.
Relation Instance:
A relational instance denoted as r is a collection of tuples for a given relational
schema at a specific point of time.
A relation state r to the relations schema R(A1,A2…,An) also denoted by r® is a set
of n-tuples
R{t1,t2,…tm}
Where each n-tuple is an ordered list of n values
T=<v1,v2,….vn>
Where each vi belongs to domain (Ai) or contains null values.
The relation schema is also called ‘intension’ and the relation state is also called
‘extension’.
Eg:
Keys:
Super key:
A super key is an attribute or a set of attributes used to identify the records uniquely
in a relation.
Eg: (cname,telno)
Primary key:
The primary key is the candidate key that is chosen by the database designer as the
principal means of identifying entities with in an entity set. The remaining candidate
keys if any are called alternate key.
Example:
Example:
4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key.
A primary key can contain a unique and null value in the relational table.
Example:
(or)
RELATIONAL CONSTRAINTS:
There are three types of constraints on relational database that include
o DOMAIN CONSTRAINTS
o KEY CONSTRAINTS
o INTEGRITY CONSTRAINTS
DOMAIN CONSTRAINTS:
It specifies that each attribute in a relation an atomic value from the corresponding
domains. The data types associated with commercial RDBMS domains include:
o Standard numeric data types for
integer o Real numbers
o Characters
o Fixed length strings and variable length strings
Thus, domain constraints specifies the condition that we to put on each instance of the
relation. So the values that appear in each column must be drawn from the domain
associated with that column.
Rollno Name City Age
101 Sujit Bam 23
102 Kunal bbsr 22
Key constraints:
This constraints states that the key attribute value in each tuple msut be unique .i.e, no
two tuples contain the same value for the key attribute.(null values can allowed)
Integrity constraints:
Department(deptcode,dname)
Here the deptcode is the primary key.
Emp(empcode,name,city,deptcode).
Here the deptcode is foreign key.
CODD'S RULES
• View Definition
• Integrity Constraints
• Authorization.
Every RDBMS should provide a language to allow the user to query the contents of the
RDBMS and also manipulate the contents of the RDBMS.
Rule 6 : .View updating Rule
"All views that are theoretically updateable are also updateable by the system."
Not only can the user modify data, but so can the RDBMS when the user is not logged-in.
Rule 7 : High-level insert, update and delete.
"The capability of handling a base relation or a derived relation as a single operand
applies not only to the retrieval of data but also to the insertion, update and deletion of
data."
The user should be able to modify several tables by modifying the view to which they act
as base tables.
Rule 8 : Physical data independence.
"Application programs and terminal activities remain logically unimpaired whenever any
changes are made in either storage representations or access methods."
The user should not be aware of where or upon which media data-files are
stored Rule 9 : Logical data independence.
"Application programs and terminal activities remain logically unimpaired when
information-preserving changes of any kind that theoretically permit un-impairment are
made to the base tables."
User programs and the user should not be aware of any changes to the structure of the
tables (such as the addition of extra columns).
Rule 10 : Integrity independence.
"Integrity constraints specific to a particular relational data base must be definable in the
relational data sub-language and storable in the catalog, not in the application programs."
If a column only accepts certain values, then it is the RDBMS which enforces these
constraints and not the user program, this means that an invalid value can never be
entered into this column, whilst if the constraints were enforced via programs there is
always a chance that a buggy program might allow incorrect values into the system.
Rule 11 : Distribution independence.
"A relational DBMS has distribution independence."
The RDBMS may spread across more than one system and across several networks,
however to the end-user the tables should appear no different to those that are local.
Rule 12 : Non-subversion Rule.
"If a relational system has a low-level (single-record-at -a-time) language, that low level
cannot be used to subvert or bypass the integrity Rules and constraints expressed in the
higher level relational language (multiple-records-at-a-time)."
RELATION ALGEBRA:
Relational algebra is a set of basic operations used to manipulate the data in relational
model. These operations enable the user to specify basic retrieval request. The result of
retrieval is anew relation, formed from one or more relation. These operation can be
classified in two categories.
Basic Set Operation
Union
Intersection
Set difference
Cartesian product
Relational operations
Select
Project
Join
Division
A B
A B A B
α 1 α 2
α 2 β 3
β 1
s
r
α 1
α 2
1
β β
3
UNION OPERATION:
Notation: r ∪ s
Defined as:
r ∪ s = {t | t ∈ r or t ∈ s}
For r ∪ s to be valid.
r, s must have the same arity (same number of attributes)
2. The attribute domains must be compatible (e.g., 2nd column of r deals
with the same type of values as does the 2nd column of s)
E.g. to find all customers with either an account or a loan ∏customer-name
(depositor) ∪ ∏customer-name (borrower)
Set Difference
Operation – Example
Relations r, s:
r – s:
A B
A B A B
α 1 α 2
α 2 β 3
1β
s
r
α 1
β 1
Notation r – s
Defined as:
r – s = {t | t ∈ r and t ∉ s}
Set differences must be taken between compatible relations.
o r and s must have the same arity
o attribute domains of r and s must be compatible
Cartesian product – Example
A B C D E A B C D E
α 1 α 10 a α 1 α 10 a
β 2 β 10 a α 1 β 10 a
β 20 b α 1 β 20 b
r γ s
Pr oject
10 Oper ation
b –
α Examp le
1 γ 10 b
β 2 α 10 a
β 2 β 10 a
Relation r: A B C β 2 β 20 b
α
α
10
20
1
1
β 2 γ 10 b
β 30 1
β 40 2
r x s:
Notation r x s
Defined as: A C A C
∏A,C (r)
r x s = {t q | t ∈ r and q ∈ s}
Notation: α 1 α 1
∅ ). α
Assume that attributes of r(R) and s(S) are disjoint. (That is, R ∩ S =
∏ A1, A2, …, Ak (r ) 1 = β 1
If attribut es of r(R) and s(S) ar e not d isjoint, then ren am ing must be
1 2
β β
• Relation r A B C D
α α 1 7
α β 5 7
β β 12 3
β β 23 10
σ
• A=B^D>5 (r) A B C D
α α 1 7
β β 23 10
Notation: σ p(r)
p is called the selection predicate
Defined as:
σp(r) = {t | t ∈ r and p(t)}
Where p is a formula in propositional calculus consisting of terms
connected by : ∧ (and), ∨ (or), ¬ (not) Each term is one of:
<attribute> op <attribute> or <constant>
where op is one of: =, ≠, >, ≥. <. ≤
Example of selection:
Q: Display the account details belonging to the branch “perryridge”. σ
branch-name=“Perryridge”(account)
Rename Operation
Allows us to name, and therefore to refer to, the results of relational-
algebra expressions.
Allows us to refer to a relation by more than one name.
Example:
ρ x (E)
returns the expression E under the name X
If a relational-algebra expression E has arity n, then
ρx (A1, A2, …, An) (E)
returns the result of expression E under the name X, and with the
attributes renamed to A1, A2, …., An.
Set-Intersection Operation
Notation: r ∩ s
Defined as:
r ∩ s ={ t | t ∈ r and t ∈ s }
Assume:
r, s have the same arity
attributes of r and s are compatible
Note: r ∩ s = r - (r - s)
Set-Intersection Operation - Example
n Relation r, s: A B A B
α 1 α 2
α 2
β 3
β 1
r s
n r∩s A B
α 2
Natural-Join Operation
Let r and s be relations on schemas R and S respectively.
Notation: r
Relations r, s:
A B C D B D E
α 1 α a 1 a α
β 2 γ a 3 a β
γ 4 β b 1 a γ
α 1 γ a 2 b δ
δ 2 β b 3 b ∈
r s
r s
A B C D E
α 1 α a α
α 1 α a γ
α 1 γ a α
α 1 γ a γ
δ 2 β b δ
Division Operation
r÷s
Suited to queries that include the phrase “for all”.
Let r and s be relations on schemas R and S
respectively where
R = (A1, …, Am, B1, …, Bn)
S = (B1, …, Bn)
The result of r ÷ s is a relation on schema
R – S = (A1, …, Am)
r ÷ s = { t | t ∈ ∏ R-S(r) ∧ ∀ u ∈ s ( tu ∈ r ) }
A B
Relations r, s: B
α 1 1
α 2 2
α 3
β 1
s
γ 1
δ 1
δ 3
4
δ
6
∈ 1
∈
β 2
r ÷ s: A r
α
β
Example Queries
n Find all customers who have an account from at
least the “Downtown” and the Uptown” branches.
Query 1
∏CN(σBN=“Downtown”(depositor account)) ∩
∏CN(σBN=“Uptown”(depositor account))
Query 2
∏ (depositor account)
customer-name, branch-name
Example Queries
n Find all customers who have an account at all branches
located in Brooklyn city.
∏ (depositor account)
customer-name, branch-name
÷∏ (σ (branch))
branch-name branch-city = “Brooklyn”
Banking Example
Example Queries
σ (loan)
amount > 1200
n Find the loan number for each loan of an amount greater than
$1200
∏ (σ (loan))
loan-number amount > 1200
Example Queries
∏ (borrower) ∪ ∏ (depositor)
customer-name customer-name
account at bank.
∏ (borrower) ∩ ∏ (depositor)
customer-name customer-name
Example Queries
Find the names of all customers who have a loan at the Perryridge
branch.
∏customer-name (σbranch-name=“Perryridge”
(σborrower.loan-number = loan.loan-number(borrower x loan)))
Find the names of all customers who have a loan at the Perryridge
branch but do not have an account at any branch of the bank.
Example Queries
n Find the names of all customers who have a loan at the Perryridge
branch.
−Query 1
∏ (σ (
customer-name branch-name = “Perryridge”
σ (borrower x loan)))
borrower.loan-number = loan.loan-number
− Query 2
∏ (σ (
customer-name loan.loan-number = borrower.loan-number
(σ (loan)) x borrower))
branch-name = “Perryridge”
Example Queries
Find the largest account balance
n Rename account relation as
A B C
α α 7
α β 7
β β 3
β β 10
sum-C
g sum(c) (r) 27
OUTER JOIN:
The outer join operation is an extension of the join operation to deal with missing
information.
There are three forms of outer join
left outer join
right outer join
full outer join
employee:
Empname Street City
Coyote Toon Hollywood
Rabbit Tunnel carrot
Smith Revolver Death valley
William Seaview Seattle
Ft_works:
Empname Branch name Salary
Coyote Mesa 1500
Rabbit Mesa 1300
Gates Redmond 5300
William Redmond 1500
Employee ft_works
The tuple relational calculus is a non procedural query language. It describes the
desired information with out giving a specific procedure for obtaining that
information.
A query in the tuple relational calculus is expressed as:
{t|P(t)}
where P is a formula. Several tuple variables may appear in a formula. A tuple
variable is said to be a free variable unless it is quantified by a ∃ or ∀.
2. n Set P is a
of comparison operators: (e formula
.g.,< similarto that of,≤ ,the=,≠ ,predicate>,≥) calculus
{t | ∃ s ∈connectives:loan([loan-number] = s[loan-number] ∧ s [amount] > 1200)}
3. Set of and (∧), or (v)‚ not (¬)
4. Implication (⇒): x ⇒ y, if x if true, then y is true
x ⇒ y ≡ ¬x v y
5. Set of quantifiers:
Notice that a relation on schema [ loan-number] is implicitly defined
∃ t ∈ r (Q(t)) ≡ ”there exists” a tuple in t in relation r
by the query such that predicate Q(t) is true
∀t ∈ r (Q(t)) ≡ Q is true “for all” tuples t in relation r
Example Queries
Find the names ofExampleallcustomers
havingQueriesaloan, an account, or both at the bank
Find
thethe namesnames ofof allallcustomerscustomershavinghavinga aloan,loananat account,the
{ t | ∃s ∈ borrower( t[customer-name] = s[customer-name]) ∨ ∃u ∈ Perryridge branch
or both at the bank
∃u ∈ loan(u[branch-name] = “Perryridge”
∃u ∈ depositor ( t[customer- name] = u [customer-name])
∧
Find the names of all customers who have a loan and an account
u[loan-number] = s[loan-number]))}
at the bank Safety of Expressions
Find the names of all customers who have a loan and an
{t | ∃s ∈ borrower( t[customer-name] = s[customer-name])
account at the bank
∧ ∃u ∈ depositor( t[customer -name] = u[customer-name])
It is possible to write tuple calculus expressions that generate
infinite{|∃s relations∈borrower(. t[customer-name] = s[customer-
Domain Relational Calculus
A nonprocedural
queryExamplelanguagequivalQueriesntnpower to the
tuple relational calculus
Each query is an expression of the form:
FindQuerytheloan-number,-bybranch-Example-
name,andamount(QBE)forloansof over $1200
{ < x , x , …, x > | P(x , x , …, x )}
1 2 n 1 2 n
(or)
Relational Calculus
o Relational calculus is a non-procedural query language. In the non-procedural query
language, the user is concerned with the details of how to obtain the end results.
o The relational calculus tells what to do but never explains how to do.
Notation:
Where
For example:
OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).
For example:
Output: This query will yield the same result as the previous one.
Notation:
Where
a1, a2 are attributes
P stands for formula built by inner attributes
For example:
Output: This query will yield the article, page, and subject from the relational javatpoint,
where the subject is a database.
Rules:
SQL follows the following rules:
o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement
on one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.
SQL process:
o When an SQL command is executing for any RDBMS, then the system figure out the
best way to carry out the request and the SQL engine determines that how to
interpret the task.
o In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query
engine won't handle logical files.
Characteristics of SQL
o SQL is easy to learn.
o SQL is used to access data from relational database management systems.
o SQL can execute queries against the database.
o SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.
o SQL is used to create a view, stored procedure, function in a database.
o SQL allows users to set permissions on tables, procedures, and views.
Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of
records from a database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Datatype of SQL:
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
Data Description
type
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL command
o SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
1. DROP TABLE ;
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
EXAMPLE
d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:
Example:
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row
of a table.
Syntax:
Or
For example:
b. UPDATE: This command is used to update or modify the value of a column in the
table.
Syntax:
For example:
Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
o Grant
o Revoke
Example
Example
These operations are automatically committed in the database that's why they cannot be
used while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling
back the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.
Syntax:
For example:
- It is used to subtract the right-hand operand from the left- a-b will give
hand operand. 10
/ It is used to divide the left-hand operand by the right-hand a/b will give
operand. 2
% It is used to divide the left-hand operand by the right-hand a%b will give
operand and returns reminder. 0
= It checks if two operands values are equal or not, if the values (a=b) is not
are queal then condition becomes true. true
!= It checks if two operands values are equal or not, if values are (a!=b) is
not equal, then condition becomes true. true
<> It checks if two operands values are equal or not, if values are (a<>b) is
not equal then condition becomes true. true
> It checks if the left operand value is greater than right (a>b) is not
operand value, if yes then condition becomes true. true
< It checks if the left operand value is less than right operand (a<b) is
value, if yes then condition becomes true. true
>= It checks if the left operand value is greater than or equal to (a>=b) is
the right operand value, if yes then condition becomes true. not true
<= It checks if the left operand value is less than or equal to the (a<=b) is
right operand value, if yes then condition becomes true. true
!< It checks if the left operand value is not less than the right (a!=b) is not
operand value, if yes then condition becomes true. true
!> It checks if the left operand value is not greater than the right (a!>b) is
operand value, if yes then condition becomes true. true
BETWEEN It is used to search for values that are within a set of values.
SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns. In
DBMS, the table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient
representation of relations.
Operation on Table
1. Create table
2. Drop table
3. Delete table
4. Rename table
Syntax
Example
If you create the table successfully, you can verify the table by looking at the message by
the SQL server. Else you can use DESC command as follows:
Now you have an EMPLOYEE table in the database, and you can use the stored information
related to the employees.
Drop table
A SQL drop table is used to delete a table definition and all the data from a table. When this
command is executed, all the information available in the table is lost forever, so you have
to very careful while using this command.
Syntax
Firstly, you need to verify the EMPLOYEE table using the following command:
This table shows that EMPLOYEE table is available in the database, so we can drop it as
follows:
Now, we can check whether the table exists or not using the following command:
1. Query OK, 0 rows affected (0.01 sec)
Syntax
Example
If you don't specify the WHERE condition, it will remove all the rows from the table.
Syntax
Here, the expression is the field name of the table that you want to select data from.
Use the following syntax to select all the fields available in the table:
Example:
EMPLOYEE
To fetch the EMP_ID of all the employees, use the following query:
Output
EMP_ID
EMP_NAME SALARY
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000
To fetch all the fields from the EMPLOYEE table, use the following query:
1. SELECT * FROM EMPLOYEE
Output
Sample Table
EMPLOYEE
Syntax
1. INSERT INTO TABLE_NAME VALUES (value1, value2, value 3, .... Value N);
Query
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
1. INSERT INTO TABLE_NAME [(col1, col2, col3,.... col N)] VALUES (value1, value2, value 3, .
.. Value N);
Query
1. INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40);
Output: After executing this query, the table will look like:
EMP_ID EMP_NAME CITY SALARY AGE
Note: In SQL INSERT query, if you add values for all columns then there is no need to specify
the column name. But, you must be sure that you are entering the values in the same order
as the column exists.
Syntax
1. UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Sample Table
EMPLOYEE
Syntax
1. UPDATE table_name
2. SET column_name = value
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Emma'
3. WHERE SALARY = 500000;
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
1. UPDATE table_name
2. SET column_name = value1, column_name2 = value2
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Kevin', City = 'Boston'
3. WHERE EMP_ID = 5;
Output
Syntax
1. UPDATE table_name
2. SET column_name = value1;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Harry';
Output
Syntax
Sample Table
EMPLOYEE
Query
Output: After executing this query, the EMPLOYEE table will look like:
Query
Syntax
Query
Output: After executing this query, the EMPLOYEE table will look like:
Note: Using the condition in the WHERE clause, we can delete single as well as multiple
records. If you want to delete all the records from the table, then you don't need to use the
WHERE clause.
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main
query, and the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can
be used to perform the same function as ORDER BY command.
Syntax
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
Syntax:
Example
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP
table.
1. INSERT INTO EMPLOYEE_BKP
2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);
Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
1 John 20 US 2000.00
Syntax
Example
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
SQL Clauses
The following are the various SQL clauses:
1. GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP
BY statement is used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
o The GROUP BY statement is used with aggregation function.
Syntax
1. SELECT column
2. FROM table_name
3. WHERE conditions
4. GROUP BY column
5. ORDER BY column
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example:
Output:
Com1 5
Com2 3
Com3 2
2. HAVING
o HAVING clause is used to specify a search condition for a group or an aggregate.
o Having is used in a GROUP BY clause. If you are not using GROUP BY clause then
you can use HAVING function like a WHERE clause.
Syntax:
Example:
Output:
Com1 5
Com2 3
3. ORDER BY
o The ORDER BY clause sorts the result-set in ascending or descending order.
o It sorts the records in ascending order by default. DESC keyword is used to sort the
records in descending order.
Syntax:
Where
CUSTOMER
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME;
Output:
34 Alina Dubai
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US
Output:
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the
right table. If there is no matching join value, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and
the matched values from the left table. If there is no matching in both tables, it will return
NULL.
Syntax
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
Using the above First and Second table.
ID NAME
1 Jack
2 Harry
PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger
is stored into database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Advantages of Triggers
These are the following advantages of Triggers:
Creating a trigger:
Syntax for creating trigger:
Here,
Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire
for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Use the following code to get the old salary, new salary and salary difference after the
trigger created.
1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /
Output:
Note: As many times you executed this code, the old and new both salary is incremented
by 5000 and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Important Points
Following are the two very important point and should be noted carefully.
o OLD and NEW references are used for record level triggers these are not avialable for
table level triggers.
o If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of
information.
o Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the
database.
Note: we should not compare null value with 0. They are not equivalent.
TYAGI SEEMA
SHARMA AMAR
Let's see the query to get all the records where marks is NULL:
SHARMA AMAR
TYAGI SEEMA
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
Example:
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very
fast.
o An Index is used to speed up select queries and where clauses. But it shows down
the data input with insert and update statements. Indexes can be created or dropped
without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic,
you first have to refer to the index, which alphabetically lists all the topics and then
referred to one or more specific page numbers.
Example
Syntax
Example
Syntax
Example