You are on page 1of 113

UNIT-2

Relational data model

Relational data model is the primary data model, which is used widely around
the world for data storage and processing. This model is simple and it has all
the properties and capabilities required to process data with storage efficiency.

RELATIONAL MODEL (RM) represents the database as a collection of


relations. A relation is nothing but a table of values. Every row in the table
represents a collection of related data values. These rows in the table denote
a real-world entity or relationship.

The table name and column names are helpful to interpret the meaning of
values in each row. The data are represented as a set of relations. In the
relational model, data are stored as tables. However, the physical storage of
the data is independent of the way the data are logically organized.

Some popular Relational Database management systems are:

 DB2 and Informix Dynamic Server - IBM


 Oracle and RDB – Oracle
 SQL Server and Access - Microsoft

Relational Model Concepts


1. Attribute: Each column in a Table. Attributes are the properties which
define a relation. e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the, relations are saved in the table
format. It is stored along with its entities. A table has two properties
rows and columns. Rows represent records and columns represent
attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single
record.
4. Relation Schema: A relation schema represents the name of the
relation with its attributes.
5. Degree: The total number of attributes which in the relation is called the
degree of the relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific
attribute.
8. Relation instance – Relation instance is a finite set of tuples in the
RDBMS system. Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is
called relation key.
10. Attribute domain – Every attribute has some pre-defined value
and scope which is known as attribute domain

Best Practices for creating a Relational Model


 Data need to be represented as a collection of relations
 Each relation should be depicted clearly in the table
 Rows should contain data about instances of an entity
 Columns must contain data about attributes of the entity
 Cells of the table should hold a single value
 Each column should be given a unique name
 No two rows can be identical
 The values of an attribute should be from the same domain

Advantages of using Relational model


 Simplicity: A relational data model is simpler than the hierarchical and
network model.
 Structural Independence: The relational database is only concerned
with data and not with a structure. This can improve the performance of
the model.
 Easy to use: The relational model is easy as tables consisting of rows
and columns is quite natural and simple to understand
 Query capability: It makes possible for a high-level query language like
SQL to avoid complex database navigation.
 Data independence: The structure of a database can be changed
without having to change any application.
 Scalable: Regarding a number of records, or rows, and the number of
fields, a database should be enlarged to enhance its usability.

Disadvantages of using Relational model


 Few relational databases have limits on field lengths which can't be
exceeded.
 Relational databases can sometimes become complex as the amount of
data grows, and the relations between pieces of data become more
complicated.
 Complex relational database systems may lead to isolated databases
where the information cannot be shared from one system to another.

Summary
 The Relational database model represents the database as a collection
of relations (tables)
 Attribute, Tables, Tuple, Relation Schema, Degree, Cardinality, Column,
Relation instance, are some important components of Relational Model
 Relational Integrity constraints are referred to conditions which must be
present for a valid relation
 Domain constraints can be violated if an attribute value is not appearing
in the corresponding domain or it is not of the appropriate data type
 Insert, Select, Modify and Delete are operations performed in Relational
Model
 The relational database is only concerned with data and not with a
structure which can improve the performance of the model
 Advantages of relational model is simplicity, structural independence,
ease of use, query capability, data independence, scalability.
 Few relational databases have limits on field lengths which can't be
exceeded.
UNIT-2
Codd’s Rules
Dr Edgar F. Codd, after his extensive research on the Relational Model of database
systems, came up with twelve rules of his own, which according to him, a database must
obey in order to be regarded as a true relational database.
These rules can be applied on any database system that manages stored data using
only its relational capabilities. This is a foundation rule, which acts as a base for all the
other rules.

Rule 1: Information Rule


The data stored in a database, may it be user data or metadata, must be a value of some
table cell. Everything in a database must be stored in a table format.

Rule 2: Guaranteed Access Rule


Every single data element (value) is guaranteed to be accessible logically with a
combination of table-name, primary-key (row value), and attribute-name (column value).
No other means, such as pointers, can be used to access data.

Rule 3: Systematic Treatment of NULL Values


The NULL values in a database must be given a systematic and uniform treatment. This
is a very important rule because a NULL can be interpreted as one the following − data
is missing, data is not known, or data is not applicable.

Rule 4: Active Online Catalog


The structure description of the entire database must be stored in an online catalog,
known as data dictionary, which can be accessed by authorized users. Users can use
the same query language to access the catalog which they use to access the database
itself.

Rule 5: Comprehensive Data Sub-Language Rule


A database can only be accessed using a language having linear syntax that supports
data definition, data manipulation, and transaction management operations. This
language can be used directly or by means of some application. If the database allows
access to data without any help of this language, then it is considered as a violation.

Rule 6: View Updating Rule


All the views of a database, which can theoretically be updated, must also be updatable
by the system.

Rule 7: High-Level Insert, Update, and Delete Rule


A database must support high-level insertion, updation, and deletion. This must not be
limited to a single row, that is, it must also support union, intersection and minus
operations to yield sets of data records.

Rule 8: Physical Data Independence


The data stored in a database must be independent of the applications that access the
database. Any change in the physical structure of a database must not have any impact
on how the data is being accessed by external applications.

Rule 9: Logical Data Independence


The logical data in a database must be independent of its user’s view (application). Any
change in logical data must not affect the applications using it. For example, if two tables
are merged or one is split into two different tables, there should be no impact or change
on the user application. This is one of the most difficult rule to apply.

Rule 10: Integrity Independence


A database must be independent of the application that uses it. All its integrity constraints
can be independently modified without the need of any change in the application. This
rule makes a database independent of the front-end application and its interface.

Rule 11: Distribution Independence


The end-user must not be able to see that the data is distributed over various locations.
Users should always get the impression that the data is located at one site only. This
rule has been regarded as the foundation of distributed database systems.

Rule 12: Non-Subversion Rule


If a system has an interface that provides access to low-level records, then the interface
must not be able to subvert the system and bypass security and integrity constraints.
Difference between DBMS and RDBMS
Although DBMS and RDBMS both are used to store information in physical database but
there are some remarkable differences between them.

No. DBMS RDBMS

1) DBMS applications store data as file. RDBMS applications store data in a tabular form.

2) In DBMS, data is generally stored in either In RDBMS, the tables have an identifier called primary
a hierarchical form or a navigational form.
key and the data values are stored in the form of tables.

3) Normalization is not present in DBMS. Normalization is present in RDBMS.

4) DBMS does not apply any security with RDBMS defines the integrity constraint for the purpose
regards to data manipulation.
of ACID (Atomocity, Consistency, Isolation and Durability)

property.

5) DBMS uses file system to store data, so in RDBMS, data values are stored in the form of tables, so
there will be no relation between the a relationship between these data values will be stored
tables.
in the form of a table as well.

6) DBMS has to provide some uniform RDBMS system supports a tabular structure of the data
methods to access the stored information.
and a relationship between them to access the stored

information.

7) DBMS does not support distributed RDBMS supports distributed database.


database.
8) DBMS is meant to be for small RDBMS is designed to handle large amount of data. it
organization and deal with small data. it supports multiple users.
supports single user.

9) Examples of DBMS are file Example of RDBMS are mysql, postgre, sql server,
systems, xml etc.
oracle etc.

The main differences between DBMS and RDBMS are given below:

After observing the differences between DBMS and RDBMS, you can say that RDBMS is an
extension of DBMS. There are many software products in the market today who are
compatible for both DBMS and RDBMS. Means today a RDBMS application is DBMS
application and vice-versa.
UNIT-2
Relational Integrity constraints
Relational Integrity constraints is referred to conditions which must be present
for a valid relation. These integrity constraints are derived from the rules in the
mini-world that the database represents.

There are many types of integrity constraints. Constraints on the Relational


database management system is mostly divided into three main categories
are:

1. Domain constraints
2. Key constraints
3. Referential integrity constraints

Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the
corresponding domain or it is not of the appropriate data type.

Domain constraints specify that within each tuple, and the value of each
attribute must be unique. This is specified as data types which include
standard data types integers, real numbers, characters, Booleans, variable
length strings, etc.

Example:

Create DOMAIN CustomerName


CHECK (value not NULL)

The example shown demonstrates creating a domain constraint such that


CustomerName is not NULL

Key constraints
An attribute that can uniquely identify a tuple in a relation is called the key of
the table. The value of the attribute for different tuples in the relation has to be
unique.
Example:

In the given table, CustomerID is a key attribute of Customer Table. It is most


likely to have a single key for one customer, CustomerID =1 is only for the
CustomerName =" Google".

CustomerID CustomerName Status

1 Google Active

2 Amazon Active

3 Apple Inactive

Referential integrity constraints


Referential integrity constraints is base on the concept of Foreign Keys. A
foreign key is an important attribute of a relation which should be referred to in
other relationships. Referential integrity constraint state happens where
relation refers to a key attribute of a different or same relation. However, that
key element must exist in the table.
Basic SQL Relational Algebra Operations

Relational Algebra divided in various groups

Unary Relational Operations

 SELECT (symbol: σ)
 PROJECT (symbol: π)
 RENAME (symbol: ρ)

