0% found this document useful (0 votes)
16 views37 pages

Cse CSPC403 DBMS-15-51

unit-4

Uploaded by

drunanaji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views37 pages

Cse CSPC403 DBMS-15-51

unit-4

Uploaded by

drunanaji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT – II Relational Approach

Relational Model – Relational Data Structure – Relational Data Integrity – Domain Constraints – Entity Integrity –
Referential Integrity – Operational Constraints – Keys – Relational Algebra – Fundamental operations – Additional
Operations –Relational Calculus - Tuple Relational Calculus – Domain Relational Calculus - SQL – Basic Structure –
Set operations – Aggregate Functions – Null values – Nested Sub queries – Derived Relations – Views – Modification
of the database – Joined Relations – Data Definition Language – Triggers.

Relational Model
Relational model can represent as a table with columns and rows. Each row is known as a tuple. Each table of
the column has a name or attribute.
Domain: It contains a set of atomic values that an attribute can take.
Attribute: It contains the name of a column in a particular table. Each attribute Ai must have a domain,
dom(Ai)
Relational instance: In the relational database system, the relational instance is represented by a finite set of
tuples. Relation instances do not have duplicate tuples.
Relational schema: A relational schema contains the name of the relation and name of all columns or
attributes.
Relational key: In the relational key, each row has one or more attributes. It can identify the row in the relation
uniquely.
Example: STUDENT Relation

NAME ROLL_NO PHONE_NO ADDRESS AGE

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 9028 9i3988 Delhi 40

o In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the attributes.
o The instance of schema STUDENT has 5 tuples.
o t3 = <Laxman, 33289, 8583287182, Gurugram, 20>

Properties of Relations
o Name of the relation is distinct from all other relations.
o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence

Relational Data Structure


The database and the database structure are defined in the installation process. The structure of the database
depends on whether the database is Oracle Database, IBM® DB2®, or Microsoft SQL Server. A database that
can be perceived as a set of tables and manipulated in accordance with the relational model of data. Each
database includes:
• a set of system catalog tables that describe the logical and physical structure of the data
• a configuration file containing the parameter values allocated for the database
• a recovery log with ongoing transactions and archivable transactions
Component Description

Data A repository of information about the application programs, databases, logical data models,
dictionary and authorizations for an organization.
When you change the data dictionary, the change process includes edit checks that can
prevent the data dictionary from being corrupted. The only way to recover a data dictionary
is to restore it from a backup.
Container A data storage location, for example, a file, directory, or device that is used to define a
database.
Storage A logical unit of storage in a database such as a collection of containers. Database storage
partition partitions are called table spaces in DB2 and Oracle, and called file groups in SQL Server.
Business A tangible entity within an application that users create, access, and manipulates while
object performing a use case. Business objects within a system are typically stateful, persistent,
and long-lived. Business objects contain business data and model the business behavior.
Database An object that exists in an installation of a database system, such as an instance, a database,
object a database partition group, a buffer pool, a table, or an index. A database object holds data
and has no behavior.

Table A database object that holds a collection of data for a specific topic. Tables consist of rows
and columns.

Column The vertical component of a database table. A column has a name and a particular data type
for example, character, decimal, or integer.

Row The horizontal component of a table, consisting of a sequence of values, one for each
column of the table.
View A logical table that is based on data stored in an underlying set of tables. The data returned
by a view is determined by a SELECT statement that is run on the underlying tables.

Index A set of pointers that is logically ordered by the values of a key. Indexes provide quick
access to data and can enforce uniqueness of the key values for the rows in the table.

Relationship A link between one or more objects that is created by specifying a join statement.
Join An SQL relational operation in which data can be retrieved from two tables, typically based
on a join condition specifying join columns.
Table 1. Database hierarchy
• Data dictionary tables
The structure of a relational database is stored in the data dictionary tables of the database.
• Integrity checker
The integrity checker is a database configuration utility that you can use to assesses the health of the base layer
data dictionary. The tool compares the data dictionary with the underlying physical database schema. If errors
are detected, the tool produces error messages detailing how to resolve the issues.
• Storage partitions
A database storage partition is the location where a database object is stored on a disk. Database storage
partitions are called table spaces in DB2 and Oracle, and called file groups in SQL Server.
• Business objects
A business object is an object that has a set of attributes and values, operations, and relationships to other
business objects. Business objects contain business data and model the business behaviour.
• User-defined objects
Objects can be created in two ways: you can create an object in the database or an object can be natively
defined in the database. User-defined objects are always created in the Database Configuration application.
• Configuration levels for objects
Levels describe the scope of objects and must be applied to objects. Depending on the level that you assign to
objects, you must create certain attributes. For users to access an object, an attribute value must exist at the
level to which they have authority. The level that you assign to an object sometimes depends on the level of
the record in the database.
• Database relationships
Database relationships are associations between tables that are created using join statements to retrieve data.
• Business object attributes
Attributes of business objects contain the data that is associated with a business object. A persistent attribute
represents a database table column or a database view column. A nonpersistent attribute exists in memory
only, because the data that is associated with the attribute is not stored in the database.
• Attribute data types
Each database record contains multiple attributes. Every attribute has an associated data type.
• Database views
A database view is a subset of a database and is based on a query that runs on one or more database tables.
Database views are saved in the database as named queries and can be used to save frequently used, complex
queries.
• Indexes
You can use indexes to optimize performance for fetching data. Indexes provide pointers to locations of
frequently accessed data. You can create an index on the columns in an object that you frequently query.
• Primary keys
When you assign a primary key to an attribute, the key uniquely identifies the object that is associated with
that attribute. The value in the primary column determines which attributes are used to create the primary key.
Structure of Relational Database
1. A relational database consists of a collection of tables, each having a unique name.
A row in a table represents a relationship among a set of values.
Thus a table represents a collection of relationships.
2. There is a direct correspondence between the concept of a table and the mathematical concept of a relation.
A substantial theory has been developed for relational databases.

