Rdbms Unit II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

UNIT- II: RELATIONAL DATA MODEL

Relational model concepts, Relational constraints, Relational Languages: Relational Algebra,


The Tuple Relational Calculus - The Domain Relational Calculus - SQL: Basic Structure-Set
Operations- Aggregate Functions-Null Value-Nested Sub QueriesViews Complex Queries
Modification of Database-Joined Relations-DDL-Embedded SQL-Dynamic SQL-Other SQL
Functions- -Integrity and Security.

RELATIONAL DATA MODEL

2.1 Relational data model concepts:

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.

Concepts
Tables − In relational data model, relations are saved in the format of Tables. This format stores
the relation among entities. A table has rows and columns, where rows represents records and
columns represent the attributes.

Tuple − A single row of a table, which contains a single record for that relation is called a tuple.

Relation instance − A finite set of tuples in the relational database system represents relation
instance. Relation instances do not have duplicate tuples.

Relation schema − A relation schema describes the relation name (table name), attributes, and
their names.

Relation key − Each row has one or more attributes, known as relation key, which can identify
the row in the relation (table) uniquely.

Attribute domain − Every attribute has some pre-defined value scope, known as attribute
domain.

2.2 Relational Constraints


Every relation has some conditions that must hold for it to be a valid relation. These conditions
are called Relational Integrity Constraints. There are three main integrity constraints −

• Key constraints
• Domain constraints
• Referential integrity constraints

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 1


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1) Key Constraints
There must be at least one minimal subset of attributes in the relation, which can identify a tuple
uniquely. This minimal subset of attributes is called key for that relation. If there are more than
one such minimal subsets, these are called candidate keys.

Key constraints force that –

• in a relation with a key attribute, no two tuples can have identical values for key
attributes.

• a key attribute cannot have NULL values.

Key constraints are also referred to as Entity Constraints.

2)Domain Constraints
Attributes have specific values in real-world scenario. For example, age can only be a positive
integer. The same constraints have been tried to employ on the attributes of a relation. Every
attribute is bound to have a specific range of values. For example, age cannot be less than zero
and telephone numbers cannot contain a digit outside 0-9.

3)Referential integrity Constraints


Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key
attribute of a relation that can be referred in other relation.

Referential integrity constraint states that if a relation refers to a key attribute of a different or
same relation, then that key element must exist.
THE RELATIONAL DATABASE STRUCTURE
A modern database, on the other hand, alleviates the problem of multiple updates of individual
files. The database enables the user to perform a single update across multiple files
simultaneously. A database is a collection of organized files that are electronically stored. The
files in a database are referred to as tables.
We come in contact with databases every day. Some examples of databases include ATMs,
computer-based card-catalog systems at a library, and numerous Internet features including order
forms and catalogs of merchandise.
The most popular and widely implemented type of database is called a relational database.
A relational database is a collection of two or more tables related by key values.
Tables
We refer to the tables in a database as two-dimensional files that contain rows (records) and
columns (fields). The reason we say that tables are two-dimensional is because the rows of a
table run horizontally and the columns run vertically, hence two dimensions. Take a look
at Figure 1-1.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 2


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Figure 1-1. A blank table


Figure 1-1 shows an unpopulated (empty) table with five columns and six rows. Each row in the
table represents an individual record and each column represents an individual entity of
information. For example, a table named Customers could have the following seven entities
(columns) of information: First Name, Last Name, Address, City, State, Zip, and Phone.
Each customer entered into the Customers table represents an individual record.
Keys
To create a relationship between two tables in a relational database you use keys. Keys are
columns in a table that are specifically used to point to records in another table. The two most
commonly used keys during database creation are the primary key and the foreign key.
The primary key is a column in a table that uniquely identifies every record in that table. This
means that no two cells within the primary key column can be duplicated. While tables usually
contain a primary key column, this practice is not always implemented. The absence of a primary
key in a table means that the data in that table is harder to access and subsequently results in
slower operation. On the other hand, tables with very few entries will often not be indexed. This
is especially true if the value is not used for searches or lookups. A table with three values of
single, married, and divorced might not be indexed, although a table that uses this information,
like an employee table, would definitely index on this field.

Figure 1-2. Employees table


Figure 1-2 shows a table named Employees. The SocialSecNum column is the primary key
column in the Employees table. Since no two people can have the same social security number,
social security numbers are commonly used as a primary key. As you can see, the SocialSecNum
column uniquely identifies every employee in the Employees table.
The foreign key is a column in a table that links records of one type with those of another type.
Foreign keys create relationships between tables and help to ensure referential
integrity. Referential integrity ensures that every record in a database is correctly matched to any
associated records. Foreign keys help promote referential integrity by ensuring that every foreign
key within the database corresponds to a primary key.
Every time you create a foreign key, a primary key with the same name must already exist in
another table. For example, the SocialSecNum column is used to link the Employees table
in Figure 1-2 to the Departments table in Figure 1-3.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 3


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Figure 1-3. Departments table


The SocialSecNum column is a primary key column in the Employees table and a foreign key
column in the Departments table. Notice that the Departments table in Figure 1-3 also contains
its own primary key column named DepartmentID.

2.3 Relational Languages :


2.3.1 Relational Algebra
The relational algebra is a procedural query language. It consists of a set of operations that take
one or two relations as input and produce a new relation as their result. The fundamental
operations in the relational algebra are select, project, union, set difference, Cartesian product,
and rename. In addition to the fundamental operations, there are several other operations—
namely, set intersection, natural join, and assignment. We shall define these operations in terms
of the fundamental operations
Basic Relational Operations

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 operation selects tuples that satisfy a given predicate.

σp(r)

σ is the predicate

r stands for relation which is the name of the table

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 4


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

p is prepositional logic

Example 1

σ topic = "Database" (Tutorials)

Output - Selects tuples from Tutorials where topic = 'Database'.

Example 2

σ topic = "Database" and author = "guru99"( Tutorials)

Output - Selects tuples from Tutorials where the topic is 'Database' and 'author' is guru99.

Example 3

σ sales > 50000 (Customers)

Output - Selects tuples from Customers where sales is greater than 50000

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) The symbol
used to choose attributes from a relation. This operation helps you to keep specific columns from
a relation and discards the other columns.

Example of Projection:

Consider the following table

CustomerID CustomerName Status

1 Google Active

2 Amazon Active

3 Apple Inactive

4 Alibaba Active

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 5


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Here, the projection of CustomerName and status will give

Π CustomerName, Status (Customers)

CustomerName Status

Google Active

Amazon Active

Apple Inactive

Alibaba Active

Union operation (υ)

UNION is symbolized by ∪ symbol. It includes all tuples that are in tables A or in B. It also
eliminates duplicate tuples. So, set A UNION set B would be expressed as:

The result <- A ∪ B

For a union operation to be valid, the following conditions must hold -

• R and S must be the same number of attributes.


• Attribute domains need to be compatible.
• Duplicate tuples should be automatically removed.

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

A ∪ B gives

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 6


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Table A ∪ B

column 1 column 2

1 1

1 2

1 3

Set Difference (-)

- 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.

Example

A-B
Table A - B

column 1 column 2

1 2

Intersection