Relational Algebra Operations From Set Theory

 UNION (U)
 INTERSECTION (∩),
 DIFFERENCE (-)
 CARTESIAN PRODUCT ( x )

SELECT (σ)

The SELECT operation is used for selecting a subset of the tuples


according to a given selection condition. Sigma (σ)Symbol denotes it.
It is used as an expression to choose tuples which meet the selection
condition. Select operator selects tuples that satisfy a given predicate.

σp(r)

σ is the predicate

r stands for relation which is the name of the table

p is prepositional logic
Select Operator (σ) Example
Table: CUSTOMER
---------------

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
CN00121 Shivendra Mumbai
CN00123 Mohit Mumbai
CN00125 Karan Noida
CN00127 Aman Delhi
CN00130 Virat Delhi

Query:

σ Customer_City="Mumbai" (CUSTOMER)

Output:

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
CN00121 Shivendra Mumbai
CN00123 Mohit Mumbai

Projection(π)

The projection eliminates all attributes of the input relation but those
mentioned in the projection list. The projection method defines a
relation that contains a vertical subset of Relation.

This helps to extract the values of specified attributes to eliminates


duplicate values. (pi) symbol is used to choose attributes from a
relation. This operator helps you to keep specific columns from a
relation and discards the other columns.
Table: CUSTOMER

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
CN00121 Shivendra Mumbai
CN00123 Mohit Mumbai
CN00125 Karan Noida
CN00127 Aman Delhi
CN00130 Virat Delhi

Query:

∏ Customer_Name, Customer_City (CUSTOMER)

Output:

Customer_Name Customer_City
------------- -------------
Shivendra Mumbai
Mohit Mumbai
Karan Noida
Aman Delhi
Virat Delhi

Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute
of a relation.

Rename (ρ) Syntax:


ρ(new_relation_name, old_relation_name)
Rename (ρ) Example
Lets say we have a table customer, we are fetching customer names and
we are renaming the resulted relation to CUST_NAMES.

Table: CUSTOMER

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
CN00121 Shivendra Mumbai
CN00123 Mohit Mumbai
CN00125 Karan Noida
CN00127 Aman Delhi
CN00130 Virat Delhi
Query:

ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))

Output:

CUST_NAMES
----------
Shivendra
Mohit
Karan
Aman
Virat

Union Operator (∪)


Union operator is denoted by ∪ symbol and it is used to select all the
rows (tuples) from two tables (relations).

Lets discuss union operator a bit more. Lets say we have two relations
R1 and R2 both have same columns and we want to select all the
tuples(rows) from these relations then we can apply the union operator
on these relations.

Note: The rows (tuples) that are present in both the tables will only
appear once in the union set. In short you can say that there are no
duplicates present after the union operation.

Syntax of Union Operator (∪)

table_name1 ∪ table_name2
Union Operator (∪) Example
Table 1: COURSE

Course_Id Student_Name Student_Id


--------- ------------ ----------
C101 Aditya SI701
C104 Aditya SI701
C106 Shivendra SI705
C109 Prateek SI707
C115 Ruchika SI711

Table 2: STUDENT

Student_Id Student_Name Student_Age


------------ ---------- -----------
SI701 Aditya 19
SI705 Shivendra 18
SI707 Prateek 19
SI711 Ruchika 17
S941 Virat 16
S951 Richa 18
Query:

∏ Student_Name (COURSE) ∪ ∏ Student_Name (STUDENT)

Output:

Student_Name

------------
Aditya
Virat
Prateek
Ruchika
Richa
Shivendra

Note: As you can see there are no duplicate names present in the output
even though we had few common names in both the tables, also in the
COURSE table we had the duplicate name itself.

Intersection Operator (∩)


Intersection operator is denoted by ∩ symbol and it is used to select
common rows (tuples) from two tables (relations).

Lets say we have two relations R1 and R2 both have same columns and
we want to select all those tuples(rows) that are present in both the
relations, then in that case we can apply intersection operation on these
two relations R1 ∩ R2.

Note: Only those rows that are present in both the tables will appear in
the result set.
Syntax of Intersection Operator (∩)

table_name1 ∩ table_name2

Intersection Operator (∩) Example


Lets take the same example that we have taken above.

Table 1: COURSE

Course_Id Student_Name Student_Id


--------- ------------ ----------
C101 Aditya SI701
C104 Aditya SI701
C106 Shivendra SI705
C109 Prateek SI707
C115 Ruchika SI711

Table 2: STUDENT

Student_Id Student_Name Student_Age


------------ ---------- -----------
SI701 Aditya 19
SI705 Shivendra 18
SI707 Prateek 19
SI711 Ruchika 17
S941 Virat 16
S951 Richa 18
Query:

∏ Student_Name (COURSE) ∩ ∏ Student_Name (STUDENT)


Output:

Student_Name
------------
Aditya
Shivendra
Prateek
Ruchika

Set Difference (-)


Set Difference is denoted by – symbol. Lets say we have two relations
R1 and R2 and we want to select all those tuples(rows) that are present
in Relation R1 but not present in Relation R2, this can be done using
Set difference R1 – R2.

Syntax of Set Difference (-)

table_name1 - table_name2

Set Difference (-) Example


Lets take the same tables COURSE and STUDENT that we have seen
above.

Query:
Lets write a query to select those student names that are present in
STUDENT table but not present in COURSE table.

∏ Student_Name (STUDENT) - ∏ Student_Name (COURSE)


Output:

Student_Name
------------
Virat
Richa
Relational Algebra:

Relational database systems are expected to be equipped with a query language that can assist
its users to query the database instances. There are two kinds of query languages − relational
algebra and relational calculus.
Relational algebra is a procedural query language, which takes instances of relations as input
and yields instances of relations as output. It uses operators to perform queries. An operator can
be either unary or binary. They accept relations as their input and yield relations as their
output. Relational algebra is performed recursively on a relation and intermediate results are
also considered relations. It collects instances of relations as input and gives occurrences of
relations as output. It uses various operations to perform this action. SQL Relational algebra
query operations are performed recursively on a relation. The output of these operations is a
new relation, which might be formed from one or more input relations.

Unary Relational Operations

 SELECT (symbol: σ)
 PROJECT (symbol: π)
 RENAME (symbol: ρ)

Relational Algebra Operations from Set Theory

 UNION (υ)
 INTERSECTION (Ո)
 DIFFERENCE (-)
 CARTESIAN PRODUCT ( x )

Binary Relational Operations

 JOIN
 DIVISION

Set Difference (−):

Example

Consider the following tables.

Table A Table B

column 1 column 2 column 1 column 2


1 1 1 1

1 2 1 3

The result of set difference operation is tuples, which are present in one relation but are not in
the second relation.
Notation: r − s
Finds all the tuples that are present in r but not in s.

- Symbol denotes it. The result of A - B, is a relation which includes all tuples that are in A but
not in B.

 The attribute name of A has to match with the attribute name in B.


 The two-operand relations A and B should be either compatible or Union compatible.
 It should be defined relation consisting of the tuples that are in relation A, but not in B.

Table A – B

column 1 column 2

1 2
Cartesian Product (Χ):

This type of operation is helpful to merge columns from two relations. Generally, a Cartesian
product is never a meaningful operation when it performs alone. However, it becomes
meaningful when it is followed by other operations.

It combines information of two different relations into one.


Notation − r Χ s
Where r and s are relations and their output will be defined as −
r Χ s = { q t | q ∈ r and t ∈ s}

σ column 2 = '1' (A X B)

Output – The above example shows all rows from relation A and B whose column 2 has value 1

σ column 2 = '1' (A X B)

column 1 column 2

1 1

1 1

Division operator (÷):

Division operator A÷B can be applied if and only if:

• Attributes of B is proper subset of Attributes of A.

• The relation returned by division operator will have attributes = (All attributes of A – All
Attributes of B)

• The relation returned by division operator will return those tuples from relation A which
are associated to every B’s tuple.

STUDENT_SPORTS

ROLL_NO SPORTS
1 Badminton

2 Cricket

2 Badminton

4 Badminton

ALL_SPORTS

SPORTS

Badminton

Cricket

• The operation is valid as attributes in ALL_SPORTS is a proper subset of attributes in


STUDENT_SPORTS.

• The attributes in resulting relation will have attributes {ROLL_NO,SPORTS}-


{SPORTS}=ROLL_NO

• The tuples in resulting relation will have those ROLL_NO which are associated with all
B’s tuple {Badminton, Cricket}. ROLL_NO 1 and 4 are associated to Badminton only.
ROLL_NO 2 is associated to all tuples of B. So the resulting relation will be:

STUDENT_SPORTS÷ ALL_SPORTS

ROLL_NO

2
Join Operations:
A Join operation combines related tuples from different relations, if and only if a given join
condition is satisfied. It is denoted by ⋈.

Example:

EMPLOYEE

EMP_CODE EMP_NAME

101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

Operation: (EMPLOYEE ⋈ SALARY)

Result:

EMP_CODE EMP_NAME SALARY


101 Stephan 50000

102 Jack 30000

103 Harry 25000

Types of Join operations:

1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:

Input:

∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

Output:
EMP_NAME SALARY