Relational Data Integrity


It is evident that most of the relations have an attribute, which can uniquely identify each tuple in the relation.
In some cases there can be more than one attribute, which can uniquely identify each tuple in the relation. This
attribute is called the candidate key. In other words a candidate key is an attribute that can uniquely identify a
row in a table.
ELEMENT Table

In the above table, the attributes symbol, name and atomic number can uniquely identify each row, so any one
can be a candidate key, or the ELEMENT_TABLE has three candidate keys. Since the body of a relation is a
set and sets by definition do not contain duplicate elements, it follows that at any given time no two tuples (or
rows) of a relation can be duplicates of each other (or in other words no two rows can be the same). Let R be
the relation with attributes Al, A2 An. The set of attributes K=(Ai,Aj, An) of R is said to be a candidate key
of R if and only if the following two properties are satisfied:
• Uniqueness - At any given time, no two distinct tuples (rows) of R have the same value for Ai, the same
value for Aj and the same value for An.
• Minimality - No proper subset of the set (Ai, Aj, An) has the uniqueness property.
Every relation has at least one candidate key, because at least the combination of all its attributes has the
uniqueness property. In the case of base relations (relations of a base table), one candidate key is designated
as the primary key and the remaining candidate keys are called alternate keys. For example in the
ELEMENT_TABLE, the relation has three candidate keys. We can choose any one of them as the primary
key. So if we choose the symbol as the primary key, then the name and atomic number become alternate keys.
But there are no hard and fast rules on how to choose the primary key from the list of candidate keys; it is a
matter of preference and convenience of the database designer.
The terms candidate keys and primary keys should not be abbreviated to just 'keys'. The term 'key' has too
many meanings in the database world. In the relational model alone, there are candidate keys, primary keys,
alternate keys, foreign keys, search keys, parent keys, encryption keys, decryption keys, and so on. So it is
better to qualify the word 'key' with the appropriate title to avoid confusion. Consider the following two tables.
One is the ELEMENT_TABLE and the other the SHIPMENTJTABLE.
SHIPMENT Table

Let us take a look at the attribute 'Item' of relation SHIPMENTJTABLE. It is clear that a given value for that
attribute, say item 'Au' should be permitted to appear in the database only if the same value appears as a value
of the primary key 'Symbol' in the relation ELEMENT_TABLE. Such an attribute is called a foreign key. Or
in other words, a foreign key is an attribute or attribute combination of one relation (table) whose values are
required to match those of the primary key of some other relation (table). Also the foreign key and the primary
key should be defined on the same underlying domain.
Primary Key - Foreign Key relationship

From the above discussions we are now able to identify many integrity rules (or constraints) for the relational
model. Relational data model includes several types of constraints whose purpose is to maintain the accuracy
and integrity of the data in the database. The major types of integrity constraints are:
• Domain Constraints
• Entity Integrity
• Referential Integrity
• Operational Constraints
Domain Constraints
All the values that appear in a column of a relation (table) must be taken from the same domain. As we have seen
before, a domain is a set of values that may be assigned to an attribute. A domain definition usually consists of the
following components:

• Domain name
• Meaning
• Data Type
• Size or Length
• Allowable values or Allowable range (if applicable)
For example, in the ELEMENT table, the domain for the column Symbol is a character of length 2, and should be
from the list of the elements. In other, words, the domain of the column Symbol is a value whose maximum length
is 2 characters and the first letter is in uppercase and it should be a value from the periodic table of elements.
Similarly the domain of the column atomic number is an integer and so on.

Attributes have specific values in real-world scenario. For example, age can only be a positive integer. The
same constraints have been tried to employ on the attributes of a relation. Every attribute is bound to have a
specific range of values. For example, age cannot be less than zero and telephone numbers cannot contain a
digit outside 0-9.
Definition: Domain constraints are user defined data type and we can define them like this:
Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY /
CHECK / DEFAULT)
Example:
For example I want to create a table “student_info” with “stu_id” field having value greater than 100, I can
create a domain and table like this:
create domain id_value int
constraint id_test
check(value > 100);
create table student_info (
stu_id id_value PRIMARY KEY,
stu_name varchar(30),
stu_age int
);
• Domain constraint defines the domain or set of values for an attribute.
• It specifies that the value taken by the attribute must be the atomic value from its domain.
Example-
Consider the following Student table-

