Unit-2 1

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

KIT Ajeet Singh

UNIT-2

1 Relational Data Model


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

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

UNIT-2 Page 1
KIT Ajeet Singh

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

Fig No 1 Relational Data Model

3 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

UNIT-2 Page 2
KIT Ajeet Singh

3. Referential integrity constraints

4 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

5 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

UNIT-2 Page 3
KIT Ajeet Singh

3 Apple Inactive

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

Example:

Fig No 2 Referential integrity constraints

In the above example, we have 2 relations, Customer and Billing.


Tuple for CustomerID =1 is referenced twice in the relation Billing. So we know
CustomerName=Google has billing amount $300

UNIT-2 Page 4
KIT Ajeet Singh

7 Operations in Relational Model


Four basic update operations performed on relational database model are

Insert, update, delete and select.

● Insert is used to insert data into the relation

● Delete is used to delete tuples from the table.

● Modify allows you to change the values of some attributes in existing tuples.

● Select allows you to choose a specific range of data.

Whenever one of these operations are applied, integrity constraints specified on the relational
database schema must never be violated.

7.1 Insert Operation

The insert operation gives values of the attribute for a new tuple which should be inserted into a
relation.

Fig No 3 Insert Operation

7.2 Update Operation

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

UNIT-2 Page 5
KIT Ajeet Singh

Fig No 4 Update Operation

7.3 Delete Operation

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

Fig No 5 Delete Operation

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

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

7.4 Select Operation

Fig No 6 Select Operation

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

8 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

UNIT-2 Page 6
KIT Ajeet Singh

● No two rows can be identical

● The values of an attribute should be from the same domain

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

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

11 Summary

● The Relational database model represents the database as a collection of relations (tables)

UNIT-2 Page 7
KIT Ajeet Singh

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

12 Relational Algebra
RELATIONAL ALGEBRA is a widely used procedural query language. It collects instances of
relations as input and gives occurrences of relations as output. It uses various operations to
perform this action. Relational algebra 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.

12.1 Basic Relational Algebra Operations:

Relational Algebra devided in various groups

Unary Relational Operations

● SELECT (symbol: σ)

● PROJECT (symbol: π)

● RENAME (symbol: )

UNIT-2 Page 8
KIT Ajeet Singh

Relational Algebra Operations From Set Theory

● UNION (υ)

● INTERSECTION ( ),

● DIFFERENCE (-)

● CARTESIAN PRODUCT ( x )

Binary Relational Operations

● JOIN

● DIVISION

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

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.

UNIT-2 Page 9
KIT Ajeet Singh

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

Here, the projection of CustomerName and status will give

Π CustomerName, Status (Customers)

CustomerName Status

UNIT-2 Page 10
KIT Ajeet Singh

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

UNIT-2 Page 11
KIT Ajeet Singh

1 2 1 3

A ∪ B gives

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

UNIT-2 Page 12
KIT Ajeet Singh

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.

Fig No 7 Intersection

Example:

A B
Table A B

column 1 column 2

1 1

UNIT-2 Page 13
KIT Ajeet Singh

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

Join Operations

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

Join operation denoted by ⋈.

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

Types of JOIN:

Various forms of join operation are:

Inner Joins:

UNIT-2 Page 14
KIT Ajeet Singh

● Theta join

● EQUI join

● Natural join

Outer join:

● Left Outer Join

● Right Outer Join

● Full Outer Join

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:

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

UNIT-2 Page 15
KIT Ajeet Singh

1 2

EQUI join:

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

For example:

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.

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

Num Square

UNIT-2 Page 16
KIT Ajeet Singh

2 4

3 9

Num Cube

2 8

3 27

C⋈D

C D

Num Square Cube

2 4 4

3 9 27

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.

UNIT-2 Page 17
KIT Ajeet Singh

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.

Fig No Left Outer Join

Consider the following 2 Tables

Num Square

2 4

3 9

4 16

UNIT-2 Page 18
KIT Ajeet Singh

Num Cube

2 8

3 18

5 75

A B

A⋈B

Num Square Cube

2 4 4

3 9 9

4 16 -

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.

UNIT-2 Page 19
KIT Ajeet Singh

Fig No 8 Right Outer Join

A B

A B

Num Cube Square

2 8 4

3 18 9

5 75 -

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

A B

Num Cube Square

2 4 8

3 9 18

4 16 -

5 - 75

UNIT-2 Page 20
KIT Ajeet Singh

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