An intersection is defined by the symbol ∩

A∩B

Defines a relation consisting of a set of all tuple that are in both A and B. However, A and B
must be union-compatible.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 7


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Example:

A∩B
Table A ∩ B

column 1 column 2

1 1

Cartesian product(X)

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.

Example – Cartesian product

σ 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

Additional Relational Algebra Operations


Join Operations
Join operation is essentially a cartesian product followed by a selection criterion.

Join operation denoted by ⋈.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 8


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

JOIN operation also allows joining variously related tuples from different relations.

Types of JOIN:

Various forms of join operation are:

Inner Joins:

• Theta join
• EQUI join
• Natural join

Outer join:

• Left Outer Join


• Right Outer Join
• Full Outer Join

I . Inner Join:
In an inner join, only those tuples that satisfy the matching criteria are included, while the rest
are excluded. Let's study various types of Inner Joins:

1) Theta Join:
The general case of JOIN operation is called a Theta join. It is denoted by symbol θ

Example

A ⋈θ B
Theta join can use any conditions in the selection criteria.

For example:

A ⋈ A.column 2 > B.column 2 (B)

A ⋈ A.column 2 > B.column 2 (B)

column 1 column 2

1 2

2) EQUI join:
When a theta join uses only equivalence condition, it becomes a equi join.

For example:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 9


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

A ⋈ A.column 2 = B.column 2 (B)

A ⋈ A.column 2 = B.column 2 (B)

column 1 column 2

1 1
EQUI join is the most difficult operations to implement efficiently in an RDBMS and one reason
why RDBMS have essential performance problems.

3) NATURAL JOIN (⋈)


Natural join can only be performed if there is a common attribute (column) between the
relations. The name and type of the attribute must be same.

Example:

Consider the following two tables

C D

Num Square Num Cube

2 4 2 8

3 9 3 18

C⋈D
C⋈D

Num Square Cube

2 4 4

3 9 9

II. OUTER JOIN

In an outer join, along with tuples that satisfy the matching criteria, we also include some or all
tuples that do not match the criteria.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 10


A⋈B

RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1) Left Outer Join(A B)

In the left outer join, operation allows keeping all tuple in the left relation. However, if there is
no matching tuple is found in right relation, then the attributes of right relation in the join result
are filled with null values.

Consider the following 2 Tables

A B

Num Square Num Cube

2 4 2 8

3 9 3 18

4 16 5 75

A B
A⋈B

Num Square Cube

2 4 4

3 9 9

4 16 -

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 11


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Num Cube Square

2 4 8

3 9 18

4 16 -

5 - 75

2)Right Outer Join: ( A B)

In the right outer join, operation allows keeping all tuple in the right relation. However, if there is
no matching tuple is found in the left relation, then the attributes of the left relation in the join
result are filled with null values.

A B
A⋈B

Num Cube Square

2 8 4

3 18 9

5 75 -

3)Full Outer Join: ( A B)

In a full outer join, all tuples from both relations are included in the result, irrespective of the
matching condition.

A B

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 12


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Summary
Operation Purpose

Select(𝛔) The SELECT operation is used for selecting a subset of the tuples
according to a given selection condition

Projection(π) The projection eliminates all attributes of the input relation but those
mentioned in the projection list.

Union Operation(∪) UNION is symbolized by symbol. It includes all tuples that are in tables A
or in B.

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

Intersection(∩) Intersection defines a relation consisting of a set of all tuple that are in
both A and B.

Cartesian Product(X) Cartesian operation is helpful to merge columns from two relations.

Inner Join Inner join, includes only those tuples that satisfy the matching criteria.

Theta Join(θ) The general case of JOIN operation is called a Theta join. It is denoted by
symbol θ.

EQUI Join When a theta join uses only equivalence condition, it becomes a equi join.

Natural Join(⋈) Natural join can only be performed if there is a common attribute
(column) between the relations.

Outer Join In an outer join, along with tuples that satisfy the matching criteria.

Left Outer Join( ) In the left outer join, operation allows keeping all tuple in the left relation.

Right Outer join( ) In the right outer join, operation allows keeping all tuple in the right
relation.

Full Outer Join( ) In a full outer join, all tuples from both relations are included in the result
irrespective of the matching condition.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 13


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Division

• Notation: r ÷ s

• Precondition: attributes in S must be a subset of attributes in R, i.e., S ⊆ R. Let r, s be relations


on schemas R and S, respectively,

where – R(A1, . . . , Am, B1, . . . , Bn) – S(B1, . . . , Bn)

The result of r ÷ s is a relation on schema R − S = (A1, . . . , Am) • Suited for queries that include
the phrase “for all”. The result of the division operator consists of the set of tuples from r defined
over the attributes R − S that match the combination of every tuple in s.

r ÷ s := {t | t ∈ πR−S(r) ∧ ∀u ∈ s: tu ∈ r}

Assignment Operation

■ The assignment operation (←) provides a convenient way to express complex queries.

● Write query as a sequential program consisting of a series of assignments followed by an


expression whose value is displayed as a result of the query.

● Assignment must always be made to a temporary relation variable.

■ Example: Write r ÷ s as

temp1← ∏RS (r )

temp2 ← ∏RS ((temp1 x s ) – ∏RS,S (r ))

result = temp1 – temp2

● The result to the right of the ← is assigned to the relation variable on the left of the ←.

● May use variable in subsequent expressions.

Null values

In populating a database with data objects, it is not uncommon that some of these objects may
not be completely known. For example, in capturing new customer information through forms
that customers are requested to fill, some fields may have been left blank (some customers may
take exception to revealing their age or phone numbers!). In these cases, rather than not have any
information at all, we can still record those that we know about. But what value do we insert into
the unknown fields of data objects? Leaving a field blank is not good enough as it can be
interpreted as an empty string which may be a valid value for some domains. We need a value
that denotes 'unknown' and that cannot be confused with valid domain values.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 14


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

It is here that the Null value is used. We can think of it as a special value different from any other
value from any attribute domain. At the same time, we may think of it as belonging to every
attribute domain in the database, ie. it may appear as a value for any attribute and not violate any
type constraints. Syntactically, different DBMSs may use different symbols to denote null
values. For our purposes, we will use the symbol '?'.

How do null values affect relational operations? All relational operations involve comparing
values in tuples, including Projection (which involves comparison of result tuples for duplicates).
The key to answering this question is in how we evaluate boolean operations involving null
values. Thus, for example, what does "? > 5" evaluate to? The unknown value could be greater
than 5. But then again, it may not be. That is, the value of the boolean expression cannot be
determined on the basis of available information. So perhaps we should consider the result of the
comparison as unknown as well?

Unfortunately, if we did this, the relational operations we've discussed cease to be well-defined!
They all rely on comparisons evaluating categorically to one of two values: TRUE or FALSE.
For example, if the above comparison ("? > 5") was generated in the process of selection, we
would not know whether to include or exclude the associated tuple in the result if we were to
admit a third value (UNKNOWN). If we wanted to do that, we must go back and redefine all
these operations based on some form of three-valued logic.