STU_ID Name Age

S001 Akshay 20

S002 Abhishek 21

S003 Shashank 20

S004 Rahul A
Here, value ‘A’ is not allowed since only integer values can be taken by the age attribute.
Entity Integrity
An entity is any person, place, or thing to be recorded in a database. Each table represents an entity, and each row
of a table represents an instance of that entity. For example, if order is an entity, the orderstable represents the idea
of an order and each row in the table represents a specific order.

To identify each row in a table, the table must have a primary key. The primary key is a unique value that identifies
each row. This requirement is called theentity integrity constraint. The entity integrity rule is designed to assure
that every relation has a primary key, and that the data values for that primary key are all valid. Entity integrity
guarantees that every primary key attribute is non-null. No attribute participating in the primary key of a base
relation is allowed to contain nulls. Primary key performs the unique identification function in a relational model.
Thus a null primary key value within a base relation would be like saying that mere was some entity that had no
known identity. An entity that cannot be identified is a contradiction in terms, hence the name entity integrity. In
some cases, a particular attribute cannot be assigned a data value. There are two situations where this is likely to
occur:
• There is no applicable data value
• Applicable data value is not known when the values are assigned
For example, consider a situation where you are filling out your personal details. There is a column for fax number
and you don't have a fax number. You will leave the field blank. This is an example of no applicable data value. In
another case, suppose you are filling the ELEMENT table, you do not know the melting point for Nickel. You
know that Nickel has a melting point, but you do not know the exact value at that point in time. So you leave that
field blank since that information is not known at that point.

The relational model allows you to assign a null value to an attribute in the above-described situations. A null is a
value that is assigned to an attribute when no other value applies, or when the applicable value is unknown. In
reality, a null is not a value, but rather the absence of a value. For example, null is not the same as 0 (for numeric
fields) or blank (for character fields). The inclusion of nulls in the relational model is somewhat controversial, since
operations involving nulls sometimes leads to unpredictable results. On the other hand using null for missing values
is a good idea. But whatever the pros and cons of using null, it is imperative that the primary key values be non-
null.

• Entity integrity constraint specifies that no attribute of primary key must contain a null value in any
relation.
• This is because the presence of null value in the primary key violates the uniqueness property.
Example-
Consider the following Student table-

STU_ID Name Age

S001 Akshay 20

S002 Abhishek 21

S003 Shashank 20

S004 Rahul 20

This relation does not satisfy the entity integrity constraint as here the primary key contains a NULL value.
Referential Integrity
Referential integrity refers to the relationship between tables. Because each table in a database must have a primary
key, this primary key can appear in other tables because of its relationship to data within those tables. When a
primary key from one table appears in another table, it is called aforeign key. Foreign keys join tables and establish
dependencies between tables. Tables can form a hierarchy of dependencies in such a way that if you change or
delete a row in one table, you destroy the meaning of rows in other tables.
In the relational data model, associations between tables are defined using foreign keys. For example, the
association between the ELEMENT and the SHIPMENT tables is defined by including the Symbol attribute as a
foreign key in the SHIPMENT table. This implies that before we insert a new row in the SHIPMENT table, the
element for that order must already exist in the ELEMENT table. If you examine the rows in the SHIPMENT table,
you will find that every item name in that table appears in the ELEMENT table.
A referential integrity constraint is a rule that maintains consistency among the rows of two tables (relations). The
rule states that if there is a foreign key in one relation, either each foreign key value must match a primary key
value in the other table or else the foreign key value must be null.
If base relation (table) includes a foreign key- PR matching the primary key PK of some other base relation, then
every value of FK in the first table must either be equal to the value of PK in some tuple (row) of the second table
or be wholly null (that is each attribute value participating in that FK value must be null). Or in other words, a
given foreign key value must have matching primary key value in some tuple of the referenced relation if that
foreign key value is non-null. Sometimes, it is necessary to permit foreign keys to accept nulls. Here it must be
noted that the null are of the variety 'value does not exist' rather than 'value unknown'.

• This constraint is enforced when a foreign key references the primary key of a relation.
• It specifies that all the values taken by the foreign key must either be available in the relation of the
primary key or be null.
Important Results-
The following two important results emerges out due to referential integrity constraint-
• We can not insert a record into a referencing relation if the corresponding record does not exist in the
referenced relation.
• We can not delete or update a record of the referenced relation if the corresponding record exists in the
referencing relation.
Example-
Consider the following two relations- ‘Student’ and ‘Department’.
Here, relation ‘Student’ references the relation ‘Department’.

Student
Department
STU_ID Name Dept_no
Dept_no Dept_name
S001 Akshay D10
D10 ASET
S002 Abhishek D10
D11 ALS
S003 Shashank D11
D12 ASFL
S004 Rahul D14
D13 ASHS