UNIT-2 Page 21
KIT Ajeet Singh

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.

13 Relational Calculus

o Relational calculus is a non-procedural query language. In the non-procedural query language, the
user is concerned with the details of how to obtain the end results.
o The relational calculus tells what to do but never explains how to do.

13.1 Types of Relational calculus:

Fig No 9 Types of Relational calculus

13.1.1 Tuple Relational Calculus (TRC)


o The tuple relational calculus is specified to select the tuples in a relation. In TRC,

filtering variable uses the tuples of a relation.


o The result of the relation can have one or more tuples.

Notation:

UNIT-2 Page 22
KIT Ajeet Singh

{T | P (T)} or {T | Condition (T)}

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

{ T.name | Author(T) AND T.article = 'database' }

OUTPUT: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).

For example:

{ R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.

13.1.2 Domain Relational Calculus (DRC)


o The second form of relation is known as Domain relational calculus. In domain relational
calculus, filtering variable uses the domain of attributes.
o Domain relational calculus uses the same operators as tuple calculus. It uses logical
connectives ∧ (and), ∨ (or) and ┓ (not).

o It uses Existential (∃) and Universal Quantifiers (∀) to bind the variable.

Notation:

{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

UNIT-2 Page 23
KIT Ajeet Singh

Where

a1, a2 are attributes


P stands for formula built by inner attributes

For example:

{< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational javatpoint, where
the subject is a database.

14 Introduction on SQL

14.1 SQL

o SQL stands for Structured Query Language. It is used for storing and managing data in
relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read,
update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.

14.2 Rules:

SQL follows the following rules:

o Structure query language is not case sensitive. Generally, keywords of SQL are written in
uppercase.

UNIT-2 Page 24
KIT Ajeet Singh

o Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database.

o SQL depends on tuple relational calculus and relational algebra.

14.3 SQL process:


o When an SQL command is executing for any RDBMS, then the system figure out the
best way to carry out the request and the SQL engine determines that how to interpret the
task.
o In the process, various components are included. These components can be optimization
Engine, Query engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query engine
won't handle logical files.

Fig No 10 SQL Query Engine


15 Characteristics of SQL

o SQL is easy to learn.

o SQL is used to access data from relational database management systems.

UNIT-2 Page 25
KIT Ajeet Singh

o SQL can execute queries against the database.

o SQL is used to describe the data.

o SQL is used to define the data in the database and manipulate it when needed.

o SQL is used to create and drop the database and table.

o SQL is used to create a view, stored procedure, function in a database.

o SQL allows users to set permissions on tables, procedures, and views.

16 Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records
from a database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
Well defined standards
Long established are used by the SQL databases that are being used by ISO and ANSI.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.
Multiple data view
Using the SQL language, the users can make different views of the database structure.

17 SQL Datatype
o SQL Datatype is used to define the values that a column can contain.

o Every column is required to have a name and data type in the database table.

UNIT-2 Page 26
KIT Ajeet Singh

17.1 Datatype of SQL:

Fig No 11 Datatypes of SQL

Binary Datatypes

There are Three types of binary Datatypes which are given below:

Data Type Description

Binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.

Varbinary It has a maximum length of 8000 bytes. It contains variable-length binary


data.

Image It has a maximum length of 2,147,483,647 bytes. It contains variable-length


binary data.

Approximate Numeric Datatype :


The subtypes are given below:
Data type From To Description

float -1.79E + 308 1.79E + 308 It is used to specify a floating-point


value e.g. 6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single precision


floating point number

Exact Numeric Datatype


The subtypes are given below:

UNIT-2 Page 27
KIT Ajeet Singh

Data type Description

Int It is used to specify an integer value.

Smallint It is used to specify small integer value.

Bit It has the number of bits to store.

Decimal It specifies a numeric value that can have a decimal number.

Numeric It is used to specify a numeric value.

Character String Datatype

The subtypes are given below:

Data type Description

char It has a maximum length of 8000 characters. It contains Fixed-length non-


unicode characters.

varchar It has a maximum length of 8000 characters. It contains variable-length non-


unicode characters.

text It has a maximum length of 2,147,483,647 characters. It contains variable-


length non-unicode characters.

Date and time Datatypes

The subtypes are given below:

Datatype Description

Date It is used to store the year, month, and days value.

Time It is used to store the hour, minute, and second values.

Timestamp It stores the year, month, day, hour, minute, and the second value.

18 SQL Commands

UNIT-2 Page 28
KIT Ajeet Singh

o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

18.1 Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

Fig No 12 SQL command

Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.

UNIT-2 Page 29
KIT Ajeet Singh

Here are some commands that come under DDL:

o CREATE

o ALTER

o DROP

o TRUNCATE

CREATE It is used to create a new table in the database.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DAT


E);

DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE ;

Example

DROP TABLE EMPLOYEE;

ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

UNIT-2 Page 30
KIT Ajeet Singh

ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

ALTER TABLE MODIFY(COLUMN DEFINITION....);

EXAMPLE

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

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

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE EMPLOYEE;

Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all form of changes
in the database.
o The command of DML is not auto-committed that means it can't permanently save all the
changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT

o UPDATE

o DELETE

INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

UNIT-2 Page 31
KIT Ajeet Singh

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);

For example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CO


NDITION]