To avoid this problem, most systems that allow null values simply interpret any comparison
involving them as FALSE. The rationale is that even though they could be true, they are not
demonstrably true on the basis of what is known. That is, the result of any relational operation
conservatively includes only tuples that demonstrably satisfy conditions of the operation.
Adopting this convention, all the operations defined previously still hold without any
amendment. Some implications on the outcome of each operation are considered below.

For the Select operation, an unknown value cannot identify a tuple. This is illustrated in Figure
6-6 which shows two Select operations applied to the relation R. Note that between the two
operations, the selection criteria ranges over the entire domain of the attribute I2. One would
expect therefore, that any tuple in R1 would either be in the result of the first or the second. This
is not the case, however, as the second tuple in R1 (<b,?>) is not selected in either operation-the
unknown value in it falsifies the selection criteria of both operations!

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 15


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Figure 6-6 Selecting over null values

For Projection, tuples containing null values that are otherwise identical are not considered to be
duplicates. This is because the comparison "? = ?", by the above convention, evaluates to
FALSE. This leads to the situation as illustrated in Figure 6-7 below. The reader should note
from this example that the symbol '?', while it denotes some value much like a mathematical
variable, is quite unlike the latter in that it's occurrences do not always denote the same value.
Thus "? = ?" is not demonstrably true and therefore considered FALSE.

Figure 6-7 Projecting over null values

In a Join operation, tuples having null values under the common attributes are not concatenated.
This is illustrated in Figure 6-8 ("?=1", "1=?" and "?=?" are all FALSE).

Figure 6-8 Joining over null values

In Division, the occurrence of even one null value in the divisor means that the result will be an
empty relation, as any value in the dividend's common attribute(s) will fail when matched with it.
This is illustrated in Figure 6-9 below. Note, however, that this is not necessarily the case if only
the dividend contains null values under the common attribute(s) - division may still be successful
on tuples not containing null values.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 16


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Figure 6-9 Division with null divisors

In set operations, because tuples are treated as a single unit in comparisons, a single rule applies:
tuples otherwise identical but containing null values are considered to be different (as was the
case for Projection above). Figure 6-10 illustrates this for each set operation. Note that because
of the occurrence of null values, the tuples in R2 are not considered duplicates of R1's tuples.
Thus their union simply collects tuples from both relations; subtracting R2 from R1 simply
results in R1; and their intersection is empty.

Figure 6-10 Set operations involving null values

2.3.2 Relational Calculus

Before understanding Relational calculus in DBMS, we need to understand Procedural


Language and Declarative Language.

1. Procedural Language - Those Languages which clearly define how to get the required
results from the Database are called Procedural Language. Relational algebra is a
Procedural Language.
2. Declarative Language - Those Language that only cares about What to get from the
database without getting into how to get the results are called Declarative
Language. Relational Calculus is a Declarative Language.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 17


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

So Relational Calculus is a Declarative Language that uses Predicate Logic or First-Order Logic
to determine the results from Database.

Types of Relational Calculus in DBMS

Relational Calculus is of Two Types:

1. Tuple Relational Calculus (TRC)


2. Domain Relational Calculus (DRC)

Tuple Relational Calculus (TRC)

Tuple Relational Calculus in DBMS uses a tuple variable (t) that goes to each row of the table
and checks if the predicate is true or false for the given row. Depending on the given predicate
condition, it returns the row or part of the row.

The Tuple Relational Calculus expression Syntax

{t \| P(t)}

Where t is the tuple variable that runs over every Row, and P(t) is the predicate logic expression
or condition.

Let's take an example of a Customer Database and try to see how TRC expressions work.

Customer Table

Customer_id Name Zip code


1 Rohit 12345
2 Rahul 13245
3 Rohit 56789
4 Amit 12345.

Example 1: Write a TRC query to get all the data of customers whose zip code is 12345.

TRC Query: {t \| t ∈ Customer ∧ t.Zipcode = 12345} or TRC Query: {t \| Customer(t) ∧


t[Zipcode] = 12345 }

Workflow of query - The tuple variable "t" will go through every tuple of the Customer table.
Each row will check whether the Cust_Zipcode is 12345 or not and only return those rows that
satisfies the Predicate expression condition.

The TRC expression above can be read as "Return all the tuple which belongs to the
Customer Table and whose Zipcode is equal to 12345."

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 18


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Result of the TRC expression above:

Customer_id Name Zip code

1 Rohit 12345

4. Amit 12345

Example 2: Write a TRC query to get the customer id of all the Customers.

TRC query: { t \| ∃s (s ∈ Customer ∧ s.Customer_id = t.customer_id) }

Result of the TRC Query:

Customer_id

2.2.3 Domain Relational Calculus (DRC)

Domain Relational Calculus uses domain Variables to get the column values required from the
database based on the predicate expression or condition.

The Domain realtional calculus expression syntax:

{<x1,x2,x3,x4...> \| P(x1,x2,x3,x4...)}

where,

<x1,x2,x3,x4...> are domain variables used to get the column values required,
and P(x1,x2,x3...) is predicate expression or condition.

Let's take the example of Customer Database and try to understand DRC queries with some
examples.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 19


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Customer Table

Customer_id Name Zip code

1 Rohit 12345

2 Rahul 13245

3 Rohit 56789

4 Amit 12345

Example 1: Write a DRC query to get the data of all customers with Zip code 12345.

DRC query: {<x1,x2,x3> \| <x1,x2> ∈ Customer ∧ x3 = 12345 }

Workflow of Query: In the above query x1,x2,x3 (ordered) refers to the attribute or column
which we need in the result, and the predicate condition is that the first two domain variables x1
and x2 should be present while matching the condition for each row and the third domain
variable x3 should be equal to 12345.

Result of the DRC query will be:

Customer_id Name Zip code


1 Rohit 12345
4 Amit 12345

Example 2: Write a DRC query to get the customer id of all the customer.

DRC Query: { <x1> \| ∃ x2,x3(<x1,x2,x3> ∈ Customer ) }

Result of the above Query will be:

Customer_id

2.4 Basic SQL Structure

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 20


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

The basic structure of an SQL query consists of three clauses: select, from, and
where. The query takes as its input the relations listed in the from clause, operates on
them as specified in the where and select clauses, and then produces a relation as the
result.

2.4.1 Queries on a Single Relation


Let us consider the below table Faculty and DEPT,

FI FNAME DEPT SALARY DEPT DEPTNAME Block


D ID ID

1 JISY 1 35000 1 CS New

2 SANTHY 1 30000 2 EC New

3 SWETHA 2 25000 3 EE old

Queries on a Single Relation

Let us consider a simple query using our Faculty table, “Find the names of all instructors.
select FNAME from Faculty;

The result is a relation consisting of a single attribute. If want to force the


elimination ofduplicates, we insert the keyword distinct after select. We can rewrite the
preceding query as:

FID FNAME DEPTNAME

1 JISY 1
2 SANTHY 1
3 SWETHA 2

select distinct DEPTNAME from FACULTY;

DEPT
CS
EC

SQL allows us to use the keyword all to specify explicitly that duplicates are not removed:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 21


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

select all DEPTNAME from DEPT;

The select clause may also contain arithmetic expressions involving the operators +, −, ∗,
and / operating on constants or attributes of tuples. For example,the query returns a
relation that is the same as the Faculty relation, except that the attribute salary is
multiplied by 1.1.