Here,
• The relation ‘Student’ does not satisfy the referential integrity constraint.
• This is because in relation ‘Department’, no value of primary key specifies department no. 14.
• Thus, referential integrity constraint is violated.
Handling Violation of Referential Integrity Constraint-
To ensure the correctness of the database, it is important to handle the violation of referential integrity
constraint properly.
Operational Constraints
These are the constraints enforced in the database by the business rules or real world limitations. For example, if
the retirement age of the employees in an organization is 60, then the age column of the employee table can have
a constraint "Age should be less than or equal to 60." These kinds of constraints, enforced by the business and the
environment are called operational constraints.
Four basic update operations performed on relational database model are
Insert, update, delete and select.
• Insert is used to insert data into the relation
• Delete is used to delete tuples from the table.
• Modify allows you to change the values of some attributes in existing tuples.
• Select allows you to choose a specific range of data.
Whenever one of these operations are applied, integrity constraints specified on the relational database schema
must never be violated.
Insert Operation
The insert operation gives values of the attribute for a new tuple which should be inserted into a relation.

Update Operation
You can see that in the below-given relation table CustomerName= 'Apple' is updated from Inactive to Active.

Delete Operation
To specify deletion, a condition on the attributes of the relation selects the tuple to be deleted.

In the above-given example, CustomerName= "Apple" is deleted from the table.


The Delete operation could violate referential integrity if the tuple which is deleted is referenced by foreign
keys from other tuples in the same database.
Select Operation

In the above-given example, CustomerName="Amazon" is selected.


Keys
• Keys play an important role in the relational database.
• It is used to uniquely identify any record or row of data from the table. It is also used to establish and
identify relationships between tables.
For example: In Student table, ID is used as a key because it is unique for each student. In PERSON table,
passport_number, license_number, SSN are keys since they are unique for each person.

Student Person
ID Name
Name DOB
Address Passport_Number
Course License_Number
SSN
Types of key:

1. Primary key
• It is the first key which is used to identify one and only one instance of an entity uniquely. An entity
can contain multiple keys as we saw in PERSON table. The key which is most suitable from those
lists become a primary key.
• In the EMPLOYEE table, ID can be primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary key
since they are also unique.
• For each entity, selection of the primary key is based on requirement and developers.

2. Candidate key
o A candidate key is an attribute or set of an attribute which can uniquely identify a tuple.
o The remaining attributes except for primary key are considered as a candidate key. The candidate
keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. Rest of the attributes like SSN,
Passport_Number, and License_Number, etc. are considered as a candidate key.

3. Super Key
Super key is a set of an attribute which can uniquely identify a tuple. Super key is a superset of a candidate
key.
For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME) the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can also be
a key.
The super key would be EMPLOYEE-ID, (EMPLOYEE_ID, EMPLOYEE-NAME), etc.
4. Foreign key
• Foreign keys are the column of the table which is used to point to the primary key of another table.
• In a company, every employee works in a specific department, and employee and department are two
different entities. So we can't store the information of the department in the employee table. That's
why we link these two tables through the primary key of one table.
• We add the primary key of the DEPARTMENT table, Department_Id as a new attribute in the
EMPLOYEE table.
• Now in the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.
Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process to obtain the result of the
query. It uses operators to perform queries. Types of Relational operation shown below.
Fundamental operations

1. Select Operation:
• The select operation selects tuples that satisfy a given predicate.
• It is denoted by sigma (σ).
i. Notation: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and NOT. These
relational can use as relational operators like =, ≠, ≥, <, >, ≤.
For example: LOAN Relation
BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300


Input:
i. σ BRANCH_NAME="perryride" (LOAN)
Output:
BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300


2. Project Operation:
• This operation shows the list of those attributes that we wish to appear in the result. Rest of the
attributes are eliminated from the table.
• It is denoted by ∏.
i. Notation: ∏ A1, A2, An (r)
Where
A1, A2, A3 is used as an attribute name of relation r.
Example: CUSTOMER RELATION
NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:
i. ∏ NAME, CITY (CUSTOMER)
Output:
NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn
3. Union Operation:
• Suppose there are two tuples R and S. The union operation contains all the tuples that are either in R
or S or both in R & S.
• It eliminates the duplicate tuples. It is denoted by ∪.
i. Notation: R ∪ S
A union operation must hold the following condition:
• R and S must have the attribute of the same number.
• Duplicate tuples are eliminated automatically.
Example:
DEPOSITOR RELATION BORROW RELATION
CUSTOMER_NAME ACCOUNT_NO CUSTOMER_NAME LOAN_NO

Johnson A-101 Jones L-17


Smith A-121
Smith L-23
Mayes A-321
Hayes L-15
Turner A-176
Jackson L-14
Johnson A-273
Curry L-93
Jones A-472

Lindsay A-284 Smith L-11

Williams L-17

Input:
i. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes
4. Set Intersection:
• Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in
both R & S.
• It is denoted by intersection ∩.
i. Notation: R ∩ S
Example: Using the above DEPOSITOR table and BORROW table
Input:
i. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME

Smith

Jones
5. Set Difference:
• Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in R
but not in S.
• It is denoted by intersection minus (-).
i. Notation: R - S
Example: Using the above DEPOSITOR table and BORROW table
Input:
i. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME

Jackson

Hayes

Willians

Curry
6. Cartesian product
• The Cartesian product is used to combine each row in one table with each row in the other table. It is
also known as a cross product.
• It is denoted by X.
i. Notation: E X D
Example:
EMPLOYEE DEPARTMENT
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

2 Harry C B Sales

3 John B C Legal

Input:
i. EMPLOYEE X DEPARTMENT
Output:
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales
1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

7. Rename Operation:
The rename operation is used to rename the output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
i. ρ(STUDENT1, STUDENT)

Additional Operations
Additional operations are defined in terms of the fundamental operations. They do not add power to the
algebra, but are useful to simplify common queries.
1. The Set Intersection Operation
Set intersection is denoted by , and returns a relation that contains tuples that are in both of its argument
relations.
It does not add any power as
r  s = r - (r - s)
To find all customers having both a loan and an account at the SFU branch, we write
ename(bname=SFU ⋈(Borrow))  ename(bname = SFU ⋈(deposit))
2. The Natural Join Operation
Often we want to simplify queries on a cartesian product.
For example, to find all customers having a loan at the bank and the cities in which they live, we
need borrow and customer relations:
borrow,ename,ecity(borrow.ename= customer. ename (borrow × customer))
Our selection predicate obtains only those tuples pertaining to only one cname.
This type of operation is very common, so we have the natural join, denoted by a ⋈ sign. Natural join
combines a cartesian product and a selection into one operation. It performs a selection forcing equality
on those attributes that appear in both relation schemes. Duplicates are removed as in all relation
operations.
To illustrate, we can rewrite the previous query as
ename,ecity(borrow ⋈ customer)
The resulting relation is shown below table.
ename ecity
Smith Burnaby
Hayes Burnaby
Jones Vancouver
Joining borrow and customer relations.
We can now make a more formal definition of natural join.
• Consider R and S to be sets of attributes.
• We denote attributes appearing in both relations by R  S.
• We denote attributes in either or both relations by R  S.
• Consider two relations r(R) and s(S).
• The natural join of r and s, denoted by r ⋈ s is a relation on scheme R  S.
• It is a projection onto R  S of a selection on r × s where the predicate requires r.Ʌ = s.Ʌ for each
attribute Ʌ in R  S.
Formally,
r ⋈ s =RS (r.A1=s.A1Ʌ r.A3Ʌ......Ʌr.An=s.An(r × s))
where R  S = {Ʌ1, Ʌ2,.....Ʌn}
To find the assets and names of all branches which have depositors living in Stamford, we
need customer, deposit and branch relations:
bname,assets(ecity = Stamford ⋈ (Customer ⋈ deposit ⋈ branch))
Note that ⋈ is associative.
To find all customers who have both an account and a loan at the SFU branch:
ename(bname=SFU ⋈(borrow ⋈ deposit))
This is equivalent to the set intersection version we wrote earlier. We see now that there can be several
ways to write a query in the relational algebra.
If two relations r(R) and s(S) have no attributes in common, then RS=, and r ⋈ s = r × s.
3. The Division Operation
Division, denoted ÷, is suited to queries that include the phrase ``for all''.
Suppose we want to find all the customers who have an account at all branches located in Brooklyn.
Strategy: think of it as three steps.
We can obtain the names of all branches located in Brooklyn by
r1 = bname(bcity=Brooklyn⋈(branch))
We can also find all cname, bname pairs for which the customer has an account by
r2 = ename,bname(deposit)
Now we need to find all customers who appear in r2 with every branch name in r1.
The divide operation provides exactly those customers:
ename,bname(deposit) ÷ bname(bcity=Brooklyn⋈(branch))
which is simply r2 ÷ r1.
Formally,
• Let r(R) and s(S) be relations.
• Let S  R.
• The relation r ÷s is a relation on scheme R - S.
• A tuple t is in r ÷s if for every tuple ts in s there is a tuple tr in r satisfying both of the following:
tr[S] = ts[S]
tr[R – S] = t[R – S]
• These conditions say that the R – S portion of a tuple t is in r ÷s if and only if there are tuples with
the r – s portion and the S portion in r for every value of the S portion in relation S.
We will look at this explanation in class more closely.
The division operation can be defined in terms of the fundamental operations.
Read the text for a more detailed explanation.
4. The Assignment Operation
Sometimes it is useful to be able to write a relational algebra expression in parts using a temporary
relation variable (as we did with r1 and r2 in the division example).
The assignment operation, denoted , works like assignment in a programming language.
We could rewrite our division definition as
temp  R – S (r)
temp – R – S ((temp × s) – r)
Relational Calculus
• 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.
• The relational calculus tells what to do but never explains how to do.
Types of Relational calculus:

Tuple Relational Calculus (TRC)