For example:

UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'

DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

UNIT-2 Page 32
KIT Ajeet Singh

DELETE FROM javatpoint


WHERE Author="Sonoo";

Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

Grant: It is used to give user access privileges to a database.

Example

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

Revoke: It is used to take back permissions from the user.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT

o ROLLBACK

o SAVEPOINT

Commit: Commit command is used to save all the transactions to the database.

Syntax:

UNIT-2 Page 33
KIT Ajeet Singh

COMMIT;

Example:

DELETE FROM CUSTOMERS


WHERE AGE = 25;
COMMIT;

Rollback: Rollback command is used to undo transactions that have not already been saved to
the database.

Syntax:

ROLLBACK;

Example:

DELETE FROM CUSTOMERS


WHERE AGE = 25;
ROLLBACK;

SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

UNIT-2 Page 34
KIT Ajeet Singh

SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.

Syntax:

SELECT expressions
FROM TABLES
WHERE conditions;

For example:

SELECT emp_name
FROM employee
WHERE age > 20;

19 SQL Operator
There are various types of SQL operator:

UNIT-2 Page 35
KIT Ajeet Singh

Fig No 13 Types of SQL Operator

19.1 SQL Arithmetic Operators

Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example

+ It adds the value of both operands. a+b will give 30

- It is used to subtract the right-hand operand from the a-b will give 10
left-hand operand.

* It is used to multiply the value of both operands. a*b will give 200

/ It is used to divide the left-hand operand by the a/b will give 2


right-hand operand.

UNIT-2 Page 36
KIT Ajeet Singh

% It is used to divide the left-hand operand by the a%b will give 0


right-hand operand and returns reminder.

19.2 SQL Comparison Operators:

Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example

= It checks if two operands values are equal or not, if the (a=b) is not true
values are queal then condition becomes true.

!= It checks if two operands values are equal or not, if values (a!=b) is true
are not equal, then condition becomes true.

<> It checks if two operands values are equal or not, if values (a<>b) is true
are not equal then condition becomes true.

> It checks if the left operand value is greater than right (a>b) is not true
operand value, if yes then condition becomes true.

< It checks if the left operand value is less than right operand (a<b) is true
value, if yes then condition becomes true.

>= It checks if the left operand value is greater than or equal to (a>=b) is not true
the right operand value, if yes then condition becomes true.

<= It checks if the left operand value is less than or equal to the (a<=b) is true
right operand value, if yes then condition becomes true.

!< It checks if the left operand value is not less than the right (a!=b) is not true
operand value, if yes then condition becomes true.

!> It checks if the left operand value is not greater than the (a!>b) is true
right operand value, if yes then condition becomes true.

19.3 SQL Logical Operators

There is the list of logical operator used in SQL:

Operator Description

ALL It compares a value to all values in another value set.

UNIT-2 Page 37
KIT Ajeet Singh

AND It allows the existence of multiple conditions in an SQL


statement.

ANY It compares the values in the list according to the condition.

BETWEEN It is used to search for values that are within a set of values.

IN It compares a value to that specified list value.

NOT It reverses the meaning of any logical operator.

OR It combines multiple conditions in SQL statements.

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

LIKE It compares a value to similar values using wildcard operator.

20 SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns. In
DBMS, the table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient
representation of relations.

Let's see an example of the EMPLOYEE table:

EMP_ID EMP_NAME CITY PHONE_NO

1 Kristen Washington 7289201223

2 Anna Franklin 9378282882

3 Jackson Bristol 9264783838

4 Kellan California 7254728346