Stephan 50000

Jack 30000

Harry 25000

2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information.

Example:

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000


Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:

(EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

a. Left outer join


b. Right outer join
c. Full outer join

a. Left outer join:


o Left outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:
EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:


o Right outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad


Kuber HCL 30000 NULL NULL

c. Full outer join:


o Full outer join is like a left or right join except that it contains all rows from both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in S that have
no matching tuples in R in their common attribute name.
o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:

It is also known as an inner join. It is the most common join. It is based on matched data as per
the equality condition. The equi join uses the comparison operator(=).

Example:

CUSTOMER RELATION
CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

Input:

CUSTOMER ⋈ PRODUCT

Output:

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

2 Harry 2 Mumbai

3 Harry 3 Noida
Scanned by CamScanner
Scanned by CamScanner
RELATIONAL CALCULUS

In this section, we introduce another formal query language for the relational model
called relational calculus. In relational calculus, we write one declarative
expression to specify a retrieval request, and hence there is no description of how to
evaluate a query. A calculus expression specifies what is to be retrieved rather than
how to retrieve it. Therefore, the relational calculus is considered to be a
nonprocedural language. This differs from relational algebra, where we must write
a sequence of operations to specify a retrieval request; hence, it can be considered
as a procedural way of stating a query. It is possible to nest algebra operations to
form a single expression; however, a certain order among the operations is always
explicitly specified in a relational algebra expression. This order also influences the
strategy for evaluating the query. A calculus expression may be written in different
ways, but the way it is written has no bearing on how a query should be evaluated.

Difference between Relational Algebra and Relational


Calculus
Both Relational Algebra and Relational Calculus are the formal query languages.

Relational Algebra:
Relational Algebra is a Procedural language. In Relational Algebra, The order is
specified in which the operations have to be performed. In Relation Algebra frameworks
are created to implement the queries. The basic operation included in relational algebra
are:
1. Select (σ)
2. Project (Π)
3. Union (U)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

Relational Calculus:
Relational Calculus is the formal query language. It also known as Declarative
language. In Relational Calculus, The order is not specified in which the operation
have to be performed. Relational Calculus means what result we have to obtain.
Relational Calculus has two variations:

1. Tuple Relational Calculus (TRC)


2. Domain Relational Calculus (DRC)
Relational Calculus is denoted as:
{ t | P(t) }
Where,
t: the set of tuples
p: is the condition which is true for the given set of tuples.

Difference between Relational Algebra and Relational Calculus:

S.NO RELATIONAL ALGEBRA RELATIONAL CALCULUS

While Relational Calculus is

1. It is a Procedural language. Declarative language.

While Relational Calculus

Relational Algebra means how to obtain means what result we have to

2. the result. obtain.


In Relational Algebra, The order is

specified in which the operations have to While in Relational Calculus,

3. be performed. The order is not specified.

Relational Algebra is independent on While Relation Calculus can be

4. domain. a domain dependent.

While Relational Calculus is not

Relational Algebra is nearer to a nearer to programming

5. programming language. language.

When queries are optimized, the system will choose a particular sequence of
operations that corresponds to an execution strategy that can be executed efficiently.
It has been shown that any retrieval that can be specified in the basic relational
algebra can also be specified in relational calculus, and vice versa; in other words,
the expressive power of the two languages is identical. This led to the definition of
the concept of a relationally complete language. A relational query language L is
considered relationally complete if we can express in L any query that can be
expressed in relational calculus. Relational completeness has become an important
basis for comparing the expressive power of high-level query languages.
Most relational query languages are relationally complete but have more expressive
power than relational algebra or relational calculus because of additional operations
such as aggregate functions, grouping, and ordering.

Relational Calculus can be divided into two main parts:


1. Tuple Relational Calculus
2. Domain Relational Calculus
THE TUPLE RELATIONAL CALCULUS

Tuple Variables and Range Relations

The tuple relational calculus is based on specifying a number of tuple variables. Each
tuple variable usually ranges over a particular database relation, meaning that the
variable may take as its value any individual tuple from that relation. A simple tuple
relational calculus query is of the form

{ t | COND(t)}

where t is a tuple variable and COND(t) is a conditional expression involving t. The


result of such a query is the set of all tuples t that satisfy COND(t).
For example, to find all employees whose salary is above $50,000, we can write the
following tuple calculus expression:

{t | EMPLOYEE (t) and t.SALARy>50000}

The condition EMPLOYEE(t) specifies that the range relation of tuple variable t is
EMPLOYEE. Each EMPLOYEE tuple t that satisfies the condition
t.SALARy>50000 will be retrieved.
Notice that t.SALARY references attribute SALARY of tuple variable t; this
notation resembles how attribute names are qualified with relation names or aliases
in SQL.
The above query retrieves all attribute values for each selected EMPLOYEE tuple r.
To retrieve only some of the attributes-say, the first and last names-we write
{t.FNAME, t.LANME I EMPLOYEE(t) AND t.SALARy>50000}

Informally, we need to specify the following information in a tuple calculus


expression:
• For each tuple variable t, the range relation R of t. This value is specified by a
condition of the form R(t).

• A condition to select particular combinations of tuples. As tuple variables range


over their respective range relations, the condition is evaluated for every possible
combination of tuples to identify the selected combinations for which the condition
evaluates to TRUE.
• A set of attributes to be retrieved, the requested attributes. The values of these
attributes are retrieved for each selected combination of tuples. Before we discuss
the formal syntax of tuple relational calculus, consider another query.

QUERY 0
Retrieve the birth date and address of the employee (or employees) whose name is
'John B. Smith'.

QO: {t.BDATE, t.ADDRESS I EMPLOYEE(t) AND t.FNAME='John' AND


t.MINIT='B' AND t.LNAME='Smith'}

ln tuple relational calculus, we first specify the requested attributes t.BDATE and
t.ADDRESS for each selected tuple r. Then we specify the condition for selecting a
tuple following the bar ( | )-namely, that t be a tuple of the EMPLOYEE relation
whose FNAME, MINIT, and LNAME attribute values are 'John', 'B', and 'Smith',
respectively.

Expressions and Formulas in Tuple Relational Calculus

A general expression of the tuple relational calculus is of the form


{t1·Aj , t2·Ak, ••• ,tn·Am | COND(tl, t2, ... , tn , tn+ l , tn+2, ••• , tn+m)}
where tl, t2, ... , tn' tn+i' ... , tn+m are tuple variables, each Aj is an attribute of the
relation on which tj ranges, and COND is a condition or formula '< of the tuple
relational calculus.
A formula is made up of predicate calculus atoms, which can be one of the following:
1. An atom of the form R(t), where R is a relation name and tj is a tuple variable.
This atom identifies the range of the tuple variable ti as the relation whose name is
R.
2. An atom of the form ti.A op tj.B, where op is one of the comparison operators in
the set {=, <, ≤, >, ≥, ≠}, tj and tj are tuple variables, A is an attribute of the relation
on which ti ranges, and B is an attribute of the relation on which tj ranges.

3. An atom of the form ti.A op core op tj.B, where op is one of the comparison
operators in the set {=, <, ≤, >, ≥, ≠}, tj and tj are tuple variables, A is an attribute of
the relation on which tj ranges, B is an attribute of the relation on which tj ranges,
and c is a constant value.

Also called a well-formed formula, or wff, in mathernatical logic.

Each of the preceding atoms evaluates to either TRUE or FALSE for a specific
combination of tuples; this is called the truth value of an atom. In general, a tuple
variable t ranges over all possible tuples "in the universe." For atoms of the form
R(t), if t is assigned to a tuple that is a member of the specified relation R, the atom
is TRUE; otherwise, it is FALSE. In atoms of types 2 and 3, if the tuple variables
are assigned to tuples such that the values of the specified attributes of the tuples
satisfy the condition, then the atom is TRUE.

A formula (condition) is made up of one or more atoms connected via the logical
operators AND, OR, and NOT and is defined recursively as follows:
1. Every atom is a formula.
2. If F1 and F2 are formulas, then so are (F1 AND F2), (F1 OR F2), NOT (F1),
and NOT (F2). The truth values of these formulas are derived from their
component formulas F1 and F2 as follows:
a. (F1 AND F2) is TRUE if both F1 and F1 are TRUE; otherwise, it is FALSE.
b. (F1 OR F2) is FALSE if both F1 and F2 are FALSE; otherwise, it is TRUE.
c. NOT (F1) is TRUE if F1 is FALSE; it is FALSE if F1 is TRUE.
d. NOT (F2) is TRUE if F2 is FALSE; it is FALSE if F2 is TRUE.

The Existential and Universal Quantifiers


In addition, two special symbols called quantifiers can appear in formulas; these are
the universal quantifier (∀ ) and the existential quantifier (∃). Truth values for
formulas with quantifiers are described in rules 3 and 4 below; first, however, we
need to define the concepts of free and bound tuple variables in a formula.
Informally, a tuple variable t is bound if it is quantified, meaning that it appears in
an (∀ t) or (∃ t) clause; otherwise, it is free. Formally, we define a tuple variable in a
formula as free or bound according to the following rules:

• An occurrence of a tuple variable in a formula F that is an atom is free in F.


• An occurrence of a tuple variable t is free or bound in a formula made up of logical
Connectives (F1, And F2), (F1 OR F2), NOT (F2), and NOT (F2)-depending on
whether it is free or bound in F1 or F2 (if it occurs in either). Notice that in a formula
of the form F = (F1 AND F2) or F = (F1 OR F2), a tuple variable may be free in F1
and bound in F2, or vice versa; in this case, one occurrence of the tuple variable is
bound and the other is free in F.
• All free occurrences of a tuple variable t in F are bound in a formula F' of the form
F' = (∃ t)(F) or F' = (∀ t)(F). The tuple variable is bound to the quantifier specified
in F'. For example, consider the following formulas:

F1: D.DNAME=' RESEARCH'


F2: (∃ T) (D. DNUMBER=T. DNO)
F3: (∀ D) (D. MGRSSN= ‘333445555 ')

The tuple variable d is free in both F1 and F2, whereas it is bound to the (∀) quantifier
in F3. Variable t is bound to the (∃) quantifier in F2.
We can now give rules 3 and 4 for the definition of a formula we started earlier:
3. If F is a formula, then so is (∃ t)(F), where t is a tuple variable. The formula
(∃t)(F) is TRUE if the formula F evaluates to TRUE for some (at least one) tuple
assigned to free occurrences of tin F; otherwise, (3 t)(F) is FALSE.
4. If F is a formula, then so is (∀ t)(F), where t is a tuple variable. The formula
(∀t)(F) is TRUE if the formula F evaluates to TRUE for every tuple (in the universe)
assigned to free occurrences of tin F; otherwise, (∀ t)(F) is FALSE.
The (∃) quantifier is called an existential quantifier because a formula (∃ t)(F) is
TRUE if "there exists" some tuple that makes F TRUE. For the universal quantifier,
(∀t)(F) is TRUE if every possible tuple that can be assigned to free occurrences of t
in F is substituted for t, and F is TRUE for every such substitution.
It is called the universal or "for all" quantifier because every tuple in "the universe
of" tuples must make F TRUE to make the quantified formula TRUE.

Example Queries Using the Existential Quantifier


We will use some of the queries to give a flavor of how the same queries are specified
in relational algebra and in relational calculus. Notice that some queries are easier to
specify in the relational algebra than in the relational calculus, and vice versa.

QUERY 1
Retrieve the name and address of all employees who work for the 'Research'
department.

Q1: {t.FNAME, t.LNAME, t.ADDRESS I EMPLOYEE(t) AND (∃d)


(DEPARTMENT(d) AND d.DNAME='Research' AND d.DNUMBER=t.DNO) }

The only free tuple variables in a relational calculus expression should be those that
appear to the left of the bar ( | ). In Ql, t is the only free variable; it is then bound
successively to each tuple. If a tuple satisfies the conditions specified in Ql, the
attributes FNAME, LNAME, and ADDRESS are retrieved for each such tuple. The
conditions EMPLOYEE (t) and DEPARTMENT (d) specify the range relations for
t and d. The condition d.DNAME = 'Research' is a selection condition and
corresponds to a SELECT operation in the relational algebra, where as the condition
d.DNUMBER = t.DNO is a join condition and serves a similar purpose to the JOIN
operation.

QUERY 2
For every project located in 'Stafford', list the project number, the controlling
department number, and the department manager's last name, birth date, and address.

In Q2 there are two free tuple variables, p and m. Tuple variable d is bound to the
existential quantifier. The query condition is evaluated for every combination of
tuples assigned to p and m; and out of all possible combinations of tuples to which
p and m are bound, only the combinations that satisfy the condition are selected.
Several tuple variables in a query can range over the same relation. For example, to
specify the query Q8-for each employee, retrieve the employee's first and last name
and
the first and last name of his or her immediate supervisor-we specify two tuple
variables
e and s that both range over the EMPLOYEE relation:
QUERY 3’
Find the name of each employee who works on some project controlled by
department number 5. This is a variation of query 3 in which "all" is changed to
"some." In this case we need two join conditions and two existential quantifiers.

QUERY 4
Make a list of project numbers for projects that involve an employee whose last name
is 'Smith', either as a worker or as manager of the controlling department for the
project.

Compare this with the relational algebra version of this query in Section 6.5. The
UNION operation in relational algebra can usually be substituted with an OR
connective in relational calculus. In the next section we discuss the relationship
between the universal and existential quantifiers and show how one can be
transformed into the other.
Transforming the Universal and Existential Quantifiers
We now introduce some well-known transformations from mathematical logic that
relate the universal and existential quantifiers. It is possible to transform a universal
quantifier into an existential quantifier, and vice versa, to get an equivalent
expression. One general transformation can be described informally as follows:
Transform one type of quantifier into the other with negation (preceded by NOT);
AND and OR replace one another; a negated formula becomes un negated; and an
unnegated formula becomes negated. Some special cases of this transformation can
be stated as follows, where the == symbol stands for
equivalent to:

Using the Universal Quantifier


Whenever we use a universal quantifier, it is quite judicious to follow a few rules to
ensure that our expression makes sense. We discuss these rules with respect to Query
3.

QUERY 3
Find the names of employees who work on all the projects controlled by department
number 5. One way of specifying this query is by using the universal quantifier as
shown.
We want to make sure that a selected employee e works on all the projects controlled
by department 5, but the definition of universal quantifier says that to make the
quantified formula TRUE, the inner formula must be TRUE for all tuples in the
universe.
The trick is to exclude from the universal quantification all tuples that we are not
interested in by making the condition TRUE for all such tuples. This is necessary
because a universally quantified tuple variable, such as x in Q3, must evaluate to
TRUE for every possible tuple assigned to it to make the quantified formula TRUE.
The first tuples to exclude (by making them evaluate automatically to TRUE) are
those that are not in the relation R of interest. In Q3, using the expression NOT
(PROJECT(x)) inside the universally quantified formula evaluates to TRUE all
tuples x that are not in the PROJECT relation. Then we exclude the tuples we are
not interested in from R itself. In Q3, using the expression NOT (x.DNUM=5)
evaluates to TRUE all tuples x that are in the PROJECT relation but are not
controlled by department 5. Finally, we specify a condition F2 that must hold on all
the remaining tuples in R. Hence, we can explain Q3 as follows:

1. For the formula F' = (∀ x)(F) to be TRUE, we must have the formula F be TRUE
for all tuples in the universe that can be assigned to x. However, in Q3 we are only
interested in F being TRUE for all tuples of the PROJECT relation that are controlled
by department 5. Hence, the formula F is of the form (NOT (PROJECT(X)) OR F1).
The 'NOT(PROJECT(X)) OR ...' condition is TRUE for all tuples not in the
PROJECT relation and has the effect of eliminating these tuples from consideration
in the truth value of Fl' For every tuple in the PROJECT relation, FI must be TRUE
if F' is to be TRUE.

2. Using the same line of reasoning, we do not want to consider tuples in the
PROJECT relation that are not controlled by department number 5, since we are only
interested in PROJECT tuples whose DNUM = 5. We can therefore write:
IF (x.DNUM=5) THEN F2
which is equivalent to
(NOT (x.DNUM=5) OR F2)

3. Formula F1, hence, is of the form NOT (x.DNuM=5) OR F2. In the context of
Q3, this means that, for a tuple x in the PROJECT relation, either its DNUM, t5 or
it must satisfy F2.

4. Finally, F2 gives the condition that we want to hold for a selected EMPLOYEE
tuple: that the employee works on every PROJECT tuple that has not been excluded
yet. Such employee tuples are selected by the query.
In English, Q3 gives the following condition for selecting an EMPLOYEE tuple e:
For every tuple x in the PROJECT relation with X.DNUM = 5, there must exist a
tuple w in WORKS_ON such that W.ESSN = e.SSN and W.PNO = X.PNUMBER.
This is equivalent to saying that EMPLOYEE e works on every PROJECT x in
DEPARTMENT number 5.

Using the general transformation from universal to existential quantifiers given in


Section 6.6.5, we can rephrase the query in Q3 as shown in Q3A:

We now give some additional examples of queries that use quantifiers.

QUERY 6
Find the names of employees who have no dependents.

Using the general transformation rule, we can rephrase Q6 as follows:

QUERY 7
List the names of managers who have at least one dependent.

This query is handled by interpreting "managers who have at least one dependent"
as "managers for whom there exists some dependent."
Safe Expressions
Whenever we use universal quantifiers, existential quantifiers, or negation of
predicates in a calculus expression, we must make sure that the resulting expression
makes sense. A safe expression in relational calculus is one that is guaranteed to
yield a finite number of tuples as its result; otherwise, the expression is called unsafe.
For example, the expression

[t | NOT (EMPLOYEE(t))}

is unsafe because it yields all tuples in the universe that are not EMPLOYEE tuples,
which are infinitely numerous. If we follow the rules for Q3 discussed earlier, we
will get a safe expression when using universal quantifiers. We can define safe
expressions more precisely by introducing the concept of the domain of a tuple
relational calculus expression: This is the set of all values that either appear as
constant values in the expression or exist in any tuple in the relations referenced in
the expression.
The domain of [t | NOT(EMPLOYEE(t))} is the set of all attribute values appearing
in some tuple of the EMPLOYEE relation (for any attribute).
The domain of the expression Q3A would include all values appearing in
EMPLOYEE, PROJECT, and WORKS_ON (unioned with the value 5 appearing in
the query itself).
An expression is said to be safe if all values in its result are from the domain of the
expression. Notice that the result of [t I NOT(EMPLOYEE(t))} is unsafe, since it
will, in general, include tuples (and hence values) from outside the EMPLOYEE
relation; such values are not in the domain of the expression. All of our other
examples are safe expressions.

THE DOMAIN RELATIONAL CALCULUS


There is another type of relational calculus called the domain relational calculus, or
simply, domain calculus. While SQL (see Chapter 8), a language based on tuple
relational calculus, was being developed by IBM Research at San Jose, California,
another language called QBE (Query-By-Example) that is related to domain calculus
was being developed almost concurrently at IBM Research at Yorktown Heights,
New York. The formal specification of the domain calculus was proposed after the
development of the QBE system.
Domain calculus differs from tuple calculus in the type of variables used in formulas:
Rather than having variables range over tuples, the variables range over single values
from domains of attributes. To form a relation of degree n for a query result, we must
have n of these domain variables-one for each attribute. An expression of the domain
calculus is of the form
{Xl' X2' ... 'Xn I COND (XI' X2' ... ,Xn' Xn+l' Xn+2' ... 'xn+m)}

where Xl' X2' ... , x", Xn+l' x,,+2' ... , x,,+m are domain variables that range over
domains (of attributes), and COND is a condition or formula of the domain relational
calculus.
A formula is made up of atoms. The atoms of a formula are slightly different from
those for the tuple calculus and can be one of the following:

1. An atom of the form R(x1, x2, ... , xj ) , where R is the name of a relation of degree
j and each Xi ,1≤ i ≤ j is a domain variable. This atom states that a list of values of
(x1, x2, ... , xj )must be a tuple in the relation whose name is R, where Xi is the value
of the ith attribute value of the tuple. To make a domain calculus expression more
concise, we can drop the commas in a list of variables; thus, we can write

As in tuple calculus, atoms evaluate to either TRUE or FALSE for a specific set of
values, called the truth values of the atoms. In case 1, if the domain variables are
assigned values corresponding to a tuple of the specified relation R, then the atom is
TRUE. In cases 2 and 3, if the domain variables are assigned values that satisfy the
condition, then the atom is TRUE.
In a similar way to the tuple relational calculus, formulas are made up of atoms,
variables, and quantifiers, so we will not repeat the specifications for formulas here.
Some examples of queries specified in the domain calculus follow. We will use
lowercase letters l, m, n, ... , x, y, z for domain variables.

QUERY 0
Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.
We need ten variables for the EMPLOYEE relation, one to range over the domain
of each attribute in order. Of the ten variables q, r, s, ... , z, only u and v are free. We
first specify the requested attributes, BDATE and ADDRESS, by the free domain
variables u for BDATE and v for ADDRESS. Then we specify the condition for
selecting a tuple following the bar (|) namely, that the sequence of values assigned
to the variables qrstuvwxyz be a tuple of the EMPLOYEE relation and that the values
for q (FNAME), r (MINH), and s (LNAME) be 'John', 'B', and 'Smith', respectively.
For convenience, we will quantify only those variables actually appearing in a
condition (these would be q, r, and s in Q0 in the rest of our examples.
An alternative shorthand notation, used in QBE, for writing this query is to assign
the constants 'John', 'B', and 'Smith' directly as shown in Q0A. Here, all variables
not appearing to the left of the bar are implicitly existentially quantified.!"

QUERY 1
Retrieve the name and address of all employees who work for the 'Research'
department.

A condition relating two domain variables that range over attributes from two
relations, such as m = Z in Q1, is a join condition; whereas a condition that relates a
domain variable to a constant, such as l == 'Research', is a selection condition.

QUERY 6
Find the names of employees who have no dependents.

QUERY 7
List the names of managers who have at least one dependent.
SQL Operators
SQL statements generally contain some reserved words or characters that are used to
perform operations such as comparison and arithmetical operations etc. These reserved
words or characters are known as operators.

Generally there are three types of operators in SQL:

1. SQL Arithmetic Operators


2. SQL Comparison Operators
3. SQL Logical Operators

SQL Arithmetic Operators:


Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.

Example:

Operators Descriptions Examples

+ It is used to add containing values of both operands a+b will give


150

- It subtracts right hand operand from left hand operand a-b will give -
50

* It multiply both operand's values a*b will give


5000

/ It divides left hand operand by right hand operand b/a will give 2

% It divides left hand operand by right hand operand and b%a will give 0
returns reminder
SQL Comparison Operators:
Let's take two variables "a" and "b" that are valued 50 and 100.

Operator Description Example

= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true

!= This is used to check the value of both operands equal or not,if (a!=b) is
not condition become true. true

<> Examines the operand's value equal or not, if values are not (a<>b) is
equal condition is true true

> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true

< Examines the left operand value is less than right Operand, if (a<=""
yes condition becomes true td="">

>= Examines that the value of left operand is greater than or equal (a>=b) is
to the value of right operand or not,if yes condition become true not true

<= Examines that the value of left operand is less than or equal to (a<=b) is
the value of right operand or not, if yes condition becomes true true

!< Examines that the left operand value is not less than the right (a!<=""
operand value td="">

!> Examines that the value of left operand is not greater than the (a!>b) is
value of right operand true
SQL Logical Operators:
This is the list of logical operators used in SQL.

Operator Description

ALL this is used to compare a value to all values in another value set.

AND this operator allows the existence of multiple conditions in an SQL statement.

ANY this operator is used to compare the value in list according to the condition.

BETWEEN this operator is used to search for values, that are within a set of values

IN this operator is used to compare a value to that specified list value

NOT the NOT operator reverse the meaning of any logical operator

OR this operator is used to combine multiple conditions in SQL statements

EXISTS the EXISTS operator is used to search for the presence of a row in a specified
table

LIKE this operator is used to compare a value to similar values using wildcard
operator

SQL CREATE Database


The SQL CREATE DATABASE statement is used by a developer to create a database.

Let's see the syntax of SQL CREATE DATABASE:

CREATE DATABASE database_name;

If you want to add tables in that database, you can use CREATE TABLE statement.

Create Database in MySQL


In MySQL, same command is used to create a database.

CREATE DATABASE database_name;


Create Database in Oracle
You don't need to create database in Oracle. In Oracle database, you can create
tables directly.

SQL DROP Database


SQL DROP statement is used to delete or remove indexes from a table in the
database.

If you want to delete or drop an existing database in a SQL schema, you can use SQL
DROP DATABASE

Let's see the syntax of SQL DROP DATABASE:

DROP DATABASE database_name;

SQL RENAME Database


SQL RENAME DATABASE is used when you need to change the name of your database.
Sometimes it is used because you think that the original name is not more relevant to
the database or you want to give a temporary name to that database.

Let's see how to rename MySql and SQL Server databases.

Rename MySQL database


To rename the mysql database, you need to follow the following syntax:

RENAME DATABASE old_db_name TO new_db_name;

Rename SQL server database using T-SQL


This command is useful for SQL server 2005, 2008, 2008R2 and 2012.

ALTER DATABASE old_name MODIFY NAME = new_name

If you are using SQL server 2000, you can also use this command to rename the
database. But, Microsoft phased out it.

EXEC sp_renamedb 'old_name' , 'new_name'

SQL SELECT Database


In MySQL database, you need to select a database first before executing any query on
table, view etc. To do so, we use following query:

USE DATABASE database_name;

In oracle, you don't need to select database.

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term,
table is known as relation and row as tuple.

Note: A table has a specified number of columns, but can have any number of
rows.

Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.

Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and
"SALARY" are the column names. The combination of data of multiple columns forms a
row e.g. "Ankit", "Lucknow" and 15000 are the data of one row.

SQL TABLE Variable


The SQL Table variable is used to create, modify, rename, copy and delete tables.
Table variable was introduced by Microsoft.

It was introduced with SQL server 2000 to be an alternative of temporary tables.

It is a variable where we temporary store records and results. This is same like temp
table but in the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks
like CREATE TABLE syntax.

create table "tablename"


("column1" "data type",
"column2" "data type",
...
"columnN" "data type");

When a transaction rolled back the data associated with table variable is not rolled back.

A table variable generally uses lesser resources than a temporary variable.

Table variable cannot be used as an input or an output parameter.

SQL CREATE TABLE


SQL CREATE TABLE statement is used to create table in a database.

If you want to create a table, you should name the table and define its column and each
column's data type.

Let's see the simple syntax to create the table.

create table "tablename"


("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");

The data type of the columns may vary from one database to another. For example,

NUMBER is supported in Oracle database for integer value whereas INT is supported in MySQL.

Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL

are the constraint showing that these fields cannot be NULL while creating records in the
table.

SQL> CREATE TABLE STUDENTS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
);

You can verify it, if you have created the table successfully by looking at the message displayed

by the SQL Server, else you can use DESC command as follows:

SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

4 rows in set (0.00 sec)

Now you have the STUDENTS table available in your database and you can use to store required

information related to students.

SQL CREATE TABLE Example in MySQL


Let's see the command to create a table in MySQL database.

CREATE TABLE Employee


(
EmployeeID int,
FirstName varchar(255),
LastName varchar(255),
Email varchar(255),
AddressLine varchar(255),
City varchar(255)
);
SQL CREATE TABLE Example in Oracle
Let's see the command to create a table in Oracle database.

CREATE TABLE Employee


(
EmployeeID number(10),
FirstName varchar2(255),
LastName varchar2(255),
Email varchar2(255),
AddressLine varchar2(255),
City varchar2(255)
);

SQL CREATE TABLE Example in Microsoft SQLServer


Let's see the command to create a table in SQLServer database. It is same as MySQL and Oracle.

CREATE TABLE Employee


(
EmployeeID int,
FirstName varchar(255),
LastName varchar(255),
Email varchar(255),
AddressLine varchar(255),
City varchar(255)
);

Create a Table using another table


We can create a copy of an existing table using the create table command. The new table gets

the same column signature as the old table. We can select all columns or some specific columns.

If we create a new table using an old table, the new table will be filled with the existing value from

the old table.

The basic syntax for creating a table with the other table is:
CREATE TABLE table_name AS
SELECT column1, column2,...
FROM old_table_name WHERE ..... ;
The following SQL creates a copy of the employee table.
CREATE TABLE EmployeeCopy AS
SELECT EmployeeID, FirstName, Email
FROM Employee;

SQL Primary Key with CREATE TABLE Statement

The following query creates a PRIMARY KEY on the "D" column when the "Employee" table is created.

MySQL
CREATE TABLE Employee(
EmployeeID NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255),
City varchar(255),
PRIMARY KEY (EmployeeID)
);
SQL Server / Oracle / MS Access
CREATE TABLE Employee(
EmployeeID NOT NULL PRIMARY KEY,
FirstName varchar(255) NOT NULL,
LastName varchar(255),
City varchar(255)
);

Use the following query to define a PRIMARY KEY constraints on multiple columns, and to

allow naming of a PRIMARY KEY constraints.

For MySQL / SQL Server /Oracle / MS Access


CREATE TABLE Employee(
EmployeeID NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255),
City varchar(255),
CONSTRAINT PK_Employee PRIMARY KEY (EmployeeID, FirstName)
);

SQL DROP TABLE


A SQL DROP TABLE statement is used to delete a table definition and all data from a
table.

This is very important to know that once a table is deleted all the information available in
the table is lost forever, so we have to be very careful when using this command.

Let's see the syntax to drop the table from the database.

DROP TABLE "table_name";

Let us take an example:

First we verify STUDENTS table and then we would delete it from the database.

SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

4 rows in set (0.00 sec)

This shows that STUDENTS table is available in the database, so we can drop it as
follows:

SQL>DROP TABLE STUDENTS;

Now, use the following command to check whether table exists or not.

SQL> DESC STUDENTS;

Query OK, 0 rows affected (0.01 sec)

As you can see, table is dropped so it doesn't display it.

SQL DROP TABLE Example in MySQL


Let's see the command to drop a table from the MySQL database.

DROP TABLE table_name;


SQL DELETE TABLE
The DELETE statement is used to delete rows from a table. If you want to remove a
specific row from a table you should use WHERE condition.

DELETE FROM table_name [WHERE condition];

But if you do not specify the WHERE condition it will remove all the rows from the table.

DELETE FROM table_name;

There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement but they are not exactly same there are some differences between
them.

Difference between DELETE and TRUNCATE statements


There is a slight difference b/w delete and truncate statement. The DELETE
statement only deletes the rows from the table based on the condition defined by
WHERE clause or delete all the rows from the table when condition is not specified.

But it does not free the space containing by the table.

The TRUNCATE statement: it is used to delete all the rows from the table and free
the containing space.

Let's see an "employee" table.

Emp_id Name Address Salary

1 Aryan Allahabad 22000

2 Shurabhi Varanasi 13000

3 Pappu Delhi 24000

Execute the following query to truncate the table:

TRUNCATE TABLE employee;

Difference b/w DROP and TRUNCATE statements


When you use the drop statement it deletes the table's row together with the table's
definition so all the relationships of that table with other tables will no longer be valid.
When you drop a table:

o Table structure will be dropped


o Relationship will be dropped
o Integrity constraints will be dropped
o Access privileges will also be dropped

On the other hand when we TRUNCATE a table, the table structure remains the same,
so you will not face any of the above problems.

SQL RENAME TABLE


SQL RENAME TABLE syntax is used to change the name of a table. Sometimes, we
choose non-meaningful name for the table. So it is required to be changed.

Let's see the syntax to rename a table from the database.

ALTER TABLE table_name


RENAME TO new_table_name;

Optionally, you can write following command to rename the table.

RENAME old_table _name To new_table_name;

Let us take an example of a table named "STUDENTS", now due to some reason we want
to change it into table name "ARTISTS".

Table1: students

Name Age City

Amrita gill 25 Amritsar

Amrender sirohi 22 Ghaziabad

Divya khosla 20 Delhi

You should use any one of the following syntax to RENAME the table name:

ALTER TABLE STUDENTS


RENAME TO ARTISTS;

SQL TRUNCATE TABLE


A truncate SQL statement is used to remove all rows (complete data) from a table. It is
similar to the DELETE statement with no WHERE clause.
TRUNCATE TABLE Vs DELETE TABLE

Truncate table is faster and uses lesser resources than DELETE TABLE command.

TRUNCATE TABLE Vs DROP TABLE

Drop table command can also be used to delete complete table but it deletes table
structure too. TRUNCATE TABLE doesn't delete the structure of the table.

Let's see the syntax to truncate the table from the database.

TRUNCATE TABLE table_name;

For example, you can write following command to truncate the data of employee table

TRUNCATE TABLE Employee;

SQL ALTER TABLE


The ALTER TABLE statement is used to add, modify or delete columns in an existing
table. It is also used to rename a table.

You can also use SQL ALTER TABLE command to add and drop various constraints on an
existing table.

SQL ALTER TABLE Add Column


If you want to add columns in SQL table, the SQL alter table syntax is given below:

ALTER TABLE table_name ADD column_name column-definition;

If you want to add multiple columns in table, the SQL table will be

ALTER TABLE table_name


ADD (column_1 column-definition,
column_2 column-definition,
.....
column_n column-definition);

SQL ALTER TABLE Modify Column


If you want to modify an existing column in SQL table, syntax is given below:
ALTER TABLE table_name MODIFY column_name column_type;

If you want to modify multiple columns in table, the SQL table will be

ALTER TABLE table_name


MODIFY (column_1 column_type,
column_2 column_type,
.....
column_n column_type);

SQL ALTER TABLE DROP Column


The syntax of alter table drop column is given below:

ALTER TABLE table_name DROP COLUMN column_name;

SQL ALTER TABLE RENAME Column


The syntax of alter table rename column is given below:

ALTER TABLE table_name


RENAME COLUMN old_name to new_name;

SQL SELECT
The most commonly used SQL command is SELECT statement. It is used to query the
database and retrieve selected data that follow the conditions we want.

In simple words, we can say that the select statement used to query or retrieve data
from a table in the database.

Let's see the syntax of select statement.

SELECT expressions
FROM tables
WHERE conditions;

Here expression is the column that we want to retrieve.

Tables indicate the tables, we want to retrieve records from.

Optional clauses in SELECT statement


There are some optional clauses in SELECT statement:
[WHERE Clause] : It specifies which rows to retrieve.

[GROUP BY Clause] : Groups rows that share a property so that the aggregate
function can be applied to each group.

[HAVING Clause] : It selects among the groups defined by the GROUP BY clause.

[ORDER BY Clause] : It specifies an order in which to return the rows.

For example, let a database table: student_details;

ID First_name Last_name Age Subject

1 Amar Sharma 20 Maths

2 Akbar Khan 22 Biology

3 Anthony Milton 25 Commerce

From the above example, select the first name of all the students. To do so, query
should be like this:

SELECT first_name FROM student_details;

Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:

select first_name from student_details;

Now, you will get following data:

Amar

Akbar

Anthony

We can also retrieve data from more than one column. For example, to select first name
and last name of all the students, you need to write

SELECT first_name, last_name FROM student_details;

Now, you will get following data:

Amar Sharma
Akbar Khan

Anthony Milton

We can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT
statement.

Here a point is notable that only SELECT and FROM statements are necessary in SQL
SELECT statements. Other clauses like WHERE, GROUP BY, ORDER BY, HAVING may be
optional.

SQL SELECT UNIQUE


Actually, there is no difference between DISTINCT and UNIQUE.

SELECT UNIQUE is an old syntax which was used in oracle description but later ANSI
standard defines DISTINCT as the official keyword.

After that oracle also added DISTINCT but did not withdraw the service of UNIQUE
keyword for the sake of backward compatibility.

In simple words, we can say that SELECT UNIQUE statement is used to retrieve a unique
or distinct element from the table.

Let's see the syntax of select unique statement.

SELECT UNIQUE column_name


FROM table_name;

SQL SELECT DISTINCT


The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or
unique data.

In a table, there may be a chance to exist a duplicate value and sometimes we want to
retrieve only unique values. In such scenarios, SQL SELECT DISTINCT statement is used.

Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT statements are same.

Let's see the syntax of select distinct statement.

SELECT DISTINCT column_name ,column_name


FROM table_name;

Let's try to understand it by the table given below:

Student_Name Gender Mobile_Number HOME_TOWN


Rahul Ojha Male 7503896 Lucknow

Disha Rai Female 92705688 Varanasi

Sonoo Jaiswal Male 99904499 Lucknow

Here is a table of students from where we want to retrieve distinct information For
example: distinct home-town.

SELECT DISTINCT home_town


FROM students

Now, it will return two rows.

HOME_TOWN

Lucknow

Varanasi

SQL SELECT COUNT


The SQL COUNT() function is used to return the number of rows in a query.

The COUNT() function is used with SQL SELECT statement and it is very useful to count
the number of rows in a table having enormous data.

For example: If you have a record of the voters in selected area and want to count the
number of voters then it is very difficult to do it manually but you can do it easily by
using the SQL SELECT COUNT query.

Let's see the syntax of SQL COUNT statement.

SELECT COUNT (expression)


FROM tables
WHERE conditions;

Let's see the examples of sql select count function.

SQL SELECT COUNT(column_name)


SELECT COUNT(name) FROM employee_table;
It will return the total number of names of employee_table. But null fields will not be
counted.

SQL SELECT COUNT(*)


SELECT COUNT(*) FROM employee_table;

The "select count(*) from table" is used to return the number of records in table.

SQL SELECT COUNT(DISTINCT column_name)


SELECT COUNT(DISTINCT name) FROM employee_table;

SQL SELECT TOP


The SQL SELECT TOP Statement is used to select top data from a table. The top clause
specifies that how many rows are returned.

Let's see an example. If a table has a large number of data, select top statement
determines that how many rows will be retrieved from the given table.

There is an example of employee table:

EMP_ID NAME SIR_NAME USER_NAME

1 RAHUL OJHA ra@jha

2 ANU SHARMA anusha1

3 RAVI SINGHAL ravin

Let's see the syntax for the select top statement.

SELECT COUNT (expression)

Let's see the example of sql select top statement.

SELECT TOP 2 * FROM employee

It will return the following table:

EMP_ID NAME SIR_NAME USER_NAME


1 RAHUL OJHA ra@jha

2 ANU SHARMA anusha1

SQL WHERE
A WHERE clause in SQL is a data manipulation language statement.

WHERE clauses are not mandatory clauses of SQL DML statements. But it can be used to
limit the number of rows affected by a SQL DML statement or returned by a query.

Actually. it filters the records. It returns only those queries which fulfill the specific
conditions.

WHERE clause is used in SELECT, UPDATE, DELETE statement etc.

Let's see the syntax for sql where:

SELECT column1, column 2, ... column n


FROM table_name
WHERE [conditions]

WHERE clause uses some conditional selection

= equal

> greater than

< less than

>= greater than or equal

<= less than or equal

<> not equal to

SQL WITH CLAUSE


The SQL WITH clause is used to provide a sub-query block which can be referenced in
several places within the main SQL query. It was introduced by oracle in oracle 9i
release2 database.

There is an example of employee table:


Syntax for the SQL WITH clause -

This syntax is for SQL WITH clause using a single sub-query alias.

WITH <alias_name> AS (sql_sub-query_statement)


SELECT column_list FROM <alias_name> [table name]
[WHERE <join_condition>]

When you use multiple sub-query aliases, the syntax will be as follows.

WITH <alias_name_A> AS (sql_sub-query_statement)


<alias_name_B> AS (sql_sub-query_statement_from_alias_name_A
Or sql_sub-query_statement)
SELECT <column_list>
FROM <alias_name_A >,< alias_name_B >, [tablenames]
[WHERE < join_condition>]

SQL ORDER BY Clause


The SQL ORDER BY clause is used for sorting data in ascending and descending order
based on one or more columns.

Some databases sort query results in ascending order by default.

SQL ORDER BY syntax:

SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ASC | DESC];

Let us take a CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY

1 Himani gupta 21 Modinagar 22000

2 Shiva tiwari 22 Bhopal 21000

3 Ajeet bhargav 45 Meerut 65000

4 Ritesh yadav 36 Azamgarh 26000

5 Balwant singh 45 Varanasi 36000

6 Mahesh sharma 26 Mathura 22000


This is an example that would sort the result in ascending order by NAME and SALARY.

SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;

This would produce the following result.

ID NAME AGE ADDRESS SALARY

3 Ajeet bhargav 45 Meerut 65000

5 Balwant singh 45 Varanasi 36000

1 Himani gupta 21 Modinagar 22000

6 Mahesh sharma 26 Mathura 22000

4 Ritesh yadav 36 Azamgarh 26000

2 Shiva tiwari 22 Bhopal 21000

This is an example to sort the result in descending order by NAME.

SELECT * FROM CUSTOMERS


ORDER BY NAME DESC;

This would produce the following result.

ID NAME AGE ADDRESS SALARY

2 Shiva tiwari 22 Bhopal 21000

4 Ritesh yadav 36 Azamgarh 26000

6 Mahesh sharma 26 Mathura 22000

1 Himani gupta 21 Modinagar 22000

5 Balwant singh 45 Varanasi 36000

3 Ajeet bhargav 45 Meerut 65000


SET Operations in SQL
SQL supports few Set operations which can be performed on the table data. These
are used to get meaningful results from data stored in the table, under different
special conditions.
In this tutorial, we will cover 4 different types of SET operations, along with example:

1. UNION

2. UNION ALL

3. INTERSECT

4. MINUS

UNION Operation
UNION is used to combine the results of two or more SELECT statements. However it
will eliminate duplicate rows from its resultset. In case of union, number of columns
and datatype must be same in both the tables, on which UNION operation is being
applied.

Example of UNION
The First table,

ID Name
1 abhi

2 adam

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,


SELECT * FROM First

UNION

SELECT * FROM Second;

The resultset table will look like,

ID NAME

1 abhi

2 adam

3 Chester

UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.

Example of Union All


The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Union All query will be like,


SELECT * FROM First

UNION ALL

SELECT * FROM Second;

The resultset table will look like,


ID NAME

1 abhi

2 adam

2 adam

3 Chester

INTERSECT
Intersect operation is used to combine two SELECT statements, but it only retuns the
records which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same.
NOTE: MySQL does not support INTERSECT operator.

Example of Intersect
The First table,

ID NAME
1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,


SELECT * FROM First

INTERSECT

SELECT * FROM Second;

The resultset table will look like

ID NAME

2 adam

MINUS
The Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.
Example of Minus
The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Minus query will be,


SELECT * FROM First

MINUS

SELECT * FROM Second;

The resultset table will look like,


ID NAME

1 abhi

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of a
single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION
o 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.
o 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:

Example: COUNT() with DISTINCT

SELECT COUNT(DISTINCT COMPANY)


FROM PRODUCT_MAST;

Output:

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;
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
SQL Subquery
Summary: in this tutorial, you will learn about the SQL subquery and how
to use the subqueries to form flexible SQL statements.

SQL subquery basic


Consider the following employees and departments tables from the sample
database:

Suppose you have to find all employees who locate in the location with the
id 1700. You might come up with the following solution.

First, find all departments located at the location whose id is 1700:

SELECT
*
FROM
departments
WHERE
location_id = 1700;

Second, find all employees that belong to the location 1700 by using the
department id list of the previous query:

SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (1 , 3, 8, 10, 11)
ORDER BY first_name , last_name;

This solution has two problems. To start with, you have looked at
the departments table to check which department belongs to the location
1700. However, the original question was not referring to any specific
departments; it referred to the location 1700.
Because of the small data volume, you can get a list of department easily.
However, in the real system with high volume data, it might be problematic.

Another problem was that you have to revise the queries whenever you
want to find employees who locate in a different location.

A much better solution to this problem is to use a subquery. By definition, a


subquery is a query nested inside another query such
as SELECT, INSERT, UPDATE, or DELETE statement. In this tutorial, we are focusing
on the subquery used with the SELECT statement.
In this example, you can rewrite combine the two queries above as follows:

SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
The query placed within the parentheses is called a subquery. It is also
known as an inner query or inner select. The query that contains the
subquery is called an outer query or an outer select.

To execute the query, first, the database system has to execute the
subquery and substitute the subquery between the parentheses with its
result – a number of department id located at the location 1700 – and then
executes the outer query.

You can use a subquery in many places such as:

 With the IN or NOT IN operator


 With comparison operators
 With the EXISTS or NOT EXISTS operator
 With the ANY or ALL operator
 In the FROM clause
 In the SELECT clause

SQL subquery examples


Let’s take some examples of using the subqueries to understand how they
work.

SQL subquery with the IN or NOT IN operator


In the previous example, you have seen how the subquery was used with
the IN operator. The following example uses a subquery with the NOT
IN operator to find all employees who do not locate at the location 1700:
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id NOT IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
SQL subquery with the comparison operator
The following syntax illustrates how a subquery is used with a comparison
operator:

comparison_operator (subquery)
where the comparison operator is one of these operators:

 Equal (=)
 Greater than (>)
 Less than (<)
 Greater than or equal ( >=)
 Less than or equal (<=)
 Not equal ( !=) or (<>)

The following example finds the employees who have the highest salary:

SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary = (SELECT
MAX(salary)
FROM
employees)
ORDER BY first_name , last_name;

In this example, the subquery returns the highest salary of all employees
and the outer query finds the employees whose salary is equal to the
highest one.
The following statement finds all employees who salaries are greater than
the average salary of all employees:

SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary > (SELECT
AVG(salary)
FROM
employees);

In this example, first, the subquery returns the average salary of all
employees. Then, the outer query uses the greater than operator to find all
employees whose salaries are greater than the average.

SQL subquery with the EXISTS or NOT EXISTS operator


The EXISTS operator checks for the existence of rows returned from the
subquery. It returns true if the subquery contains any rows. Otherwise, it
returns false.
The syntax of the EXISTS operator is as follows:
EXISTS (subquery )
The NOT EXISTS operator is opposite to the EXISTS operator.
NOT EXISTS (subquery)
The following example finds all departments which have at least one
employee with the salary is greater than 10,000:

SELECT
department_name
FROM
departments d
WHERE
EXISTS( SELECT
1
FROM
employees e
WHERE
salary > 10000
AND e.department_id = d.department_id)
ORDER BY department_name;

Similarly, the following statement finds all departments that do not have
any employee with the salary greater than 10,000:

SELECT
department_name
FROM
departments d
WHERE
NOT EXISTS( SELECT
1
FROM
employees e
WHERE
salary > 10000
AND e.department_id = d.department_id)
ORDER BY department_name;

SQL subquery with the ALL operator


The syntax of the subquery when it is used with the ALL operator is as
follows:
comparison_operator ALL (subquery)
The following condition evaluates to true if x is greater than every value
returned by the subquery.
x > ALL (subquery)
For example, suppose the subquery returns three value one, two, and three.
The following condition evaluates to true if x is greater than 3.
x > ALL (1,2,3)
The following query uses the GROUP BY clause and MIN() function to find the
lowest salary by department:
SELECT
MIN(salary)
FROM
employees
GROUP BY department_id
ORDER BY MIN(salary) DESC;
The following example finds all employees whose salaries are greater than
the lowest salary of every department:

SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= ALL (SELECT
MIN(salary)
FROM
employees
GROUP BY department_id)
ORDER BY first_name , last_name;

SQL subquery with the ANY operator


The following shows the syntax of a subquery with the ANY operator:
comparison_operator ANY (subquery)
For example, the following condition evaluates to true if x is greater than
any value returned by the subquery. So the condition x > SOME
(1,2,3) evaluates to true if x is greater than 1.
x > ANY (subquery)
Note that the SOME operator is a synonym for the ANY operator so you can
use them interchangeably.
The following query finds all employees whose salaries are greater than or
equal to the highest salary of every department.

SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= SOME (SELECT
MAX(salary)
FROM
employees
GROUP BY department_id);

In this example, the subquery finds the highest salary of employees in each
department. The outer query looks at these values and determines which
employee’s salaries are greater than or equal to any highest salary by
department.

SQL subquery in the FROM clause


You can use a subquery in the FROM clause of the SELECT statement as
follows:
SELECT
*
FROM
(subquery) AS table_name
In this syntax, the table alias is mandatory because all tables in
the FROM clause must have a name.
Note that the subquery specified in the FROM clause is called a derived table
in MySQL or inline view in Oracle.
The following statement returns the average salary of every department:

SELECT
AVG(salary) average_salary
FROM
employees
GROUP BY department_id;
You can use this query as a subquery in the FROM clause to calculate the
average of average salary of departments as follows:
SELECT
ROUND(AVG(average_salary), 0)
FROM
(SELECT
AVG(salary) average_salary
FROM
employees
GROUP BY department_id) department_salary;

SQL Subquery in the SELECT clause


A subquery can be used anywhere an expression can be used in
the SELECT clause. The following example finds the salaries of all employees,
their average salary, and the difference between the salary of each
employee and the average salary.
SELECT
employee_id,
first_name,
last_name,
salary,
(SELECT
ROUND(AVG(salary), 0)
FROM
employees) average_salary,
salary - (SELECT
ROUND(AVG(salary), 0)
FROM
employees) difference
FROM
employees
ORDER BY first_name , last_name;
Now you should understand what an SQL subquery is and how to use
subqueries to form flexible SQL statements.
SQL - Using Views

A view is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a
predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to create
a view.
Views, which are a type of virtual tables allow users to do the following −
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data in such a way that a user can see and (sometimes)
modify exactly what they need and no more.
 Summarize data from various tables which can be used to generate reports.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the
specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you
use them in a normal SQL SELECT query.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| 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 | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view
would be used to have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual
table. Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

The WITH CHECK OPTION


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of
the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the
condition(s) in the view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view
CUSTOMERS_VIEW with the WITH CHECK OPTION.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values
in the view's AGE column, because the view is defined by data that does not have a
NULL value in the AGE column.
Updating a View
A view can be updated under certain conditions which are given below −
 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in
order for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view.
The following code block has an example to update the age of Ramesh.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the SELECT statement
would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the UPDATE
command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not
included all the NOT NULL columns in this view, otherwise you can insert rows in a
view in a similar way as you insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE
and INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the same
would reflect in the view itself. Now, try to query the base table and the SELECT
statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple and is given below −
DROP VIEW view_name;
Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS
table.
DROP VIEW CUSTOMERS_VIEW;

SQL - Indexes

Indexes are special lookup tables that the database search engine can use to
speed up data retrieval. Simply put, an index is a pointer to data in a table. An index
in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain
topic, you first refer to the index, which lists all the topics alphabetically and are then
referred to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down
data input, with the UPDATE and the INSERT statements. Indexes can be created
or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate
whether the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax
is as follows.
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the table. The
basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is
as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration
the column(s) that you may use very frequently in a query's WHERE clause as filter
conditions.
Should there be only one column used, a single-column index should be the choice.
Should there be two or more columns that are frequently used in the WHERE clause
as filters, the composite index would be the best choice.
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server
when an object is created. Indexes are automatically created for primary key
constraints and unique constraints.

The DROP INDEX Command


An index can be dropped using SQL DROP command. Care should be taken when
dropping an index because the performance may either slow down or improve.
The basic syntax is as follows −
DROP INDEX index_name;
You can check the INDEX Constraint chapter to see some actual examples on
Indexes.
When should indexes be avoided?
Although indexes are intended to enhance a database's performance, there are times
when they should be avoided.
The following guidelines indicate when the use of an index should be reconsidered.
 Indexes should not be used on small tables.
 Tables that have frequent, large batch updates or insert operations.
 Indexes should not be used on columns that contain a high number of NULL
values.
 Columns that are frequently manipulated should not be indexed.
PL/SQL - Cursors

In this chapter, we will discuss the cursors in PL/SQL. Oracle creates a memory area,
known as the context area, for processing an SQL statement, which contains all the
information needed for processing the statement; for example, the number of rows
processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through
a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The
set of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and
process the rows returned by the SQL statement, one at a time. There are two types
of cursors −

 Implicit cursors
 Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement. The following table provides the description of the most
used attributes −

S.No Attribute & Description

%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.

2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned no
rows. Otherwise, it returns FALSE.

%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.

%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below


in the example.
Example
We will be using the CUSTOMERS table we had created and used in the previous
chapters.
Select * from customers;

+----+----------+-----+-----------+----------+
| 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 | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer
by 500 and use the SQL%ROWCOUNT attribute to determine the number of rows
affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected
');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result

6 customers selected

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have been
updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open
the above defined cursor as follows −
OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close
the above-opened cursor as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' ||
c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.


Triggers

In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs,
which are automatically executed or fired when some events occur. Triggers are, in
fact, written to be executed in response to any of the following events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.
Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the
trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when the SQL statement is executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in
the previous chapters −
Select * from customers;

+----+----------+-----+-----------+----------+
| 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 | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS
table. This trigger will display the salary difference between the old values and new
values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following result

Trigger created.
The following points need to be considered here −
 OLD and NEW references are not available for table-level triggers, rather you
can use them for record-level triggers.
 If you want to query the table in the same trigger, then you should use the
AFTER keyword, because triggers can query the table or change it again only
after the initial changes are applied and the table is back in a consistent state.
 The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but you can write your
trigger on a single or multiple operations, for example BEFORE DELETE,
which will fire whenever a record will be deleted using the DELETE operation
on the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes
as null. Let us now perform one more DML operation on the CUSTOMERS table. The
UPDATE statement will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500

You might also like