select FID , FNAME, SALARY * 1.1 from Faculty;

SQL allows the use of the logical connectives and, or, and not in the where clause. The
operands of the logical connectives can be expressions involving the comparison
operators <, <=, >, >=, =, and <>.

select FNAME from Faculty where SALARY>30000;

2.4.2 Queries on Multiple Relations


Consider two tables,

CID NAME Addr OID CID AMOUNT


1 Manju abc 1 2 100
2 Jisy cde 2 1 250
3 Vishnu efg 3 4 300
4 Meera hij 4 3 400

2.4.2.1 Retrieve CID, Address and amount from relation CUSTOMER and ORDER
whose name= jisy
SELECT CUSTOMER.CID, Addr, AMOUNT FROM CUSTOMER,
ORDER WHERECUSTOMERS.CID = ORDERS.CID and NAME=’Jisy’;
2.4.2.2 Retrieve customer id, name, Address and amount from relation CUSTOMER AND
ORDER
SELECT CUSTOMER.CID, NAME, Addr, AMOUNT FROM
CUSTOMER, ORDER WHERE CUSTOMERS.CID =
ORDERS.CID;

Join
Select CID, NAME, Addr, AMOUNT from CUSTOMER Natural join ORDER

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 22


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Select CID, NAME, Addr, AMOUNT from CUSTOMER Inner join ORDER onCUST

SQL aliases/ correlation name/ tuple variable.

SQL aliases are used to give a table, or a column in a table, a temporary name.

2.4.2.3 To rename column,


Select old column name as new name from table
name;

Eg:

Select CID as CustomerID , Name from


CUSTOMER;

2.4.2.4 To rename table


Select Name from Customer as Cust where CID=1;

SELECT C.CID, NAME, Addr, AMOUNT FROM CUSTOMER


as C, ORDERWHERE C.CID = ORDERS.CID;

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position

WHERE CustomerName LIKE 'a_%_%' Finds any values that start with "a" and are at
least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" andends
with "o"

String Operations
SQL specifies strings by enclosing them in single quotes, for example,

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 23


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

’Computer’. The SQL standard specifies that the equality operation on strings is case
sensitive; as a result the expression “ ’computer’ = ’Computer’ ” evaluates to false.
SQL also permits a variety of functions on character strings, such as
concatenating (using “ ||”), extracting substrings, finding the length of strings, converting
strings to uppercase (using the function upper(s) where s is a string) and lowercase
(using the function lower(s)), removing spaces at the end of the string (using trim(s)).
Pattern matching can be performed on strings, using the operator like. We describe
patterns by using two special characters:

• Percent (%): multiple character


• Underscore ( _): single character.

SELECT column1, column2, ...FROM table_name WHERE columnN


LIKE pattern; SELECT * FROM CUSTOMER WHERE Name LIKE
'a%';

SQL ORDER BY

The ORDER BY statement in sql is used to sort the fetched data in either ascending or
descending according to one or more columns. By default ORDER BY sorts the data in
ascending order.
SELECT column1, column2, ...FROM table_name ORDER
BY column1,column2, ... ASC/DESC;

Eg. SELECT NAME FROM CUSTOMER ORDER BY Name DESC;

NAME
Vishnu

Manju
Jisy

SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are
included.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 24


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

SELECT column_name(s) FROM table_name WHERE column_name BETWEEN

value1 AND value2;

SELECT * FROM ORDER WHERE AMOUNT BETWEEN 100 AND 350;

OID CID AMOUNT

1 2 100

2 1 250

3 4 300

2.5 SET OPERATIONS

The SQL operations union, intersect, and except operate on relations and
correspond to the mathematical set-theory operations ∪, ∩, and −. Consider two tables
First and Second,

SET operators are special type of operators which are used to combine the result of two queries.

Operators covered under SET operators are:

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

ID Name ID Name

1 JISY 3 SWETHA

2 SANTHY 2 SANTHY

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 25


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1) UNION Operation: 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.
SELECT * FROM First UNION SELECT * FROM Second;

ID Name

1 JISY

2 SANTHY

3 SWETH
A

2)UNION ALL:This operation is similar to Union. But it also shows the duplicate rows.
SELECT * FROM First UNION ALL SELECT * FROM Second;

ID Name

1 JISY

2 SANTHY

3 SWETH
A
2 SANTHY

3)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 numberof columns and datatype must be same
SELECT * FROM First INTERSECT SELECT * FROM Second;

ID Name
2 SANTHY

4)MINUS/ EXCEPT:

It combines the result of two SELECT statements. Minus operator is used to display

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 26


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

the rows which are present in the first query but absent in the second query.
SELECT * FROM First Except SELECT * FROM Second;

ID Name

1 JISY

SELECT * FROM Second MINUS SELECT * FROM First ;

ID Name

3 SWETH
A

2.6 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.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 27


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Syntax

1. COUNT(*)
2. or
3. 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()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 28


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 29


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Com1 5
Com2 3

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.

Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 30


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Com1 150
Com2 170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. 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

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.

Syntax

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 31


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

2.6.2Aggregation with Null and Boolean Values

In general, aggregate functions treat nulls according to the following rule: All
aggregate functions except count (*) ignore null values in their input collection. As a
result of null values being ignored, the collection of values may be empty. The count of
an empty collection is defined to be 0, and all other aggregate operations return a value
of null when applied on an empty collection. A Boolean data type that can take values
true, false, and unknown.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 32


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

2.7 Nested Queries in SQL

In nested queries, a query is written inside a query. The result of inner query is used in execution
of outer query. We will use STUDENT, COURSE, STUDENT_COURSE tables for
understanding nested queries.
STUDENT

S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

STUDENT_COURSE

COURSE
S_ID C_ID
C_ID C_NAME
S1 C1
C1 DSA
S1 C3
C2 Programming
S2 C1
C3 DBMS
S3 C2

S4 C2

S4 C3

There are mainly two types of nested queries:


• Independent Nested Queries: In independent nested queries, query execution starts from
innermost query to outermost queries. The execution of inner query is independent of outer

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 33


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

query, but the result of inner query is used in execution of outer query. Various operators like IN,
NOT IN, ANY, ALL etc are used in writing independent nested queries.

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write
it with the help of independent nested query and IN operator. From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for finding S_IDs
from STUDENT_COURSE TABLE.

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


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID


Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and outer query will return
those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will
return S1, S2 and S4.

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

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

The innermost query will return a set with members C1 and C3. Second inner query will return
those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case) which are
S1, S2 and S4. The outermost query will return those S_IDs where S_ID is not a member of set
(S1, S2 and S4). So it will return S3.

• Co-related Nested Queries: In co-related nested queries, the output of inner query depends on
the row which is being currently executed in outer query. e.g.; If we want to find
out S_NAME of STUDENTs who are enrolled in C_ID ‘C1’, it can be done with the help of co-
related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 34


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

For each row of STUDENT S, it will find the rows from STUDENT_COURSE where
S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true and
corresponding S_ID will be returned as output.

2.8 View – complex queries