5 Ashley Hawaii 9638482678

UNIT-2 Page 38
KIT Ajeet Singh

In the above table, "EMPLOYEE" is the table name, "EMP_ID", "EMP_NAME", "CITY",
"PHONE_NO" are the column names. The combination of data of multiple columns forms a
row, e.g., 1, "Kristen", "Washington" and 7289201223 are the data of one row.

20.1 Operation on Table


1. Create table
2. Drop table
3. Delete table
4. Rename table

SQL Create Table

SQL create table is used to create a table in the database. To define the table, you should define
the name of the table and also define its columns and column's data type.

Syntax

create table "table_name"


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

Example

SQL> CREATE TABLE EMPLOYEE (


EMP_ID INT NOT NULL,
EMP_NAME VARCHAR (25) NOT NULL,
PHONE_NO INT NOT NULL,
ADDRESS CHAR (30),
PRIMARY KEY (ID)
);

UNIT-2 Page 39
KIT Ajeet Singh

If you create the table successfully, you can verify the table by looking at the message by the
SQL server. Else you can use DESC command as follows:

SQL> DESC EMPLOYEE;

Field Type Null Key Default Extra

EMP_ID int(11) NO PRI NULL

EMP_NAME varchar(25) NO NULL

PHONE_NO NO int(11) NULL

ADDRESS YES NULL char(30)


o 4 rows in set (0.35 sec)

Now you have an EMPLOYEE table in the database, and you can use the stored information
related to the employees.

Drop table

A SQL drop table is used to delete a table definition and all the data from a table. When this
command is executed, all the information available in the table is lost forever, so you have to
very careful while using this command.

Syntax

DROP TABLE "table_name";

Firstly, you need to verify the EMPLOYEE table using the following command:

SQL> DESC EMPLOYEE;

Field Type Null Key Default Extra

EMP_ID int(11) NO PRI NULL

UNIT-2 Page 40
KIT Ajeet Singh

EMP_NAME varchar(25) NO NULL

PHONE_NO NO int(11) NULL

ADDRESS YES NULL char(30)

o 4 rows in set (0.35 sec)

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

SQL>DROP TABLE EMPLOYEE;

Now, we can check whether the table exists or not using the following command:

Query OK, 0 rows affected (0.01 sec)

As this shows that the table is dropped, so it doesn't display it.

SQL DELETE table

In SQL, DELETE statement is used to delete rows from a table. We can use WHERE condition
to delete a specific row from a table. If you want to delete all the records from the table, then you
don't need to use the WHERE clause.

Syntax

DELETE FROM table_name WHERE condition;

Example

Suppose, the EMPLOYEE table having the following records:

EMP_ID EMP_NAME CITY PHONE_NO SALARY

UNIT-2 Page 41
KIT Ajeet Singh

1 Kristen Chicago 9737287378 150000

2 Russell Austin 9262738271 200000

3 Denzel Boston 7353662627 100000

4 Angelina Denver 9232673822 600000

5 Robert Washington 9367238263 350000

6 Christian Los angels 7253847382 260000

The following query will DELETE an employee whose ID is 2.

SQL> DELETE FROM EMPLOYEE


WHERE EMP_ID = 3;

Now, the EMPLOYEE table would have the following records.

EMP_ID EMP_NAME CITY PHONE_NO SALARY

1 Kristen Chicago 9737287378 150000

2 Russell Austin 9262738271 200000

4 Angelina Denver 9232673822 600000

5 Robert Washington 9367238263 350000

6 Christian Los angels 7253847382 260000

If you don't specify the WHERE condition, it will remove all the rows from the table.

DELETE FROM EMPLOYEE;

Now, the EMPLOYEE table would not have any records

UNIT-2 Page 42
KIT Ajeet Singh

21 SQL SELECT Statement


In SQL, the SELECT statement is used to query or retrieve data from a table in the database. The
returns data is stored in a table, and the result table is known as result-set.

Syntax

SELECT column1, column2, ...


FROM table_name;

Here, the expression is the field name of the table that you want to select data from.

Use the following syntax to select all the fields available in the table:

SELECT * FROM table_name;

Example:

EMPLOYEE

EMP_ID EMP_NAME CITY PHONE_NO SALARY

1 Kristen Chicago 9737287378 150000

2 Russell Austin 9262738271 200000

3 Angelina Denver 9232673822 600000

4 Robert Washington 9367238263 350000

