Unit 1&2
Unit 1&2
1. 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.
2. 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).
3. 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.
6. DBMS provide backup and recovery whereas data lost in file system can't be
recovered.
1
DBMS File Processing System
Minimal data redundancy problem
Data Redundancy problem exits
in DBMS
Data Inconsistency does not exist Data Inconsistency exist here
Accessing database is easier Accessing is comparatively difficult
Data is scattered in various files and files
The problem of data isolation is
may be of different format, so data
not found in database
isolation problem exists
Transactions like insert, delete,
In file system, transactions are not
view, updating, etc are possible in
possible
database
Concurrent access and recovery is Concurrent access and recovery is
possible in database not possible
Security of data Security of data is not good
A database manager
A file manager is used to store all
(administrator) stores the
relationships in directories in file systems.
relationship in form of structural
tables
History of Database
Late 1990s:
o Large decision support and data-mining applications
o Large multi-terabyte data warehouses
o Emergence of Web commerce
Early 2000s:
o XML and XQuery standards
o Automated database administration
Later 2000s:
o Web databases (semi-structured data, XML, complex data types)
o Cloud computing
o Giant data storage systems (Google BigTable, Yahoo PNuts,
Amazon Web Services, …)
3
Characteristics of a Database Stores any kind of Data
A database management system should be able to store any kind of data. It should not be
restricted to the employee name, salary and address. Any kind of data that exists in the real
world can be stored in DBMS because we need to work with all kinds of data that is present
around us.
Data integrity
This is one of the most important characteristics of database management system. Integrity
ensures the quality and reliability of database system. It protects the unauthorized access
of database and makes it more secure. It brings only the consistence and accurate data into
the database.
4
Abstraction levels
A database system is a collection of interrelated data and a set of programs that allow
users to access and modify these data. A major purpose of a database system is to
provide users with an abstract view of the data. That is, the system hides certain details
of how the data are stored and maintained.
Data Abstraction
For the system to be usable, it must retrieve data efficiently. The need for efficiency has
led designers to use complex data structures to represent data in the database. Since many
database-system users are not computer trained, developers hide the complexity from users
through several levels of abstraction, to simplify users’ interactions with the system:
Database Disk
• Physical level (or Internal View / Schema): The lowest level of abstraction describes
how the data are actually stored. The physical level describes complex low-level data
structures in detail.
• Logical level (or Conceptual View / Schema): The next-higher level of abstraction
describes what data are stored in the database, and what relationships exist among
those data. The logical level thus describes the entire database in terms of a small
number of relatively simple structures. Although implementation of the simple
structures at the logical level may involve complex physical-level structures, the user
of the logical level does not need to be aware of this complexity.
5
• This is referred to as physical data independence.
• View level (or External View / Schema): The highest level of abstraction describes
only part of the entire database. Even though the logical level uses simpler structures,
complexity remains because of the variety of information stored in a large database.
Many users of the database system do not need all this information; instead, they need
to access only a part of the database. The view level of abstraction exists to simplify
their interaction with the system. The system may provide many views for the same
database.
For example, we may describe a record as follows:
type instructor = record
ID : char (5);
end;
This code defines a new record type called instructor with four fields. Each
field has a name and a type associated with it. A university organization may
have several such record types, including
At the logical level, each such record is described by a type definition, as in the
previous code segment, and the interrelationship of these record types is defined as
well.
Finally, at the view level, computer users see a set of application programs that hide
details of the data types. At the view level, several views of the database are defined, and
a database user sees some or all of these views.
Architecture of a Database
The architecture of a database system is greatly influenced by the underlying computer
system on which the database system runs. Database systems can be centralized, or client-
server, where one server machine executes work on behalf of multiple client machines.
6
Database systems can also be designed to exploit parallel computer architectures. Distributed
databases span multiple geographically separated machines.
A database system is partitioned into modules that deal with each of the
responsibilities of the overall system. The functional components of a database
system can be broadly divided into the storage manager and the query processor
components. The storage manager is important because databases typically require a
large amount of storage space. The query processor is important because it helps the
database system simplify and facilitate access to data.
7
Query Processor:
The query processor components include
· DDL interpreter, which interprets DDL statements and records the definitions in the
data dictionary.
· DML compiler, which translates DML statements in a query language into an
evaluation plan consisting of low-level instructions that the query evaluation engine
understands.
A query can usually be translated into any of a number of alternative evaluation plans
that all give the same result. The DML compiler also performs query optimization,
that is, it picks the lowest cost evaluation plan from among the alternatives.
Query evaluation engine, which executes low-level instructions generated by the
DML compiler.
Storage Manager:
A storage manager is a program module that provides the interface between the low level
data stored in the database and the application programs and queries submitted to the
system. The storage manager is responsible for the interaction with the file manager.
8
Transaction Manager:
A transaction is a collection of operations that performs a single logical function in
a database application. Each transaction is a unit of both atomicity and consistency.
Thus, we require that transactions do not violate any database-consistency constraints.
1. File Manager manages the allocation space on disk storage and the data
structures used to represent info stored on other media. In most applications
(99.9%) the file is the central element. All applications are designed with
the specific goal: generation and use of information. A typical file system
layered architecture is the following.
User
Progra
m
Logical
I/O
Basic File System Structure
Device Drivers (Disk,tape,etc)
Controllers
Actual
Devic
e
2. Buffer Manager among other tasks, it transfers blocks between disk (or
other devices) and Main Memory (MM). A DMA (Direct Memory
Access) is a form of I/O that controls the exchange of blocks between
MM and a device. When a processor receives a request for a transfer of a
block, it sends it to the DMA which transfers the block uninterrupted.
10
Components of a Database
User: - Users are the one who really uses the database. Users can be administrator,
developer or the end users.
DBMS: - This is the software helps the user to interact with the database. It allows
the users to insert, delete, update or retrieve the data. All these operations are handled
by query languages like MySQL, Oracle etc.
Database Application: - It the application program which helps the users to interact
with the database by means of query languages. Database application will not have
any idea about the underlying DBMS.
DBMS Languages
To read data, update and store information in DBMS, some languages are used. Database
languages in DBMS are given as below.
11
DDL stands for data definition language and used to define database patterns or
structures. DDL is a syntax which is same as syntax of computer programming language
for defining patterns of database.
DROP statement destroys or deletes database or table. In structured query language, it also
deletes an object from relational database management system. Typically used DROP
statement is
It has statements which are used to manage the data within the pattern of objects. Some of
the samples of the statements are as follows:
12
• UPDATE – used in updating the data
• DELETE – do the function of deleting the records
• MERGE – this do the UPSERT operation i.e. insert or update operation
• CALL – this calls a structured query language or a java subprogram
• EXPLAIN PLAN – has the parameter of explaining data
• LOCK TABLE – this ha the function of controlling concurrency
These syntax elements are similar to the syntax elements used in computer programming
language. Performing the operation of reading of queries is also a component of data
manipulation language. Other forms of data manipulation languages (DML) are used by
IMS, CODASYL databases.
DML also include the structured query language (SQL) data modifying statements, they
modify the saved data but not the pattern of objects. The initial word of the DML
statements has functional capability.
The query statement SELECT is grouped with data statements of structured query
language (SQL). In practice there is no such difference and it is viewed to be a portion of
DML.
Data manipulation languages contribute to have distinct relishes between database sellers.
They are divided as:
• Procedural programming
• Declarative programming
Initially data manipulation languages were only used in computer programs, but with the
coming of structured query languages it is also used in the database executors.
Data Control Language (DCL) is syntax similar to the programming language, which
was used to retrieve the stored or saved data. Examples of the commands in the data
control language (DCL) are:
The operations which has the authorization of REVOKE are CONNECT, INSERT, USAGE,
EXECUTE, DELETE, UPDATE and SELECT.
13
The execution of DCL is transactional; it also has the parameter of rolling back. But
the execution of data control language in oracle database does not have the feature of
rolling back.
Transaction Control Language (TCL) has commands which are used to manage the
transactions or the conduct of a database. They manage the changes made by data
manipulation language statements and also group up the statements in o logical
management.
ROLL BACK command uses the save point command to jump to save point in transaction.
Database Users
Database administrators – DBA is responsible for authorizing access to the database, for
coordinating and monitoring its use, and acquiring software and hardware resources as
needed.
Database designers – identify data to be stored in the database and choosing appropriate
structures to represent and store the data. Most of these functions are done before the
database is implemented and populated with the data. It is the responsibility of the database
designers to communicate with all prospective users to understand their requirements and
14
come up with a design that meets these requirements. Database designers interact with
all
15
potential users and develop views of the database that meet the data and processing
requirements of these groups. The final database must support the requirements of all user
groups.
End Users
▪ Casual End Users – occasionally access, may need different information each time.
Use query language to specify requests.
▪ Naïve or parametric end users – main job is to query and update the database using
standard queries and updates. These canned transactions have been carefully
programmed and tested. Examples?
▪ Sophisticated end users – engineers, scientists, analysts who implement applications to
meet their requirements.
▪ Stand alone users – maintain personal databases using ready made packages.
DBA
A database administrator’s (DBA) primary job is to ensure that data is available, protected
from loss and corruption, and easily accessible as needed. Below are some of the chief
responsibilities that make up the day-to-day work of a DBA. DSP deliver an outsourced
DBA service in the UK, providing Oracle Support and SQL Server Support; whilst mindset
and toolset may be different, whether a database resides on-premise or in a Public / Private
Cloud, the role of the DBA is not that different.
A DBA often collaborates on the initial installation and configuration of a new Oracle,
SQL Server etc database. The system administrator sets up hardware and deploys the
operating system for the database server, then the DBA installs the database software and
configures it for use. As updates and patches are required, the DBA handles this on-going
maintenance. And if a new server is needed, the DBA handles the transfer of data from the
existing system to the new platform.
16
2. Data Extraction, Transformation, and Loading
Known as ETL, data extraction, transformation, and loading refers to efficiently importing
large volumes of data that have been extracted from multiple systems into a data
warehouse environment. This external data is cleaned up and transformed to fit the desired
format so that it can be imported into a central repository.
Today’s databases can be massive and may contain unstructured data types such as images,
documents, or sound and video files. Managing a very large database (VLDB) may require
higher-level skills and additional monitoring and tuning to maintain efficiency.
DBAs create backup and recovery plans and procedures based on industry best practices,
then make sure that the necessary steps are followed. Backups cost time and money, so the
DBA may have to persuade management to take necessary precautions to preserve data.
System admins or other personnel may actually create the backups, but it is the DBA’s
responsibility to make sure that everything is done on schedule.
In the case of a server failure or other form of data loss, the DBA will use existing backups
to restore lost information to the system. Different types of failures may require different
recovery strategies, and the DBA must be prepared for any eventuality. With technology
change, it is becoming ever more typical for a DBA to backup databases to the cloud,
Oracle Cloud for Oracle Databases and MS Azure for SQL Server.
5. Security
A DBA needs to know potential weaknesses of the database software and the company’s
overall system and work to minimize risks. No system is one hundred per cent immune to
attacks, but implementing best practices can minimize [Link] the case of a security breach or
irregularity, the DBA can consult audit logs to see who has done what to the data. Audit
trails are also important when working with regulated data.
17
6. Authentication
Setting up employee access is an important aspect of database security. DBAs control who
has access and what type of access they are allowed. For instance, a user may have
permission to see only certain pieces of information, or they may be denied the ability to
make changes to the system.
7. Capacity Planning
The DBA needs to know how large the database currently is and how fast it is growing in
order to make predictions about future needs. Storage refers to how much room the
database takes up in server and backup space. Capacity refers to usage level. If the
company is growing quickly and adding many new users, the DBA will have to create the
capacity to handle the extra workload.
8. Performance Monitoring
Monitoring databases for performance issues is part of the on-going system maintenance
a DBA performs. If some part of the system is slowing down processing, the DBA may
need to make configuration changes to the software or add additional hardware capacity.
Many types of monitoring tools are available, and part of the DBA’s job is to understand
what they need to track to improve the system. 3rd party organizations can be ideal for
outsourcing this aspect, but make sure they offer modern DBA support.
9. Database Tuning
18
10. Troubleshooting
DBAs are on call for troubleshooting in case of any problems. Whether they need to
quickly restore lost data or correct an issue to minimise damage, a DBA needs to quickly
understand and respond to problems when they occur.
19
Database Design and ER Diagram:
The database design process can be divided into six steps. The ER model is most relevant to
the first three steps:
(i) Requirements Analysis: The very first step in designing a database application is
to understand what data is to be stored in the database, what applications must be
built on top of it, and what operations are most frequent and subject to performance
requirements. In other words, we must find out what the users want from the
database.
(iii) Logical Database Design: We must choose a DBMS to implement our database
design, and convert the conceptual database design into a database schema in the
data model of the chosen DBMS. We will only consider relational DBMS’s, and
therefore, the task in the logical design step is to convert an ER schema into a
relational databaseschema.
Beyond the ER Model
(iv) Schema Refinement: The fourth step in database design is to analyze the collection
of relations in our relational database schema to identify potential problems, and to
refine it. In contrast to the requirements analysis and conceptual design steps, which
are essentially subjective, schema refinement can be guided by some elegant and
powerful theory.
(v) Physical Database Design: In this step we must consider typical expected
workloads that our database must support and further refine the database design to
ensure that it meets desired performance criteria. This step may simply involve
building indexes on some tables and clustering some tables, or it may involve a
substantial redesign of parts of the database schema obtained from the earlier design
steps.
(vi) Security Design: In this step, we identify different user groups and different roles
played by various users (e.g., the development team for a product, the customer
20
support representatives, and the product manager). For each role and user group, we
must identify the parts of the database that they must be able to access and the parts
of the database that they should not be allowed to access, and take steps to ensure
that they can access only the necessary parts.
iv) Single-valued Attributes: having only one value rather than a set of
values.
For e.g. PlaceOfBirth–single string value.
21
Diagrammatic representation of an Entity and different types of attributes:
i) entity -rectangle attribute – ellipse connected to rectangle
ii) multi-valued attribute – double ellipse
iii) composite attribute – ellipse connected to ellipse
iv) derived attribute – dashed ellipse
Domains of Attributes
For example,
basic domain
An entity set is a set of entities of the same type that share the same properties.
When two or more entities are associated with each other, we have an instance of a
Relationship.
E.g.: student Ramesh enrolls in Discrete Mathematics course
Relationship enrolls has Student and Course as the participating entity sets.
Degree of a relationship
Degree: The number of participating entities.
• Degree 2: A relationship having 2 entities attached, it is called
binaryrelationship.
• Degree 3: A relationship having 3 entities attached, it is called
ternaryrelationship
• Degree n: A relationship having 2 entities attached, it is called n-
aryrelationship
• Binary relationships are very common and widely used.
22
Binary Relationships and Cardinality Ratio
Cardinality Ratios
• One-to-One: An E1 entity may be associated with at most one E2 entity and
similarly an E2 entity may be associated with at most one E1 entity.
23
Participation Constraints
An entity set may participate in a relation either totally or partially.
• Total participation: Every entity in the set is involved in some association (or
tuple) of the relationship.
• Partial participation: Not all entities in the set are involved in association (or
tuples) of the relationship.
Grade gives the letter grade (S,A,B, etc.) earned by the student for a course. It is
neither an attribute of student nor that of course.
24
It is not always clear whether an object is best expressed by an entity set or a relationship
set.
we used the takes relationship set to model the situation where a student takes a (section of a)
course. An alternative is to imagine that there is a course-registration record for each course
that each student takes. Then, we have an entity set to represent the course-registration
record. Let us call that entity set registration. Each registration entity is related to exactly one
student and to exactly one section, so we have two relationship sets, one to relate
courseregistration records to students and one to relate course-registration records to sections.
we show the entity sets section and studentfrom with the takes relationship set replaced by
one entity set and two relationship sets:
Note that we use double lines to indicate total participation by registration entities.
25
It is always possible to replace a non-binary relationship set by a number of distinct binary
relationship sets. For example, consider a ternary relationship R associated with three entity
sets A, B and C. We can replace the relationship set R by an entity set E and create three
relationship sets as:
If the relationship set R had any attributes, these are assigned to entity set E. A special
identifying attribute is created for E
The cardinality ratio of a relationship can affect the placement of relationship attributes:
• One-to-Many: Attributes of 1:M relationship set can be repositioned to only the entity set
on the many side of the relationship
• One-to-One: The relationship attribute can be associated with either one of the
participating entities
• Many-to-Many: Here, the relationship attributes cannot be represented to the entity sets;
rather they will be represented by the entity set to be created for the relationship set.
ER Diagram Notations
26
• Rectangles divided into two parts represent entity sets. The first part, which in this
textbook is shaded blue, contains the name of the entity set. The second part contains
the names of all the attributes of the entity set.
27
option to deal with this redundancy is to get rid of the relationship sec course;
however, by doing so the relationship between section and course becomes
implicit in an attribute, which is not desirable.
The notion of weak entity set formalizes the above intuition. An entity
set that does not have sufficient attributes to form a primary key is termed a
weak entity set.
strong entity set An entity set that has a primary key is termed a strong entity
set.
ER Diagram Notations
An E-R diagram consists of the following major components:
28
Rectangle – It represents entity in the ER Model.
Ellipse – It represents attribute in the ER Model.
Diamond – It represents relationship between entity and attribute.
Line – It links attribute(s) to entity set(s) and entity set(s) to relationship set(s).
Doubles Ellipses – It represents multivalued attributes.
Dashed Ellipses – It denotes derived attributes.
Double lines – It indicates total participation of an entity in a relationship set.
Double Rectangle – It represents weak entity set.
Double Diamonds – It represents weak relationships.
Multiple ellipses connected to single ellipse using lines – It represents composite attribute
Ellipse with line inside it – It represents single values attributes
29
Extended Entity-Relationship (EE-R) Model
EER is a high-level data model that incorporates the extensions to the original ER model.
Enhanced ERD are high level models that represent the requirements and complexities of
complex database.
Super class shape has sub groups: Triangle, Square and Circle.
Sub classes are the group of entities with some unique attributes. Sub class inherits the
properties and attributes from super class.
30
It is a Bottom up process i.e. consider we have 3 sub entities Car, Truck and Motorcycle. Now
these three entities can be generalized into one super class named as Vehicle.
Specialization is a process of identifying subsets of an entity that share some different
characteristic. It is a top down approach in which one entity is broken down into low level entity.
Category or Union
Relationship of one super or sub class with more than one super class.
Aggregation
31
Consider a ternary relationship Works_On between Employee, Branch and Manager. Now the best way to
model this situation is to use aggregation, So, the relationship-set, Works_On is a higher level entity-set.
Such an entity-set is treated in the same manner as any other entity-set. We can create a binary relationship,
Manager, between Works_On and Manager to represent who manages what tasks.
32
UNIT-2
Constraints/key constraints: -
Entity integrity constraints / key constraints specify the condition and restricts the data
that can be stored, only in one table
Definitions:
Key constraint: a key constraint is a statement that a certain minimal field of a relation has
a unique identifier for all tuples. Actually, key constraint is the general term, the term
candidate key is used for satisfying the constraints according to a key constraint.
Candidate key: A set of fields that uniquely identifies a tuple according to a key constraint
is called a candidate key for the relation
Super key: A super key is a super set of a candidate key. A super key is a set
of fields that each contains a candidate key
In sql , we can declare that columns of a table from a candidate key using two statements.
Unique key
Primary key
Example:
Sql>create table student(sid char(10) primary key ,name
float);
The table in which the foreign key is defined is called a foreign table or detail table.
The table that defines the primary key and is referenced by the foreign key is called
the primary or Master Table.
Let us create the new table “Enrolled” connected with the previous example Student table.
34
Relation schema: The relation schema contains the basic information of a table. This information
includes the name of the table, the names of the columns and the data types associated with
each column
Relation instance:
An instance of a relation is a set of types in which each tuple has the same no. of
fields as the relation schema
Relational database schema: A relational database schema is a collection of
relation schemas, describing one or more relations
Relation cardinality: The Relation cardinality is the no. of tuples in the elation
Relation degree: The Relation degree as the [Link] columns in the relation
Tuples/records: The rows of the table as also known as records or tuples
Field/attributes: The columns of the table as also known as fields/attributes
The relational model is today the primary data model for commercial data
processing applications. It attained its primary position because of its simplicity,
which eases the job of the programmer, compared to earlier data models such as
the network model or the hierarchical model.
35
an instructor, consisting of the instructor’s ID, name, dept name, and salary.
Database Schema
When we talk about a database, we must differentiate between the database
schema, which is the logical design of the database, and the database instance,
which is a snapshot of the data in the database at a given instant in time. The
concept of a relation corresponds to the programming- language notion of a
variable, while the concept of a relation schema corresponds to the
programming-language notion of type definition.
Schema Diagrams
A database schema, along with primary key and foreign key dependencies, can be depicted by
schema diagrams. Figure 1.12 shows the schema diagram for our university organization.
36
Schema diagram for the university database.
Referential integrity constraints other than foreign key constraints are not shown explicitly in schema diagrams. We
will study a different diagrammatic representation called the entity- relationship diagram.
37
Views
Introduction to views
• The dynamic result of one or more relational operations operating on the base relations
to produce another relation is called view. A view is a virtual relation that does not
necessarily exist in the database. But can be produced upon request by a particular user
at the time of request.
• A view is object that gives the user a logical view of data from an underlying table or
tables. You can restrict what users can view by allowing them to see only a few columns
from a table.
Purpose of views
• The view mechanism is desirable for several reasons.
• It simplifies queries.
• It can be queried as a base table.
• It provides a powerful and flexible security mechanism by hiding parts of the
database from certain users.
• It permits users to access data in a way that is customized to their needs, so that the
same data can be seen by different users in different ways at the same time.
Updating views
• All updates to a base relation should be immediately reflected in all views that a
single base relation and containing either the primary key or a candidate key of the
base relation.
• Updates are not allowed through views involving multiple base relations.
• Updates are not allowed through views involving aggregation or grouping operations.
Creating
views
Syntax:
SELECT columnname,cloumnname
FROM tablenmae
38
Examples: create view on book table which contains two fields title, and author
name. SQL> create view V_book as select title, author_name from book;
View created.
Output:
Title Author_name
Oracle Arora
DBMS Basu
DOS Sinha
ADBMS Basu
Unix Kapoor
39
Selecting Data from a view
author_name=’Basu’; Output:
Title
DBMS
ADBMS
Updatable Views
Views can also be used for data manipulation i.e., the user can perform Insert, Update and
the Delete operations on the view. The views on which data manipulation can be done are
called Updatable views, views that do not allow data manipulation are called Read only
Views. When you give a view name in the update, insert or delete statement, the
modification to the data will be passed to the underlying table.
The definition of the table is changed using ALTER TABLE statement. The ALTER TABLE
is used to add, delete or modify columns in an existing table explained below:
1) ALTER TABLE…..ADD…..
This is used to add some extra columns into an existing table. The generalized
format is given below.
40
ALTER TABLE relation_name
41
Example:
ADD(cust_ph_no varchar(15),cust_fax_no
➢ Example:
Modify the data type of the publication year as numeric data
type. SQL> ALTER TABLE Book
MODIFY(pub_year
umber(4)); Table created.
Restrictions of the Alter Table
Using the alter table clause you perform the following tasks:
Change the name of the table.
Change the name of the
column. Drop a column.
Decrease the size of a column if table data exists.
3) ALETR TABLE……DELETE
To delete a column in a table , use the following syntax:
DELETING TABLE
The tables are deleted permanently from the database using DROP TABLE
command. We remove all the data from the table using TRUNCATE TABLE
command. It is explained below:
1) DROP TABLE
42
This command is used to delete a table. The generalized syntax if this form
is given below:
DROP TABLE relation_name
➢ Example: write the command for deleting special_customer relation.
SQL DROP TABLE
Special_customer; TABLR
dropped.
2) Truncate a table
Truncating a table is removing all records from the table. The structure of the
table stays intact. The SQL language has a DELETE statement which can be used
to remove one or more (or all) rows from a table. Truncation releases storage
space occupied by the table, but deletion does not. The syntax:
TRUNCATE TABLE table_name;
➢ Example:
SQL> TRUNCATE TABLE student;
Deleting view
A view can be dropped by using the DROP VIEW command.
Syntax:
DROP VIEW viewname;
➢ Example:
DROP VIEW V_Book;
Triggers.
Action: A procedure that is executed when the trigger is activated and its con-
dition is true.
A trigger action can examine the answers to the query in the condition part of the trigger,
43
refer to old and new values of tuples modified by the statement activating the trigger, execute
new queries, and make changes to the database.
44
Examples of Triggers in SQL
The examples shown in Figure 5.19, written using Oracle 7 Server syntax for defining
triggers, illustrate the basic concepts behind triggers. (The SQL:1999 syntax for these
triggers is similar; we will see an example using SQL:1999 syntax shortly.) The trigger
called init count initializes a counter variable before every execution of an INSERT
statement that adds tuples to the Students relation. The trigger called incr count increments
the counter for each inserted tuple that satisfies the condition age < 18.
BEGIN /*action*/
Count:=0;
END
(identifying the modified table, Students, and the kind of modifying statement, an INSERT),
and the third field is the number of inserted Students tuples with age < 18. (The trigger in
Figure 5.19 only computes the count; an additional trigger is required to insert the appropriate
tuple into the statistics table.)
46
SQL: Overview, The Form of Basic SQL Query -UNION, INTERSECT, and
EXCEPT– join operations: equi join and non equi join-Nested queries - correlated and
uncorrelated- Aggregate Functions-Null values, GROUPBY- HAVING Clause.
This section presents the syntax of a simple SQL query and explains its meaning through a
conceptual evaluation strategy. A conceptual evaluation strategy is a way to evaluate the
query that is intended to be easy to understand, rather than efficient. A DBMS would
typically execute a query in a different and more efficient way.
The answer to this query with and without the keyword DISTINCT on instance S3 of Sailors
is shown in Figures 5.4 and 5.5. The only difference is that the tuple for Horatio appears
twice if DISTINCT is omitted; this is because there are two sailors called Horatio and age
35.
47
(Q2) Find all sailors with a rating above 7.
SELECT [Link], [Link], [Link], [Link] FROM Sailors AS S WHERE [Link] > 7
(Q3) Find the sids of sailors who have reserved a red boat.
SELECT [Link] FROM Boats B, Reserves R WHERE [Link] = [Link] AND [Link] = ‘red’
(Q4) Find the names of sailors who have reserved a red boat.
SELECT [Link] FROM Sailors S, Reserves R, Boats B WHERE [Link] = [Link] AND
[Link] = [Link] AND [Link] = ‘red’
(Q6) Find the names of sailors who have reserved at least one boat.
SQL supports a more general version of the select-list than just a list of columns. Each item
in a select-list can be of the form expression AS column name, where expression is any
arithmetic or string expression over column names (possibly prefixed by range variables)
and constants.
(Q7) Compute increments for the ratings of persons who have sailed two
differentboats on the same day.
(Q8) Find the ages of sailors whose name begins and ends with B and has at
least three characters.
48
SELECT [Link] FROM Sailors S WHERE [Link] LIKE ‘B %B’
SQL provides three set-manipulation constructs that extend the basic query form pre- sented
earlier. Since the answer to a query is a multiset of rows, it is natural to consider the use of
operations such as union, intersection, and difference. SQL supports these operations under
the names UNION, INTERSECT, and EXCEPT.4 SQL also provides other set operations:
IN (to
check if an element is in a given set),op ANY,op ALL(tocom-pare a value with the elements
in a given set, using comparison operator op), and EXISTS (to check if a set is empty). IN
and EXISTS can be prefixed by NOT, with the obvious modification to their meaning. We
cover UNION, INTERSECT, and EXCEPT in this section. Consider the following query:
(Q1) Find the names of sailors who have reserved both a red and a green boat.
SELECT [Link] FROM Sailors S, Reserves R1, Boats B1, Reserves R2,
Boats B2 WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] = [Link]
AND [Link]
= [Link] AND [Link]=‘red’ AND [Link] = ‘green’
(Q2) Find the sids of all sailors who have reserved red boats but not green boats.
Joins
The join operation is one of the most useful operations in relational algebra and is the most
commonly used way to combine information from two or more relations. Althougha join
can be defined as a cross-product followed by selections and projections, joins
49
arise much more frequently in practice than plain [Link] have received a lot
of attention, and there are several variants of the join operation.
Condition Joins
The most general version of the join operation accepts a join condition c and a pair of
relation instances as arguments, and returns a relation instance. The join condition is
identical to a selection condition in form. The operation is defined as follows:
R 𝖺⊳c S = σc(R × S)
Equijoin
A common special case of the join operation R 𝖺⊳ S is when the join condition con- sists
solely of equalities (connected by 𝖠) of the form R.name1 = S.name2, that is, equalities
between two fields in R and S. In this case, obviously, there is some redun- dancy in
retaining both attributes in the result.
Natural Join
A further special case of the join operation R 𝖺⊳ S is an equijoin in which equalities are
specified on all fields having the same name in R and S. In this case, we can simply omit
the join condition; the default is that the join condition is a collection of equalities on all
common fields.
Non Equi Join
50
The SQL NON EQUI JOIN uses comparison operator instead of the equal sign like >, <, >=,
<= along with conditions.
SELECT *
NESTED QUERIES
A nested query is a querythat has another query embedded within it; the embedded
query is called a subquery.
(Q1) Find the names of sailors who have reserved boat 103.
SELECT [Link]
FROM Sailors S
WHERE [Link] IN ( SELECT [Link]
FROM Reserves R
WHERE [Link] = 103 )
(Q2) Find the names of sailors who have reserved a red boat.
SELECT
[Link]
FROM Sailors S
WHERE [Link] IN ( SELECT [Link]
FROM Reserves R
WHERE [Link] IN ( SELECT [Link]
FROM Boats B
WHERE [Link] = ‘red’ )
(Q3) Find the names of sailors who have not reserved a red boat.
SELECT [Link]
FROM Sailors S
WHERE [Link] NOT IN ( SELECT [Link]
FROM Reserves R
WHERE [Link] IN ( SELECT [Link]
FROM Boats B
WHERE [Link] = ‘red’ )
51
Correlated Nested Queries
In the nested queries that we have seen thus far, the inner subquery has been completely
independent of the outer query:
(Q1) Find the names of sailors who have reserved boat number 103.
SELECT [Link]
FROM Sailors S
WHERE EXISTS (
SELECT *FROM
Reserves
WHERE [Link] = 103
AND [Link] = [Link] )
Set-Comparison Operators
(Q1) Find sailors whose rating is better than some sailor called Horatio.
SELECT [Link]
FROM Sailors S
WHERE [Link] > ANY ( SELECT [Link]
FROM Sailors S2
WHERE [Link] = ‘Horatio’ )
SELECT [Link]
FROM Sailors S
WHERE [Link] >= ALL ( SELECT
[Link] FROM Sailors S2 )
(Q1) Find the names of sailors who have reserved both a red and a green boat.
SELECT [Link]
FROM Sailors S, Reserves R, Boats B
WHERE [Link] = [Link] AND [Link] = [Link] AND [Link] =
‘red’AND [Link] IN ( SELECT [Link]
FROM Sailors S2, Boats B2, Reserves R2
WHERE [Link] = [Link] AND [Link] =
[Link]
AND [Link] = ‘green’ )
52
Noncorrelated
There are two kind of subquery in SQL one is called non-correlated and other is called
correlated subquery. In non correlated subquery, inner query doesn't depend on outer
query and can run as stand alone [Link] used along-with IN or NOT IN sql clause
is good examples of Noncorrelated subquery in SQL. Let's a noncorrelated subquery
example to understand it better
NonCorrelated subquery are used along-with IN and NOT IN clause. here is an example
of subquery with IN clause in SQL.
SQL query: Find all stocks from United States and India
mysql> SELECT COMPANY FROM Stock WHERE LISTED_ON_EXCHANGE IN (SELECT RIC FRO
AGGREGATE OPERATORS
We now consider a powerful class of constructs for computing aggregate values such as
MIN
and SUM.
54
(Q2) Find the average age of sailors with a rating of 10.
NULL VALUES
we have assumed that column values in a row are always known. In practice column values
can be unknown. For example, when a sailor, say Dan, joins a yacht club, he may not yet
have a rating assigned. Since the definition for the Sailors table has a rating column, what
row should we insert for Dan? What is needed here is a special value that denotes unknown.
SQL provides a special column value called null to use in such situations. We use null
when the column value is either unknown or inapplicable. Using our Sailor table definition,
we might enter the row 〈 98, Dan, null, 39 〉 to represent Dan. The presence of null values
complicates many issues, and we consider the impact of null values on SQL in this section.
Comparisons Using Null Values
Consider a comparison such as rating = 8. If this is applied to the row for Dan, is this
condition true or false? Since Dan’s rating is unknown, it is reasonable to say that this
comparison should evaluate to the value unknown.
SQL also provides a special comparison operator IS NULL to test whether a column value
is null; for example, we can say rating IS NULL, which would evaluate to true on the row
representing Dan. We can also say rating IS NOT NULL, which would evaluate to false on
the row for Dan.
55
Logical Connectives AND, OR, and NOT
Now, what about boolean expressions such as rating = 8 OR age < 40 and rating = 8
AND age < 40? Considering the row for Dan again, because age < 40, the first expression
evaluates to true regardless of the value of rating, but what about the second?We can only
say unknown.
Q32) Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18
years old) for each rating level with at least two such sailors.
Q3) For each red boat, find the number of reservations for this boat.
(Q4) Find the average age of sailors for each rating level that has at least two sailors.
56
(Q5) Find the average age of sailors who are of voting age (i.e., at least 18 years old) for
57
each rating level that has at least two sailors.
(Q6) Find the average age of sailors who are of voting age (i.e., at least 18 years
old) for each rating level that has at least two such sailors.
The above formulation of the query reflects the fact that it is a variant of Q35. The answer
to Q36 on instance S3 is shown in Figure 5.16. It differs from the answer to Q35 in that
there is no tuple for rating 10, since there is only one tuple with rating 10 and age
≥ 18.
This formulation of Q36 takes advantage of the fact that the WHERE clause is applied
before grouping is done; thus, only sailors with age > 18 are left when grouping is done.
It is instructive to consider yet another way of writing this query:
SELECT [Link], [Link]
FROM ( SELECT [Link], AVG ( [Link] ) AS
avgage, COUNT (*)
AS ratingcount
FROM Sailors S WHERE S. age > 18 GROUP BY [Link] ) AS
TempWHERE [Link] > 1
58