Views in SQL
o Views in SQL are considered as a virtual table. A view
also contains rows and columns.
o To create the view, we can select the fields from one or
more tables present in the database.
o A view can either have specific rows based on certain
condition or all the rows of a table.

Sample table: Student_Detail

STU_ID NAME ADDRESS


1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE


1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18

1. Creating view

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 35


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

A view can be created using the CREATE VIEW statement. We can


create a view from a single table or multiple tables.

Syntax:
CREATE VIEW view_name AS SELECT column1, column2.....
FROM table_name WHERE condition;Creating View from a single table

Query:

CREATE VIEW DetailsView AS SELECT NAME, ADDRESS


FROM Student_Details WHERE STU_ID < 4;

Just like table query, we can query the


view to view the data. SELECT * FROM
DetailsView;

Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad

2.
3.
4.

3. Creating View from multiple tables

View from multiple tables can be created by simply include multiple


tables in the SELECT statement.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 36


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

In the given example, a view is created named MarksView from two


tables Student_Detail and Student_Marks.

Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS,
Student_Marks.MARKS FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of
View MarksView:
SELECT * FROM
MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97
Kathrin Noida 86

David Ghaziabad 74
Alina Gurugram 90

4. Deleting View

A view can be deleted using the Drop View statement.

Syntax
1. DROP VIEW view_name;

Example:

If we want to delete the View MarksView, we can do this as:


1. DROP VIEW MarksView;

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 37


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting
access to a predetermined set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.Simplify
commands for the user –
Views allows the user to select information from multiple tables
without requiring the users to actually know how to perform a join.
3. Store complex queries –
Views can be used to store complex queries.
4. Rename Columns –
Views can also be used to rename the columns without affecting
the base tables provided the number of columns in view must
match the number of columns specified in select statement. Thus,
renaming helps to to hide the names of the columns of the base
tables.
5. Multiple view facility –
Different views can be created on the same table for different users.

2.8.1 Complex queries

There are two types of views in SQL :


1. Simple view : When the view is been created on View in SQL
2. Complex view : When the view is been created on multiple tables then it is called as
complex view.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 38


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

3. Materialized view : The materialized view is view like a physical table which is
used mainly for performance management.
What is Complex view in SQL with real example?

In this section I would like to explain about complex view in SQL with real life example.

1. Complex view is view which uses multiple data together and create the snapshot of
the data.
2. Relation between table : The relation between multiple table is must to create the
complex views.
3. Complex view is nothing but the view which has been created with multiple joins,
group by statements or set operators to fetch the complex data from multiple tables.
4. The complex views are used to fetch the complex operations to fetch the complex
data from multiple table.

Real life example of Complex view in SQL:


If there are two tables Customer table and Items table and I want to prepare the report where
Customer bought the items.

1.Customer: -Customer_name, Customer_num, Customer_code columns


2.Item: -Customer_code,Item_code,Item_name,Item_category columns
We need to create view where we want to show the associated Items to Customer.Here We need
to use complex join.

Example:

Create view V_Customer as Select e.Customer_name,d.Item_name

from Customer e,Item d

where e.Customer_code=d.customer_code

Group by item_category;

2.8.2 SQL group by

In SQL, The Group By statement is used for organizing similar data into groups. The data is
further organized with the help of equivalent function. It means, if different rows in a precise
column have the same values, it will arrange those rows in a group.

o The SELECT statement is used with the GROUP BY clause in the SQL query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 39


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Syntax:

1. SELECT column1, function_name(column2)


2. FROM table_name
3. WHERE condition
4. GROUP BY column1, column2
5. ORDER BY column1, column2;
6. function_name: Table name.
7. Condition: which we used.

Sample Table:

Employee

S.no Name AGE Salary

1 John 24 25000

2 Nick 22 22000

3 Amara 25 15000

4 Nick 22 22000

5 John 24 25000

Student

SUBJECT YEAR NAME

C language 2 John

C language 2 Ginny

C language 2 Jasmeen

C language 3 Nick

C language 3 Amara

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 40


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Java 1 Sifa

Java 1 dolly

Example:

Group By single column: Group By single column is used to place all the rows with the same
value. These values are of that specified column in one group. It signifies that all rows will put
an equal amount through a single column, which is of one appropriate column in one group.

Consider the below query:

1. SELECT NAME, SUM (SALARY) FROM Employee


2. GROUP BY NAME;

The output of the query is:

NAME SALARY

John 50000

Nick 44000

Amara 15000

In the output, the rows which hold duplicate NAME are grouped under a similar NAME, and
their corresponding SALARY is the sum of the SALARY of the duplicate rows.

o Groups based on several columns: A group of some columns are GROUP BY column
1, column2, etc. Here, we are placing all rows in a group with the similar values of
both column 1 and column 2.

Consider the below query:

1. SELECT SUBJECT, YEAR, Count (*)


2. FROM Student
3. Group BY SUBJECT, YEAR;

Output:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 41


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

SUBJECT YEAR Count

C language 2 3

C language 3 2

Java 1 2

In the above output, the student with similar SUBJECT and YEAR are grouped in the same
place. The students who have only one thing in common belongs to different groups. For
example, if the NAME is same and the YEAR is different.

Now, we have to group the table according to more than one column or two columns.

2.8.3 HAVING Clause

WHERE clause is used for deciding purpose. It is used to place conditions on the columns to
determine the part of the last result-set of the group. Here, we are not required to use the
combined functions like COUNT (), SUM (), etc. with the WHERE clause. After that, we need
to use a HAVING clause.

Having clause Syntax:

1. SELECT column1, function_name(column2)


2. FROM table_name
3. WHERE condition
4. GROUP BY column1, column2
5. HAVING condition
6. ORDER BY column1, column2;
7. function_name: Mainly used for name of the function, SUM(), AVG().
8. table_name: Used for name of the table.
9. condition: Condition used.

Example:

1. SELECT NAME, SUM(SALARY) FROM Employee


2. GROUP BY NAME

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 42


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

3. HAVING SUM(SALARY)>23000;

Output:

Name SUM(SALARY)

John 50000

According to the above output, only one name in the NAME column has been listed in the result
because there is only one data in the database whose sum of salary is more than 50000.

It should be placed on groups, not on the columns.

Points:

o The GROUP BY Clause is used to group the rows, which have the same values.
o The SELECT statement in SQL is used with the GROUP BY clause.
o In the Group BY clause, the SELECT statement can use constants, aggregate
functions, expressions, and column names.
o The GROUP BY Clause is called when the HAVING clause is used to reduce the results.

2.9 Modification Of Database


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

1) INSERT Statement

The INSERT Statement adds one or more rows to a table. It has two formats:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 43


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

INSERT INTO table-1 [(column-list)] VALUES (value-list)


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

The VALUES Clause in the INSERT Statement provides a set of values to place in
the columns of a new row. It has the following general format:

VALUES ( value-1 [, value-2] ... )

value-1 and value-2 are Literal Values or Scalar


Expressions involving literals. They can also specify NULL.
The values list in the VALUES clause must match the explicit or implicit column list
for INSERT in degree (number of items).
They must also match the data type of corresponding column or be convertible
to that data type.
INSERT Examples

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 44


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

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

Before After