5 Christian Los angels 7253847382 260000

To fetch the EMP_ID of all the employees, use the following query:

SELECT EMP_ID FROM EMPLOYEE;

Output

EMP_ID

UNIT-2 Page 43
KIT Ajeet Singh

To fetch the EMP_NAME and SALARY, use the following query:

SELECT EMP_NAME, SALARY FROM EMPLOYEE;


EMP_NAME SALARY

Kristen 150000

Russell 200000

Angelina 600000

Robert 350000

Christian 260000

To fetch all the fields from the EMPLOYEE table, use the following query:

SELECT * FROM EMPLOYEE

Output

EMP_ID EMP_NAME CITY PHONE_NO SALARY

1 Kristen Chicago 9737287378 150000

2 Russell Austin 9262738271 200000

3 Angelina Denver 9232673822 600000

4 Robert Washington 9367238263 350000

5 Christian Los angels 7253847382 260000

UNIT-2 Page 44
KIT Ajeet Singh

22 SQL INSERT Statement


The SQL INSERT statement is used to insert a single or multiple data in a table. In SQL, You
can insert the data in two ways:

1. Without specifying column name


2. By specifying column name

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

Without specifying column name

If you want to specify all column values, you can specify or ignore the column values.

Syntax

INSERT INTO TABLE_NAME


VALUES (value1, value2, value 3, .... Value N);

Query

INSERT INTO EMPLOYEE VALUES (6, 'Marry', 'Canada', 600000, 48);

Output: After executing this query, the EMPLOYEE table will look like:

UNIT-2 Page 45
KIT Ajeet Singh

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

By specifying column name

To insert partial column values, you must have to specify the column names.

Syntax

INSERT INTO TABLE_NAME


[(col1, col2, col3,.... col N)]
VALUES (value1, value2, value 3, .... Value N);

Query

INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40);

Output: After executing this query, the table will look like:

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

UNIT-2 Page 46
KIT Ajeet Singh

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

7 Jack Null null 40

Note: In SQL INSERT query, if you add values for all columns then there is no need to
specify the column name. But, you must be sure that you are entering the values in the
same order as the column exists.

23 SQL Update Statement


The SQL UPDATE statement is used to modify the data that is already in the database. The
condition in the WHERE clause decides that which row is to be updated.

Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

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

UNIT-2 Page 47
KIT Ajeet Singh

Updating single record

Update the column EMP_NAME and set the value to 'Emma' in the row where SALARY is
500000.

Syntax

UPDATE table_name
SET column_name = value
WHERE condition;

Query

UPDATE EMPLOYEE
SET EMP_NAME = 'Emma'
WHERE SALARY = 500000;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_I EMP_NAME CITY SALARY AGE


D

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Emma Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Updating multiple records

If you want to update multiple columns, you should separate each field assigned with a comma.
In the EMPLOYEE table, update the column EMP_NAME to 'Kevin' and CITY to 'Boston'
where EMP_ID is 5.

UNIT-2 Page 48
KIT Ajeet Singh

Syntax

UPDATE table_name
SET column_name = value1, column_name2 = value2
WHERE condition;

Query

UPDATE EMPLOYEE
SET EMP_NAME = 'Kevin', City = 'Boston'
WHERE EMP_ID = 5;

Output

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 Kevin Boston 200000 36

6 Marry Canada 600000 48

Without use of WHERE clause

If you want to update all row from a table, then you don't need to use the WHERE clause. In the
EMPLOYEE table, update the column EMP_NAME as 'Harry'.

Syntax

UPDATE table_name
SET column_name = value1;

UNIT-2 Page 49
KIT Ajeet Singh

Query

UPDATE EMPLOYEE
SET EMP_NAME = 'Harry';

Output

EMP_ID EMP_NAME CITY SALARY AGE

1 Harry Chicago 200000 30

2 Harry Austin 300000 26

3 Harry Denver 100000 42

4 Harry Washington 500000 29

5 Harry Los angels 200000 36

6 Harry Canada 600000 48

24 SQL DELETE Statement

The SQL DELETE statement is used to delete rows from a table. Generally, DELETE statement
removes one or more records form a table.

Syntax

DELETE FROM table_name WHERE some_condition;

Sample Table

EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

UNIT-2 Page 50
KIT Ajeet Singh

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Deleting Single Record

Delete the row from the table EMPLOYEE where EMP_NAME = 'Kristen'. This will delete only
the fourth row.

Query