• The tuple relational calculus is specified to select the tuples in a relation. In TRC, filtering variable
uses the tuples of a relation.
• The result of the relation can have one or more tuples.
Notation:
1. {T | P (T)} or {T | Condition (T)}
Where
T is the resulting tuples
P(T) is the condition used to fetch T.
For example:
i. { T.name | Author(T) AND T.article = 'database' }
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:
i. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}
Output: This query will yield the same result as the previous one.
Domain Relational Calculus (DRC)
• The second form of relation is known as Domain relational calculus. In domain relational calculus,
filtering variable uses the domain of attributes.
• Domain relational calculus uses the same operators as tuple calculus. It uses logical connectives ∧
(and), ∨ (or) and ┓ (not).
• It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.
Notation:
1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where
a1, a2 are attributes
P stands for formula built by inner attributes
For example:
i. {< article, page, subject > | ∈ java ∧ subject = 'database'}
Output: This query will yield the article, page, and subject from the relational java, where the subject is a
database.
SQL
• SQL stands for Structured Query Language. It is used for storing and managing data in relational
database management system (RDMS).
• It is a standard language for Relational Database System. It enables a user to create, read, update and
delete relational databases and tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their
standard database language.
• SQL allows users to query the database in a number of ways, using English-like statements.
Rules:
SQL follows the following rules:
• Structure query language is not case sensitive. Generally, keywords of SQL are written in uppercase.
• Statements of SQL are dependent on text lines. We can use a single SQL statement on one or
multiple text line.
• Using the SQL statements, you can perform most of the actions in a database.
• SQL depends on tuple relational calculus and relational algebra.
SQL process:
• 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.
• In the process, various components are included. These components can be optimization Engine,
Query engine, Query dispatcher, classic, etc.
• All the non-SQL queries are handled by the classic query engine, but SQL query engine won't handle
logical files.
Basic Structure
A relational database is a collection of tables. Each table has its own unique name.
The basic structure of an SQL expression consists of three clauses:
• The select clause which corresponds to the projection operation. It is the list of attributes that will
appear in the resulting table.
• The from clause which corresponds to the Cartesian-product operation. It is the list of tables that will
be joined in the resulting table.
• The where clause which corresponds to the selection operation. It is the expression that controls the
which rows appear in the resulting table.
A typical SQL query has the form of:
select A1, A2, ..., An
from r1, r2, ..., rn,
where P
The query is the equivalent to the relational algebra expression
 A1, A2, ..., An ( P ( r1  r2  ...  rn ) )
The select Clause
Formal query languages are based on the mathematical notion of a relation being a set. Duplicate tuples never
appear in relations. In practice, duplicate elimination is relatively time consuming. SQL allows duplicates in
relations as well as the results of SQL expressions.
In those cases where we want to force the elimination of duplicates, we insert the keyword distinct after select.
The default is to retain duplicates. This can be explicitly required with the keyword all.
The asterisk symbol "*" can be used in place of listing all the attributes.
The clause can also contain arithmetic expressions involving the operators +, -, *, and /.
A dot notation is used when explicitly identifying the table that the attribute comes from: borrower.loan-
number
The from Clause
The from clause defines a Cartesian product of the tables in the clause.
The where Clause
SQL uses and, or and not (not symbols) and the comparison operators <, <=, >, >=, = , and <>. Also
available is between:
where amount between 90000 and 100000
Additional, not between can be used.
The rename Operation
SQL uses the as clause:
old_name as new_name
You can do pattern matching on strings, using like and special characters:
• % which matching any substring>/li>
• _ which matches any single character
• escape which allows you override another character:
o like "ab\%cd%" escape "\" which matches any strong that starts with "ab\cd"
Ordering the Display of Tuples
SQL uses the order by clause to control the order of the display of rows, either ascending (asc) or
descending (desc):
order by amount desc
Sorting a large number of tuples may be costly and its use should be limited.

Set operations
The SQL Set operation is used to combine the two or more SQL SELECT statements.
Types of Set Operation
1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union
• The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
• In the union operation, all the number of datatype and columns must be same in both the tables on
which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its resultset.

Syntax
i. SELECT column_name FROM table1
ii. UNION
iii. SELECT column_name FROM table2;
Example:
The First table
ID NAME ID NAME

1 Jack 3 Jackson

2 Harry 4 Stephan

3 Jackson 5 David
The Second table
Union SQL query will be:
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

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:
i. SELECT column_name FROM table1
ii. UNION ALL
iii. SELECT column_name FROM table2;
Example: Using the above First and Second table.
Union All query will be like:
i. SELECT * FROM First
ii. UNION ALL
iii. SELECT * FROM Second;
The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson
4 Stephan

5 David
3. Intersect
• It is used to combine two SELECT statements. The Intersect operation returns the common rows
from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax
i. SELECT column_name FROM table1
ii. INTERSECT
iii. SELECT column_name FROM table2;

Example:
Using the above First and Second table.
Intersect query will be:
i. SELECT * FROM First
ii. INTERSECT
iii. SELECT * FROM Second;
The resultset table will look like:

ID NAME

3 Jackson
4. Minus
• 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.
• It has no duplicates and data arranged in ascending order by default.
Syntax:
i. SELECT column_name FROM table1
ii. MINUS
iii. SELECT column_name FROM table2;
Example
Using the above First and Second table.
Minus query will be:
i. SELECT * FROM First
ii. MINUS
iii. SELECT * FROM Second;
The resultset table will look like:

ID NAME

1 Jack

2 Harry
Aggregate Functions
• SQL aggregation function is used to perform the calculations on multiple rows of a single column of
a table. It returns a single value.
• It is also used to summarize the data.
Types of SQL Aggregation Function

1. COUNT FUNCTION
• COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
• COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST

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

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120


Example: COUNT()
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:
10
Example: COUNT with WHERE
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
SELECT COUNT(DISTINCT COMPANY)
FROM PRODUCT_MAST;
Output:
3
Example: COUNT() with GROUP BY
SELECT COMPANY, COUNT(*)
FROM PRODUCT_MAST
GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
SELECT COMPANY, COUNT(*)
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>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
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output:
320
Example: SUM() with GROUP BY
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Example: SUM() with HAVING
SELECT COMPANY, SUM(COST)
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST)>=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
AVG()
or
AVG( [ALL|DISTINCT] expression )
Example:
SELECT AVG(COST)
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
MAX()
or
MAX( [ALL|DISTINCT] expression )
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
Output:
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
MIN()
or
MIN( [ALL|DISTINCT] expression )
Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
Null values
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field
that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is
different than a zero value or a field that contains spaces.
Syntax
The basic syntax of NULL while creating a table.
SQL> CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There
are two columns where we did not use NOT NULL, which means these columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
The NULL value can cause problems when selecting data. However, because when comparing an unknown
value to any other value, the result is always unknown and not included in the results. You must use the IS
NULL or IS NOT NULL operators to check for a NULL value.
Consider the following CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
Now, following is the usage of the IS NOT NULLoperator.
SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+----------+
Now, following is the usage of the IS NULL operator.
SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NULL;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
Nested Sub queries
In nested queries, a query is written inside a query. The result of inner query is used in execution of outer
query. We will use STUDENT, COURSE, STUDENT_COURSE tables for understanding nested queries.

STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE
C_ID C_NAME

C1 DSA

C2 Programming

C3 DBMS
STUDENT_COURSE
S_ID C_ID

S1 C1

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

There are mainly two types of nested queries:


• Independent Nested Queries: In independent nested queries, query execution starts from innermost
query to outermost queries. The execution of inner query is independent of outer query, but the result of
inner query is used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are
used in writing independent nested queries.
IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it with the
help of independent nested query and IN operator. From COURSE table, we can find out C_ID for C_NAME
‘DSA’ or DBMS’ and we can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’
STEP 2: Using C_ID of step 1 for finding S_ID
Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and outer query will return those S_IDs for which
C_ID is equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and S4.
• Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it
can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in
‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3. Second inner query will return
those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case) which are S1, S2
and S4. The outermost query will return those S_IDs where S_ID is not a member of set (S1, S2 and
S4). So it will return S3.
• Co-related Nested Queries: In co-related nested queries, the output of inner query depends on the row
which is being currently executed in outer query. e.g.; If we want to find out S_NAME of STUDENTs
who are enrolled in C_ID ‘C1’, it can be done with the help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
(select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);
For each row of STUDENT S, it will find the rows from STUDENT_COURSE where S.S_ID =
SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true and
corresponding S_ID will be returned as output.
Derived Relations
A subquery expression to be used in the from clause.
If such an expression is used, the result relation must be given a name, and the attributes can be renamed.
Find the average account balance of those branches where the average account balance is greater than $1,000.
select bname, avg-balance
from (select bname, avg(balance)
from account
group by (bname)
as result(bname, avg-balance)
where avg-balance > 1000
Find the average account balance of those branches where the average account balance is greater than $1200.
select branch-name, avg-balance
from (select branch-name, avg (balance)
as avg-balance from account
group by branch-name)
where avg-balance > 1200
Note that we do not need to use the having clause, since we compute the temporary (view) relation in the
FROM clause, and the attributes of result can be used directly in the where clause.
Views
• Views in SQL are considered as a virtual table. A view also contains rows and columns.
• To create the view, we can select the fields from one or more tables present in the database.
• A view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE

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:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
2. Creating View from a single table
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.
SELECT * FROM DetailsView;
Output:
NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the SELECT statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
NAME ADDRESS MARKS

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
DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;

Modification of the database


The SQL Modification Statements make changes to database data in tables and columns. There are 3
modification statements:
• INSERT Statement -- add rows to tables
• UPDATE Statement -- modify columns in table rows
• DELETE Statement -- remove rows from tables

INSERT Statement

The INSERT Statement adds one or more rows to a table. It has two formats:
INSERT INTO table-1 [(column-list)] VALUES (value-list)
and,
INSERT INTO table-1 [(column-list)] (query-specification)
The first form inserts a single row into table-1 and explicitly specifies the column values for the row. The
second form uses the result of query-specification to insert one or more rows into table-1. The result rows
from the query are the rows added to the insert table. Note: the query cannot reference table-1.
Both forms have an optional column-list specification. Only the columns listed will be assigned values.
Unlisted columns are set to null, so unlisted columns must allow nulls. The values from the VALUES
Clause (first form) or the columns from the query-specification rows (second form) are assigned to the
corresponding column in column-list in order.
If the optional column-list is missing, the default column list is substituted. The default column list contains
all columns in table-1 in the order they were declared in CREATE TABLE, or CREATE VIEW.

VALUES Clause

The VALUES Clause in the INSERT Statement provides a set of values to place in the columns of a new row.
It has the following general format:
VALUES ( value-1 [, value-2] ... )
value-1 and value-2 are Literal Values or Scalar Expressions involving literals. They can also specify NULL.
The values list in the VALUES clause must match the explicit or implicit column list for INSERT in degree
(number of items). They must also match the data type of corresponding column or be convertible to that data
type.

INSERT Examples

INSERT INTO p (pno, color) VALUES ('P4', 'Brown')


Before After
Pno descr color pno descr Color
P1 Widget Blue P1 Widget Blue
P2 Widget Red ➔ P2 Widget Red
P3 Dongle Green P3 Dongle Green
P4 NULL Brown
INSERT INTO sp
SELECT s.sno, p.pno, 500
FROM s, p
WHERE p.color='Green' AND s.city='London'
Before After
sno pno qty sno pno qty
S1 P1 NULL S1 P1 NULL
S2 P1 200 S2 P1 200

S3 P1 1000 S3 P1 1000
S3 P2 200 S3 P2 200
S2 P3 500

UPDATE Statement

The UPDATE statement modifies columns in selected table rows. It has the following general format:
UPDATE table-1 SET set-list [WHERE predicate]
The optional WHERE Clause has the same format as in the SELECT Statement. See WHERE Clause. The
WHERE clause chooses which table rows to update. If it is missing, all rows are in table-1 are updated.
The set-list contains assignments of new values for selected columns. See SET Clause.
The SET Clause expressions and WHERE Clause predicate can contain subqueries, but the subqueries cannot
reference table-1. This prevents situations where results are dependent on the order of processing.
SET Clause
The SET Clause in the UPDATE Statement updates (assigns new value to) columns in the selected table rows.
It has the following general format:
SET column-1 = value-1 [, column-2 = value-2] ...
column-1 and column-2 are columns in the Update table. value-1 and value-2 are expressions that can
reference columns from the update table. They also can be the keyword -- NULL, to set the column to null.
Since the assignment expressions can reference columns from the current row, the expressions are evaluated
first. After the values of all Set expressions have been computed, they are then assigned to the referenced
columns. This avoids results dependent on the order of processing.
UPDATE Examples
UPDATE sp SET qty = qty + 20
Before After
sno pno qty sno pno qty
S1 P1 NULL S1 P1 NULL
S2 P1 200 ➔ S2 P1 220
S3 P1 1000 S3 P1 1020
S3 P2 200 S3 P2 220
UPDATE s
SET name = 'Tony', city = 'Milan'
WHERE sno = 'S3'
Before After
sno name city sno name city
S1 Pierre Paris S1 Pierre Paris

S2 John London S2 John London
S3 Mario Rome S3 Tony Milan
DELETE Statement
The DELETE Statement removes selected rows from a table. It has the following general format:
DELETE FROM table-1 [WHERE predicate]
The optional WHERE Clause has the same format as in the SELECT Statement. See WHERE Clause. The
WHERE clause chooses which table rows to delete. If it is missing, all rows are in table-1 are removed.
The WHERE Clause predicate can contain subqueries, but the subqueries cannot reference table-1. This
prevents situations where results are dependent on the order of processing.
DELETE Examples
DELETE FROM sp WHERE pno = 'P1'
Before After
sno pno qty sno pno qty

S1 P1 NULL S3 P2 200
S2 P1 200
S3 P1 1000
S3 P2 200

DELETE FROM p WHERE pno NOT IN (SELECT pno FROM sp)


Before After
pno descr color pno descr color
P1 Widget Blue P1 Widget Blue

P2 Widget Red P2 Widget Red
P3 Dongle Green
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.
Types of SQL JOIN
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Sample Table
EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48


PROJECT

PROJECT_NO EMP_ID DEPARTMENT

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
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
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
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
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
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
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
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL
Marry NULL

Data Definition Language


DDL(Data Definition Language) : DDL or Data Definition Language actually consists of the SQL commands that can
be used to define the database schema. It simply deals with descriptions of the database schema and is used to create
and modify the structure of database objects in the database.
Examples of DDL commands:
• CREATE – is used to create the database or its objects (like table, index, function, views, store procedure and
triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including all spaces allocated for the records are
removed.
• COMMENT –is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.
Triggers
Trigger: A trigger is a stored procedure in database which automatically invokes whenever a special event in
the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or
when certain table columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run.
AFTER triggers run the trigger action after the triggering statement is run.
Example:
Given Student Report Database, in which student marks assessment is recorded. In such schema, create a
trigger so that the total and average of specified marks is automatically inserted whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
mysql> desc Student;
+-------+-------------+------+-----+---------+----------------+

You might also like