pno descr color pno descr color

P1 Widget Blue P1 Widget Blue

P2 Widget Red P2 Widget Red


=>
P3 Dongle Green P3 Dongle Green

P4 NULL Brown

INSERT INTO sp SELECT s.sno, p.pno, 500


FROM s, p WHERE p.color='Green' AND s.city='London'
Before After

sno pno qty sno pno qty

S1 P1 NULL S1 P1 NULL

S2 P1 200 S2 P1 200

S3 P1 1000 => S3 P1 1000

S3 P2 200 S3 P2 200

S2 P3 500

2) UPDATE Statement

The UPDATE statement modifies columns in selected table rows. It has the
following general format:

UPDATE table-1 SET set-list [WHERE predicate]

The optional WHERE Clause has the same format as in the SELECT Statement.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 45


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

The set-list contains assignments of new values for selected columns. See SET
Clause.
The SET Clause expressions and WHERE Clause predicate can contain subqueries.

SET Clause

The SET Clause in the UPDATE Statement updates (assigns new value to) columns
in the selected table rows. It has the following general format:

SET column-1 = value-1 [, column-2 = value-2] ...

column-1 and column-2 are columns in the Update table. value-


1 and value-2 are expressions that can reference columns from the update table.
They also can be the keyword -- NULL, to set the column to null.
UPDATE Examples

UPDATE sp SET qty = qty + 20

Before After

sno pno qty sno pno qty

S1 P1 NULL S1 P1 NULL
=>
S2 P1 200 S2 P1 220

S3 P1 1000 S3 P1 1020

S3 P2 200 S3 P2 220

Before After

sno name city sno name city

S1 Pierre Paris S1 Pierre Paris


=>
S2 John London S2 John London

S3 Mario Rome S3 Tony Milan

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 46


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

DELETE Statement

The DELETE Statement removes selected rows from a table. It has the following
general format:

DELETE FROM table-1 [WHERE predicate]

The optional WHERE Clause has the same format as in the SELECT Statement.
The WHERE Clause predicate can contain subqueries.

DELETE Examples
DELETE FROM sp WHERE pno = 'P1'

Before After
sno pno qty sno pno qty

S1 P1 NULL S3 P2 200

S2 P1 200 =>

S3 P1 1000

S3 P2 200

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

Before After

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 47


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

pno descr color pno descr color

P1 Widget Blue P1 Widget Blue


=>
P2 Widget Red P2 Widget Red

P3 Dongle Green

2.10 JOIN RELATION

The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN
is a means for combining fields from two tables by using values common to each.

There are different types of joins available in SQL −


• INNER JOIN − returns rows when there is a match in both tables.
• LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
table.
• RIGHT JOIN − returns all rows from the right table, even if there are no matches in the
left table.
• FULL JOIN − returns rows when there is a match in one of the tables.
• SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
• CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or
more joined tables.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 48


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Sample Table :EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 49


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

PROJECT

PROJECT_NO EMP_ID DEPARTMENT


101 1 Testing
102 2 Development
103 3 Designing
104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development

2. LEFT JOIN

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 50


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL

3. RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 51


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 52


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

2.11 DDL Commands in SQL

DDL is an abbreviation of Data Definition Language.

The DDL Commands in Structured Query Language are used to create and modify the schema of
the database and its objects. The syntax of DDL commands is predefined for describing the data.
The commands of Data Definition Language deal with how the data should exist in the database.

Following are the five DDL commands in SQL:

1. CREATE Command
2. DROP Command
3. ALTER Command
4. TRUNCATE Command
5. RENAME Command

CREATE Command

CREATE is a DDL command used to create databases, tables, triggers and other database
objects.

Examples of CREATE Command in SQL

Example 1: This example describes how to create a new database using the CREATE DDL
command.

Syntax to Create a Database:

1. CREATE Database Database_Name;

Suppose, you want to create a Books database in the SQL database. To do this, you have to write
the following DDL Command:

1. Create Database Books;

Example 2: This example describes how to create a new table using the CREATE DDL
command.

Syntax to create a new table:

1. CREATE TABLE table_name

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 53


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

2. (
3. column_Name1 data_type ( size of the column ) ,
4. column_Name2 data_type ( size of the column) ,
5. column_Name3 data_type ( size of the column) ,
6. ...
7. column_NameN data_type ( size of the column )
8. ) ;

Suppose, you want to create a Student table with five columns in the SQL database. To do this,
you have to write the following DDL command:

1. CREATE TABLE Student


2. (
3. Roll_No. Int ,
4. First_Name Varchar (20) ,
5. Last_Name Varchar (20) ,
6. Age Int ,
7. Marks Int ,
8. ) ;

Example 3: This example describes how to create a new index using the CREATE DDL
command.

Syntax to Create a new index:

1. CREATE INDEX Name_of_Index ON Name_of_Table (column_name_1 , column_name_2 ,


… . , column_name_N);

Let's take the Student table:

Stu_Id Name Marks City State

100 Abhay 80 Noida U.P

101 Sushil 75 Jaipur Rajasthan

102 Ankit 90 Gurgaon Haryana

103 Yogesh 93 Lucknow U.P

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 54


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Suppose, you want to create an index on the combination of the City and State field of
the Student table. For this, we have to use the following DDL command:

1. CREATE INDEX index_city_State ON Employee (Emp_City, Emp_State);

Example 4: This example describes how to create a trigger in the SQL database using the
DDL CREATE command.

Syntax to create a trigger:

1. CREATE TRIGGER [trigger_name]


2. [ BEFORE | AFTER ]
3. { INSERT | UPDATE | DELETE }
4. ON [table_name] ;

DROP Command

DROP is a DDL command used to delete/remove the database objects from the SQL database.
We can easily remove the entire table, view, or index from the database using this DDL
command.

Examples of DROP Command in SQL

Example 1: This example describes how to remove a database from the SQL database.

Syntax to remove a database:

1. DROP DATABASE Database_Name;

Suppose, you want to delete the Books database from the SQL database. To do this, you have to
write the following DDL command:

1. DROP DATABASE Books;

Example 2: This example describes how to remove the existing table from the SQL
database.

Syntax to remove a table:

1. DROP TABLE Table_Name;

Suppose, you want to delete the Student table from the SQL database. To do this, you have to
write the following DDL command:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 55


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1. DROP TABLE Student;

Example 3: This example describes how to remove the existing index from the SQL
database.

Syntax to remove an index:

1. DROP INDEX Index_Name;

Suppose, you want to delete the index_city from the SQL database. To do this, you have to write
the following DDL command:

1. DROP INDEX Index_city;

ALTER Command

ALTER is a DDL command which changes or modifies the existing structure of the database,
and it also changes the schema of database objects.

We can also add and drop constraints of the table using the ALTER command.

Examples of ALTER Command in SQL

Example 1: This example shows how to add a new field to the existing table.

Syntax to add a newfield in the table:

1. ALTER TABLE name_of_table ADD column_name column_definition;

Suppose, you want to add the 'Father's_Name' column in the existing Student table. To do this,
you have to write the following DDL command:

1. ALTER TABLE Student ADD Father's_Name Varchar(60);

Example 2: This example describes how to remove the existing column from the table.