DELETE FROM EMPLOYEE


WHERE EMP_NAME = 'Kristen';

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Deleting Multiple Record

Delete the row from the EMPLOYEE table where AGE is 30. This will delete two rows(first and
third row).

UNIT-2 Page 51
KIT Ajeet Singh

Query

DELETE FROM EMPLOYEE WHERE AGE= 30;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE

2 Robert Austin 300000 26

3 Christian Denver 100000 42

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Delete all of the records

Delete all the row from the EMPLOYEE table. After this, no records left to display. The
EMPLOYEE table will become empty.

Syntax

DELETE * FROM table_name;


or
DELETE FROM table_name;

Query

DELETE FROM EMPLOYEE;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE

UNIT-2 Page 52
KIT Ajeet Singh

25 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

UNIT-2 Page 53
KIT Ajeet Singh

Creating view

A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

Creating View from a single table

In this example, we create a View named DetailsView from the table Student_Detail.

Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.

SELECT * FROM DetailsView;


Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

UNIT-2 Page 54
KIT Ajeet Singh

Creating View from multiple tables

View from multiple tables can be created by simply include multiple tables in the SELECT
statement.

In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.

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

To display data of View MarksView:

SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

Deleting View

A view can be deleted using the Drop View statement.

Syntax

DROP VIEW view_name;

UNIT-2 Page 55
KIT Ajeet Singh

Example:

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

DROP VIEW MarksView;

26 SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very fast.

o An Index is used to speed up select queries and where clauses. But it shows down the
data input with insert and update statements. Indexes can be created or dropped without
affecting the data.
o An index in a database is just like an index in the back of a book.

o For example: When you reference all pages in a book that discusses a certain topic, you
first have to refer to the index, which alphabetically lists all the topics and then referred
to one or more specific page numbers.

26.1 Create Index statement

It is used to create an index on a table. It allows duplicate value.

Syntax

CREATE INDEX index_name


ON table_name (column1, column2, ...);

Example

CREATE INDEX idx_name


ON Persons (LastName, FirstName);

26.2 Unique Index statement

It is used to create a unique index on a table. It does not allow duplicate value.

UNIT-2 Page 56
KIT Ajeet Singh

Syntax

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Example

CREATE UNIQUE INDEX websites_idx


ON websites (site_name);

26.3 Drop Index Statement

It is used to delete an index in a table.

Syntax

DROP INDEX index_name;

Example

DROP INDEX websites_idx;

27 SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query,
and the inner query is known as a subquery.

UNIT-2 Page 57
KIT Ajeet Singh

o Subqueries are on the right side of the comparison operator.

o A subquery is enclosed in parentheses.

o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can
be used to perform the same function as ORDER BY command.

27.1 Subqueries with the Select Statement

SQL subqueries are most frequently used with the Select statement.

Syntax

SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

UNIT-2 Page 58
KIT Ajeet Singh

SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

27.2 Subqueries with the INSERT Statement


o SQL subquery can also be used with the Insert statement. In the insert statement, data
returned from the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date
functions.

Syntax:

INSERT INTO table_name (column1, column2, column3....)


SELECT *
FROM table_name
WHERE VALUE OPERATOR

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

UNIT-2 Page 59
KIT Ajeet Singh

Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.

INSERT INTO EMPLOYEE_BKP


SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE);
27.3 Subqueries with the UPDATE Statement

The subquery of SQL can be used in conjunction with the Update statement. When a subquery is
used with the Update statement, then either single or multiple columns in a table can be updated.

Syntax

UPDATE table
SET column_name = new_value
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE


table. The given example updates the SALARY by .25 times in the EMPLOYEE table for all
employee whose AGE is greater than or equal to 29.

UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
UNIT-2 Page 60
KIT Ajeet Singh

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

27.4 Subqueries with the DELETE Statement

The subquery of SQL can be used in conjunction with the Delete statement just like any other
statements mentioned above.

Syntax

DELETE FROM TABLE_NAME


WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE


table. The given example deletes the records from the EMPLOYEE table for all EMPLOYEE
whose AGE is greater than or equal to 29.

UNIT-2 Page 61
KIT Ajeet Singh

DELETE FROM EMPLOYEE


WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the following
records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

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

28.1 Types of SQL Aggregation Function

Fig no 14 Types of SQL Aggregate 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.

UNIT-2 Page 62
KIT Ajeet Singh

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()

UNIT-2 Page 63
KIT Ajeet Singh

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

UNIT-2 Page 64
KIT Ajeet Singh

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

UNIT-2 Page 65
KIT Ajeet Singh

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

UNIT-2 Page 66
KIT Ajeet Singh

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;

UNIT-2 Page 67
KIT Ajeet Singh

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

29 SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".

In SQL, JOIN clause is used to combine the records from two or more tables in a database.

29.1 Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN

UNIT-2 Page 68
KIT Ajeet Singh

4. FULL JOIN

Sample Table

EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

UNIT-2 Page 69
KIT Ajeet Singh

1. INNER JOIN

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

Syntax

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


FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

UNIT-2 Page 70
KIT Ajeet Singh

2. LEFT JOIN

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

Syntax

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


FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

UNIT-2 Page 71
KIT Ajeet Singh

3. RIGHT JOIN

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

Syntax

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


FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN

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

UNIT-2 Page 72
KIT Ajeet Singh

Syntax

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


FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

30 SQL Set Operation


The SQL Set operation is used to combine the two or more SQL SELECT statements.

UNIT-2 Page 73
KIT Ajeet Singh

30.1 Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

Fig No 15 SQL Set Operation

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

Syntax

SELECT column_name FROM table1


UNION
SELECT column_name FROM table2;
UNIT-2 Page 74
KIT Ajeet Singh

Example:

The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

SELECT * FROM First


UNION
SELECT * FROM Second;

The resultset table will look like:

ID NAME

UNIT-2 Page 75
KIT Ajeet Singh

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

The resultset table will look like:

ID NAME

UNIT-2 Page 76
KIT Ajeet Singh

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.

o It has no duplicates and it arranges the data in ascending order by default.

Syntax

SELECT column_name FROM table1


INTERSECT
SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

The resultset table will look like:

UNIT-2 Page 77
KIT Ajeet Singh

ID NAME

3 Jackson

4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM table1


MINUS
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

UNIT-2 Page 78
KIT Ajeet Singh

2 Harry

31 Cursors in PL/SQL
31.1Cursor in SQL
To execute SQL statements, a work area is used by the Oracle engine for its internal processing
and storing the information. This work area is private to SQL’s operations. The ‘Cursor’ is the
PL/SQL construct that allows the user to name the work area and access the stored information
in it.

31.2 Use of Cursor


The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike the
SQL commands which operate on all the rows in the result set at one time. Cursors are used
when the user needs to update records in a singleton fashion or in a row by row manner, in a
database table.
The Data that is stored in the Cursor is called the Active Data Set. Oracle DBMS has another
predefined area in the main memory Set, within which the cursors are opened. Hence the size of
the cursor is limited by the size of this pre-defined area.

Fig No 16 Cursor Function

UNIT-2 Page 79
KIT Ajeet Singh

31.3 Cursor Actions


Declare Cursor: A cursor is declared by defining the SQL statement that returns a result set.
Open: A Cursor is opened and populated by executing the SQL statement defined by the cursor.
Fetch: When the cursor is opened, rows can be fetched from the cursor one by one or in a block
to perform data manipulation.
Close: After data manipulation, close the cursor explicitly.
Deallocate: Finally, delete the cursor definition and release all the system resources associated
with the cursor.

31.4 Types of Cursors


Cursors are classified depending on the circumstances in which they are opened.

● Implicit Cursor: If the Oracle engine opened a cursor for its internal processing it is
known as an Implicit Cursor. It is created “automatically” for the user by Oracle when a
query is executed and is simpler to code.

● Explicit Cursor: A Cursor can also be opened for processing data through a PL/SQL
block, on demand. Such a user-defined cursor is known as an Explicit Cursor.
31.4.1 Explicit cursor
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row. A suitable name for the cursor.
General syntax for creating a cursor:

CURSOR cursor_name IS select_statement;

cursor_name – A suitable name for the cursor.

select_statement – A select query which returns multiple rows

31.4.2 How to use Explicit Cursor?


There are four steps in using an Explicit Cursor.

1. DECLARE the cursor in the Declaration section.


2. OPEN the cursor in the Execution Section.

UNIT-2 Page 80
KIT Ajeet Singh

3. FETCH the data from the cursor into PL/SQL variables or records in the Execution
Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
Syntax:
DECLARE variables;

records;

create a cursor;

BEGIN

OPEN cursor;

FETCH cursor;

process the records;

CLOSE cursor;
END;

32 SQL Trigger | Student Database