Syntax to remove a column from the table:

1. ALTER TABLE name_of_table DROP Column_Name_1 , column_Name_2 , ….., column_Na


me_N;

Suppose, you want to remove the Age and Marks column from the existing Student table. To do
this, you have to write the following DDL command:

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 56


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1. ALTER TABLE StudentDROP Age, Marks;

Example 3: This example describes how to modify the existing column of the existing table.

Syntax to modify the column of the table:

1. ALTER TABLE table_name MODIFY ( column_name column_datatype(size));

Suppose, you want to change the character size of the Last_Namefield of the Student table. To
do this, you have to write the following DDL command:

1. ALTER TABLE table_name MODIFY ( Last_Name varchar(25));

TRUNCATE Command

TRUNCATE is another DDL command which deletes or removes all the records from the table.

This command also removes the space allocated for storing the table records.

Syntax of TRUNCATE command

1. TRUNCATE TABLE Table_Name;

Example

Suppose, you want to delete the record of the Student table. To do this, you have to write the
following TRUNCATE DDL command:

1. TRUNCATE TABLE Student;

The above query successfully removed all the records from the student table. Let's verify it by
using the following SELECT statement:

1. SELECT * FROM Student;

RENAME Command

RENAME is a DDL command which is used to change the name of the database table.

Syntax of RENAME command

1. RENAME TABLE Old_Table_Name TO New_Table_Name;

Example

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 57


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

1. RENAME TABLE Student TO Student_Details ;

This query changes the name of the table from Student to Student_Details.

2.12 Embedded SQL


Like we said above, embedded SQL is the one which combines the high level language with the
DB language like SQL. It allows the application languages to communicate with DB and get
requested result. The high level languages which supports embedding SQLs within it are also
known as host language. There are different host languages which support embedding SQL
within it like C, C++, ADA, Pascal, FORTRAN, Java etc. When SQL is embedded within C or
C++, then it is known as Pro*C/C++ or simply Pro*C language. Pro*C is the most commonly
used embedded SQL. Let us discuss below embedded SQL with respect to C language.

Connection to DB
This is the first step while writing a query in high level languages. First connection to the DB
that we are accessing needs to be established. This can be done using the keyword CONNECT.
But it has to precede with ‘EXEC SQL’ to indicate that it is a SQL statement.

EXEC SQL CONNECT db_name;

2.13 Dynamic SQL


Dynamic SQL statements are those SQL statements that are created or executed at the run-
time. The users can execute their own query in some application. These statements are
compiled at the run-time. These kinds of SQL statements are used where there is a non-
uniformity in the data stored in the database. It is more flexible as compared to the static SQL
and can be used in some flexible applications.

Since the compilation is done at run-time, the system will know how to access the database at
run-time only. So, no proper planning for execution and optimization can be done previously.
This will reduce the performance of the system. Also, if you are taking the database query
from the user at run-time, then there are possibilities that the users might enter some wrong
queries and this is very dangerous because here you are dealing with lots and lots of data.

2.14 Other SQL Functions


Functions are very powerful feature of SQL and can be used to do the following:

Perform calculations on dala

Modify individual data items

Manipulate output for groups of rows

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 58


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Format dates and numbers for display

Convert column datatypes

SQL functions may accept arguments and always retum a value.

Note: Most of the functions described in this lesson are specific to Oracle'sversions.
Types of Functions
In general, functions in Oracle SQL are divided into five groups, the first group being the
topic of this chapter, namely, single row functions. Other function types are aggregate
functions, which create groups of rows; analytic functions, which also group but allow in-
depth data analysis; object reference functions, allowing access to special object pointers;
and finally user-defined functions, such as those you create using a programming language
such as PL/SQL.
Single Row Functions— Single row functions can be used to execute an operation
on each row of a query. In other words, a single row function can be used to execute
the same operation for every row a query retrieves.
Aggregate Functions— These functions summarize repeating groups in a row set
into distinct groups, aggregating repetitive values into items such as sums or
averages.
Analytic Functions— Unlike aggregates, which summarize repetitions into unique
items, analytics create subset summaries within aggregates.
Object Reference Functions— These functions use pointers to reference values.
Commonly, object reference functions either reference objects or dereference
values from objects.
User-Defined Functions— Custom functions can be built using PL/SQL, allowing
extension of the large library of Oracle SQL built-infunctionality. PL/SQL is
beyond the scope of this book.
Single Row Functions
Now let's focus on the subject matter of this chapter. Recall that a single row function was
defined as a function that can be used to execute an operation oneach row of a query.
Let's start this journey by discovering the different classifications for single row functions:
String Functions These functions take a string as a parameterand
return a number or a string.

Number Functions A number is passed in, usually returning anumber.

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 59


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Datetime Functions These functions accept date value parameters.


User-
Conversion Functions These functions convert between different
datatypes. Define
d
Miscellaneous Functions Odd functions fall into this category. Functi
ons
User-defined Functions Functions created by a user via PL/SQL
A

user-defined function is a function created by a user in addition to the Oracle built-

functions. Believe it or not, sometimes the plethora of available Oracle built-in functions

will not suffice. Creating your own functions can be done using PL/SQL.

CHARACTER FUNCTIONS

Character functions operate on values of character class datatype, i.e., Char, Varchar2,
Varchar etc. These functions can return either character class datatype or number classs
datatype based on the operation performed on the input data. Length of a value returned by
these functions is limited upto 4000 bytes for varchar2 datatype and 2000 bytes for char
datatype. If a function returns a value that exceedes the length limit, Oracle automatically
truncate the value before returning the result. Some of the SQL built-in character functions
are given in the following table.

Single-row Character Functions

CHR CONCAT INITCAP SUBSTR

RTRIM LTRIM TRIM REPLACE


S
LPAD RPAD UPPER LOWER
E
TRANSLATE ASCII INSTR LENGTH
L
ASCII ( 'Ç' )
199

ECT ASCII('Ç')FROM
DUAL;

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 60


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

SELECT CHR(76) "KARAKTER"


FROM DUAL ;

K
L A
R
SELECT ENAME, CONCAT(ENAME, JOB), LENGTH(ename),
INSTR(ename, 'A' )
FROM EMP
WHERE SUBSTR(job ,1 , 5) = UPPER('saLEs');

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME INSTR(ENAME,'A'


) )
ALLEN ALLENSALESMAN 5 1
WARD WARDSALESMAN 4 2
MARTIN MARTINSALESMAN 6 2
TURNER TURNERSALESMAN 6 0

SELECT ENAME, CONCAT(ENAME, JOB), LENGTH(ename),


INSTR(ename, 'A' )
FROM EMP
WHERE SUBSTR(ename , -1 , 1) = 'N' ;

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME INSTR(ENAME,'A'


) )
ALLEN ALLENSALESMAN 5 1
MARTIN MARTINSALESMAN 6 2
SELECT INSTR('MISSISSIPPI' , 'S' ,5 , 2)FROM
DUAL;

INSTR('MISSISSIPPI','S',5,2)
7

SELECT LPAD( ENAME , 20 , '*' )

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 61


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

FROM emp;