Trigger: A trigger is a stored procedure in database which automatically invokes whenever a


special event in the database occurs. For example, a trigger can be invoked when a row is
inserted into a specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name]

[before | after]

{insert | update | delete}

on [table_name]

[for each row]

[trigger_body]

UNIT-2 Page 81
KIT Ajeet Singh

Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the
trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired

32.1 BEFORE and AFTER of Trigger:


BEFORE triggers run the trigger action before the triggering statement is run.
AFTER triggers run the trigger action after the triggering statement is run.
Example:
Given Student Report Database, in which student marks assessment is recorded. In such schema,
create a trigger so that the total and average of specified marks is automatically inserted
whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.

Suppose the database Schema –


mysql> desc Student;

+-------+-------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+-------+-------------+------+-----+---------+----------------+

| tid | int(4) | NO | PRI | NULL | auto_increment |

| name | varchar(30) | YES | | NULL | |

| subj1 | int(2) | YES | | NULL | |

| subj2 | int(2) | YES | | NULL | |

| subj3 | int(2) | YES | | NULL | |

UNIT-2 Page 82
KIT Ajeet Singh

| total | int(3) | YES | | NULL | |

| per | int(3) | YES | | NULL | |

+-------+-------------+------+-----+---------+----------------+

7 rows in set (0.00 sec)

SQL Trigger to problem statement.

create trigger stud_marks

before INSERT

on

Student

for each row

set Student.total = Student.subj1 + Student.subj2 + Student.subj3, Student.per = Student.total *


60 / 100;

Above SQL statement will create a trigger in the student database in which whenever subjects
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.,

mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);

Query OK, 1 row affected (0.09 sec)

mysql> select * from Student;

+-----+-------+-------+-------+-------+-------+------+

| tid | name | subj1 | subj2 | subj3 | total | per |

+-----+-------+-------+-------+-------+-------+------+

| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |

+-----+-------+-------+-------+-------+-------+------+

UNIT-2 Page 83
KIT Ajeet Singh

1 row in set (0.00 sec)

In this way trigger can be creates and executed in the databases.

33 SQL | Procedures in PL/SQL


PL/SQL is a block-structured language that enables developers to combine the power of SQL
withproceduralstatements.
A stored procedure in PL/SQL is nothing but a series of declarative SQL statements which can
be stored in the database catalogue. A procedure can be thought of as a function or a method.
They can be invoked through triggers, other procedures, or applications on Java, PHP etc.
All the statements of a block are passed to Oracle engine all at once which increases processing
speed and decreases the traffic.

33.1 Advantages:

● They result in performance improvement of the application. If a procedure is being

called frequently in an application in a single connection, then the compiled version


of the procedure is delivered.

● They reduce the traffic between the database and the application, since the lengthy

statements are already fed into the database and need not be sent again and again
via the application.

● They add to code reusability, similar to how functions and methods work in other

languages such as C/C++ and Java.

33.2 Disadvantages:

● Stored procedures can cause a lot of memory usage. The database administrator

should decide an upper bound as to how many stored procedures are feasible for a
particular application.

● MySQL does not provide the functionality of debugging the stored procedures.

UNIT-2 Page 84
KIT Ajeet Singh

33.3 Syntax to create a stored procedure

SET ANSI_NULLS ON

GO
SET QUOTED_IDENTIFIER ON
GO

-- Comments --

CREATE PROCEDURE procedure_name


=,
=,
=

AS
BEGIN
-- Query --
END

GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE GetStudentDetails


@StudentID int = 0
AS
BEGIN

UNIT-2 Page 85
KIT Ajeet Singh

SET NOCOUNT ON;


SELECT FirstName, LastName, BirthDate, City, Country
FROM Students WHERE StudentID=@StudentID
END
GO

33.4 Syntax to modify an existing stored procedure

SET ANSI_NULLS ON

GO
SET QUOTED_IDENTIFIER ON
GO

-- Comments --

ALTER PROCEDURE procedure_name


=,
=,
=

AS
BEGIN
-- Query --
END

GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

UNIT-2 Page 86
KIT Ajeet Singh

ALTER PROCEDURE GetStudentDetails


@StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, City
FROM Students WHERE StudentID=@StudentID
END
GO

33.4 Syntax to drop a Procedure:

DROP PROCEDURE procedure_name

Example:
DROP PROCEDURE GetStudentDetails

UNIT-2 Page 87

You might also like