LPAD(ENAME,20,'*')
***************SMITH
***************ALLEN
14 rows selected.

SELECT RPAD( ENAME , 20 , '*' )FROM


EMP;

RPAD(ENAME,20,'*')
SMITH***************
ALLEN***************

14 rows selected.

SELECT LTRIM('aaaaabbccxXXyyzzaaabbbccc' , 'a') LtrimFROM DUAL;

LT
RI
bbccxXXyyzzaaabbbccc
M

SELECT RTRIM('aaaaabbccxXXyyzzaaabbbcccaaaaaaaa' , 'a') RtrimFROM DUAL;

RTRIM
aaaaabbccxXXyyzzaaabbbccc

SELECT ENAME
FROM EMP
WHERE SOUNDEX(ename) = SOUNDEX('SMYTHE');

EN
A
SMITH
M
E
RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 62
RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

SELECT SUBSTR('ABCDEFGHIJK' ,4,3) "Alt Metin"


FROM DUAL;

A
DEF l
t

A. Case Conversion Functions


M
• LOWER
• UPPER e
• INITCAP t
i
B. Character Manipulation Functions
o CONCAT n
o SUBSTR
o LENGTH
o INSTR
o LPAD
o RPAD
o TRIM
o LTRIM
o RTRIM
o ASCII
o CHR
o REPLACE
o TRANSLATE

Function Result

LOWER('SQL Course') sql course SQL

UPPER('SQLCourse') COURSE

INITCAP('SQLCourse'} Sql Course

Case Conversion Functions

LOWER, UPPER, and INITCAP are the three case conversion functions.
• LOWER Converts mıxed case ör uppercass character string lo
louercase
• UPPER Converts mısed case ör louercasc clıaracter string to
uppcrcase

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 63


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

• INITCAP Converts first letter of each word to uppercase andrcmainig


Icttcrs to lowercase.

Display the employee number, name, and department number foremployee Blake.

SELECT empno, ename, deptnoFROM


emp
WHERE ename = 'blake';no rows
selected

The WHERE clause of the first SQL statement specifies the employee name as ' blake.'
Since all the data in the EMP tabls is stored in uppercase. the name ' blake' does not ffind
a match in the EMP table and as a result no rowsare selected.

SELECT empno, ename, deptnoFROM


emp
WHERE LOWER( ename) = 'blake’ ;

EMPNO ENAME DEPTNO


7698 BLAKE 30

The WHERE clause of the second SQL statement specifies that the employee name in the
EMP table be converted to lowercase and then be compared to 'blake ' . Since both the
names are in lowercase now, a match is found and one row is selected. The WHERE
clause can be rewritten in the following manner to produce the same result:
Manipulate character strings

Function Result

CONCAT( ‘Good' , 'String' ) GoodString

SUBSTR( 'String' , 1,3 ) Str

LENGTH( 'String' ) 6

INSTR(' String’, ‘r’) 3

LPAD(sal,10 , '*' ) ******5000

Character Manipulation Functions

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 64


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

CONCAT. SUBSTR, LENGTH, INSTR. and LPAD are îhe five charactermanipulation
functions covered in this lesson.
CONCAT Joins values together (Yon are limited to using two parameterswith
CONCAT.)
SUBSTR Extracts a string of determined length LENGTH
Shows the length of a string as a numeric valueINSTR
Finds numerîc position of a named character LPAD
Pads the character value right-justified
Note: RPAD character manipulation function pads the character value lelt-justified.

Example:

The slide example displays ernployee name and job joined together, length of the
employee name, and the numeric position of the letter A in the employee name, forall
employees who are in sales.

SELECT ename, CONCAT( ename, job),


LENGTH(ename),
INSTR(ename, 'A')
FROM emp
WHERE SUBSTR(job, 1, 5) = 'SALES' ;

ENAM CONCAT(ENAME,JO LENGTH(ENAM INSTR(ENAME,'A


E B) E) ')
ALLEN ALLENSALESMAN 5 1
WARD WARDSALESMAN 4 2
MARTIN MARTINSALESMAN 6 2
TURNER TURNERSALESMAN 6 0

Example

Write a SQL statement to display the data for those employees whosenames end
with an N .

SELECT ename, CONCAT(ename, job),


LENGTH(ename), INSTR(ename, 'A')
FROM emp
WHERE SUBSTR(ename, -1, 1) = 'N';

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 65


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME INSTR(ENAME,'A'


) )
ALLEN ALLENSALESMAN 5 1
MARTIN MARTINSALESMAN 6 2

2.15 Integrity and Security

A database represents an essential corporate resource that should be properly secured using
appropriate controls. Multi-user database system must provide a database security and
authorization subsystem to enforce limits on individual and group access rights and privileges.

Database security and integrity is about protecting the database from being inconsistent and
being disrupted. We can also call it database misuse. Database security encompasses hardware,
software, people and data. Database misuse could be Intentional or accidental, where accidental
misuse is easier to cope with than intentional misuse.

Accidental inconsistency could occur due to:

• System crash during transaction processing


• Anomalies due to concurrent access
• Anomalies due to redundancy
• Logical errors

Likewise, even though there are various threats that could be categorized in this group,
intentional misuse could be:

• Unauthorized reading of data


• Unauthorized modification of data or
• Unauthorized destruction of data

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 66


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

Most systems implement good Database Integrity to protect the system from accidental misuse
while there are many computer-based measures to protect the system from intentional misuse,
which is termed as Database Security measures.

Database security is considered in relation to the following situations:

• Theft and fraud


• Loss of confidentiality (secrecy)
• Loss of privacy • Loss of integrity
• Loss of availability

Security Issues and general considerations

• Legal, ethical and social issues regarding the right to access information
• Physical control
• Policy issues regarding privacy of individual level at enterprise and national level
• Operational consideration on the techniques used (password, etc)
• System level security including operating system and hardware control Security levels
and security policies in enterprise level

Database security is the mechanisms that protect the database against intentional or
accidental threats. Threat is any situation or event, whether intentional or accidental, that may
adversely affect a system and consequently the organization. A threat may be caused by a
situation or event involving a person, action, or circumstance that is likely to bring harm to an
organization. The harm to an organization may be tangible or intangible:

• Tangible – loss of hardware, software, or data


• Intangible – loss of credibility or client confidence Examples of threats:
• Using another persons‘ means of access
• Unauthorized amendment/modification or copying of data
• Program alteration
• Inadequate policies and procedures that allow a mix of confidential and normal out put

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 67


RELATIONAL DATABASE MANAGEMENT SYSTEM UNIT-II

• Wire-tapping
• Illegal entry by hacker
• Blackmail
• Creating ‗trapdoor ‘into system
• Theft of data, programs, and equipment
• Failure of security mechanisms, giving greater access than normal
• Staff shortages or strikes
• Inadequate staff training
• Viewing and disclosing unauthorized data
• Electronic interference and radiation
• Data corruption owing to power loss or surge
• Fire (electrical fault, lightning strike, arson), flood, bomb
• Physical damage to equipment
• Breaking cables or disconnection of cables
• Introduction of viruses

RASC- DEPARTMENT COMPUTER SCIENCE AND APPLICATION-N. MANIMOZHI 68

You might also like